private Subject authenticate ( HttpServletRequest req ) { String authorization = req . getHeader ( "authorization" ) ; if ( authorization == null || authorization . trim ( ) . isEmpty ( ) ) { return null ; } // subject from session instead of re-authenticating // can't change username/password for this session. Subject subject = ( Subject ) req . getSession ( ) . getAttribute ( authorization ) ; if ( subject != null ) { return subject ; } String auth = null ; try { byte [ ] data = Base64 . decode ( authorization . substring ( 6 ) ) ; auth = new String ( data ) ; } catch ( IOException e ) { logger . error ( e . toString ( ) ) ; return null ; } String username = auth . substring ( 0 , auth . indexOf ( ' ' ) ) ; String password = auth . substring ( auth . indexOf ( ' ' ) + 1 ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "auth username: " + username ) ; } LoginContext loginContext = null ; try { CallbackHandler handler = new UsernamePasswordCallbackHandler ( username , password ) ; loginContext = new LoginContext ( jaasConfigName , handler ) ; loginContext . login ( ) ; } catch ( LoginException le ) { logger . error ( le . toString ( ) ) ; return null ; } // successfully logged in subject = loginContext . getSubject ( ) ; // object accessable by a fixed key for usage req . getSession ( ) . setAttribute ( SESSION_SUBJECT_KEY , subject ) ; // object accessable only by base64 encoded username:password that was // initially used - prevents some dodgy stuff req . getSession ( ) . setAttribute ( authorization , subject ) ; return subject ; }
Performs the authentication . Once a Subject is obtained it is stored in the users session . Subsequent requests check for the existence of this object before performing the authentication again .