Simple JAAS programming
The JAAS-enabled code is partitioned into two groups: the setup code and the user-specific code.
The JAAS Setup Code
The setup code looks like this:
package javasec.samples.ch15; import javax.security.auth.*; import javax.security.auth.callback.*; import javax.security.auth.login.*; public class CountFiles { static class NullCallbackHandler implements CallbackHandler { public void handle(Callback[] cb) { throw new IllegalArgumentException("Not implemented yet"); } } static LoginContext lc = null; public static void main(String[] args) { // use the configured LoginModules for the "CountFiles" entry try { lc = new LoginContext("CountFiles", new NullCallbackHandler( )); } catch (LoginException le) { le.printStackTrace( ); System.exit(-1); } // log in the user try { lc.login( ); // if we return with no exception, authentication succeeded } catch (Exception e) { System.out.println("Login failed: " + e); System.exit(-1); } // now execute the code as the authenticated user Object o = Subject.doAs(lc.getSubject(), new CountFilesAction( )); System.out.println("User " + lc.getSubject( ) + " found " + o + " files."); System.exit(0); } }
There are three important steps here: first, we construct a
LoginContext
object; second, we use that object
to log in a user; and third, we pass that user as one of the
parameters to the doAs( )
method.
The LoginContext class
The first two of these activities are based on the
LoginContext
class (javax.security.auth.login.LoginContext ...
Get Java Security, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.