Recipe 22.5. Applying a Security PolicyProblemYou want to add security considerations to areas of an existing application. SolutionDefine an aspect that specifies join points within your application that need to be subjected to additional security. When those join points are encountered, store and authenticate against a specific security implementation within the aspect, as shown in Example 22-10. Example 22-10. Applying authentication to calls on a specific classpublic aspect SecureClassAAspect { private boolean authenticated; public pointcut secureClassAMethods( ) : call(* com.oreilly.aspectjcookbook.ClassA.*(..)); Object around( ) : secureClassAMethods( ) { if (authenticated) { return proceed( ); } else { LoginScreen loginScreen = new LoginScreen( ); loginScreen.setVisible(true); // Use the authentication procedure of your choice here // In this simple example we are just going to check that // it is the one person we know of if ((loginScreen.getUsername( ).equals("Kim")) && (new String(loginScreen.getPassword( )).equals("password"))) { authenticated = true; loginScreen.dispose( ); return proceed( ); } loginScreen.dispose( ); return null; } } } DiscussionSecurity is an ideal example of a cross-cutting concern. Security characteristics rarely have anything to do with the simple business logic of an application. They are often intrusive and, unfortunately, the last thing to be applied to a piece of software. In Example 22-10, the aspect captures when any method on the ClassA class is called and checks to see if the current user is authenticated to run those methods. In this example, authentication takes the form of displaying a login dialog comparing the username and password with some internally stored constants. Once the user has been recognized, the aspect's authenticated attribute is set to remember that no future checks are necessary as the application calls other methods on instances of ClassA.
By applying security with aspects, you can modularize your security code in one place, apply the security policies transparently to a large degree, and apply security to an application where the concern was not originally part of the design. See AlsoJava Security by Scott Oaks (O'Reilly) goes into more detail on how to use JAAS and Java's other security features in your applications; the call(Signature) pointcut is described in Recipe 4.1; the around( ) form of advice is covered in Recipe 13.4. |