BasicAuthFilter implements Filter { @Override public Result filter(FilterChain chain, Context context) { if (context.getSession() == null) { return ninja.getUnauthorizedResult(context); } else if (context.getSession().get(SecureFilter.USERNAME) == null) { String header = context.getHeader("Authorization"); if (header != null && header.startsWith("Basic")) { String packet = header.substring("Basic".length()).trim(); String credentials = new String(Base64.decodeBase64(packet), Charset.forName(NinjaConstant.UTF_8)); final String[] values = credentials.split(":", 2); final String username = values[0]; final String password = values[1]; if (credentialsValidator .validateCredentials(username, password)) { context.getSession().put(SecureFilter.USERNAME, username); return chain.next(context); } } Result result = ninja.getUnauthorizedResult(context).addHeader( Result.WWW_AUTHENTICATE, challenge); return result; } else { return chain.next(context); } } @Inject  BasicAuthFilter(Ninja ninja,
                           NinjaProperties ninjaProperties,
                           UsernamePasswordValidator validator); @Override Result filter(FilterChain chain, Context context);  }
@Test public void testNullSession() { when(context.getSession()).thenReturn(null); basicAuthFilter.filter(filterChain, context); verifyZeroInteractions(filterChain); }
@Test public void testUnauthenticatedSession() { when(context.getSession()).thenReturn(sessionCookie); when(sessionCookie.get(SecureFilter.USERNAME)).thenReturn(null); when(result.getTemplate()).thenReturn( NinjaConstant.LOCATION_VIEW_FTL_HTML_UNAUTHORIZED); Result result = basicAuthFilter.filter(filterChain, context); assertEquals(NinjaConstant.LOCATION_VIEW_FTL_HTML_UNAUTHORIZED, result.getTemplate()); verifyZeroInteractions(filterChain); }
@Test public void testWorkingSessionWhenUsernameIsThere() { when(context.getSession()).thenReturn(sessionCookie); when(sessionCookie.get(SecureFilter.USERNAME)).thenReturn("myname"); basicAuthFilter.filter(filterChain, context); verify(filterChain).next(context); }
@Test public void testSessionIsNotReturingWithInvalidCredentials() { when(context.getSession()).thenReturn(sessionCookie); when(sessionCookie.get(SecureFilter.USERNAME)).thenReturn(null); when(result.getTemplate()).thenReturn( NinjaConstant.LOCATION_VIEW_FTL_HTML_UNAUTHORIZED); when(context.getHeader("Authorization")).thenReturn( auth("test", "user")); Result result = basicAuthFilter.filter(filterChain, context); assertEquals(NinjaConstant.LOCATION_VIEW_FTL_HTML_UNAUTHORIZED, result.getTemplate()); verifyZeroInteractions(filterChain); }
@Test public void testSessionIsReturningWithValidCredentials() { when(context.getSession()).thenReturn(sessionCookie); when(sessionCookie.get(SecureFilter.USERNAME)).thenReturn(null); when(context.getHeader("Authorization")).thenReturn( auth("james", "bond")); basicAuthFilter.filter(filterChain, context); verify(filterChain).next(context); }