JaasAuthenticator extends BasicAuthenticator { @Override public Result authenticate(HttpExchange pHttpExchange) { try { Result result = super.authenticate(pHttpExchange); if (result instanceof Success) { Subject subject = subjectThreadLocal.get(); if (subject != null) { pHttpExchange.setAttribute(ConfigKey.JAAS_SUBJECT_REQUEST_ATTRIBUTE, subject); } } return result; } finally { subjectThreadLocal.remove(); } } JaasAuthenticator(String pRealm); @Override Result authenticate(HttpExchange pHttpExchange); @Override boolean checkCredentials(String pUser, String pPassword);  }
@Test public void testAuthenticateNoAuthorizationHeader() throws Exception { Headers respHeader = new Headers(); HttpExchange ex = createHttpExchange(respHeader); Authenticator.Result res = auth.authenticate(ex); assertEquals(((Authenticator.Retry) res).getResponseCode(),401); assertTrue(respHeader.containsKey("WWW-Authenticate")); assertTrue(respHeader.getFirst("WWW-Authenticate").contains("jolokia")); }
@Test public void testAuthenticateNoLoginModules() throws Exception { Headers respHeader = new Headers(); HttpExchange ex = createHttpExchange(respHeader, "Authorization", "Basic cm9sYW5kOnMhY3IhdA=="); Authenticator.Result result = auth.authenticate(ex); assertEquals(((Authenticator.Failure) result).getResponseCode(), 401); }
@Test public void testAuthenticateSuccess() throws Exception { Headers respHeader = new Headers(); final Subject subject = new Subject(); HttpExchange ex = createHttpExchange(respHeader, subject, "Authorization", "Basic cm9sYW5kOnMhY3IhdA=="); JaasAuthenticator successAuth = new JaasAuthenticator("jolokia") { @Override protected LoginContext createLoginContext(String realm, CallbackHandler handler) throws LoginException { LoginContext mockLogin = EasyMock.mock(LoginContext.class); mockLogin.login(); expect(mockLogin.getSubject()).andReturn(subject); EasyMock.replay(mockLogin); return mockLogin; } }; Authenticator.Result result = successAuth.authenticate(ex); HttpPrincipal principal = ((Authenticator.Success) result).getPrincipal(); assertEquals(principal.getRealm(),"jolokia"); assertEquals(principal.getUsername(),"roland"); }