@Bean @ConditionalOnMissingBean(UserProvider.class) public UserProvider userProvider() { return () -> { final HttpServletRequest request = HttpServletRequestHolder.get(); final Optional<Credentials> credentials = Credentials.readFrom(request); final boolean isAdmin = true; // "admin".equals(username); return new SimpleFeatureUser((credentials.isPresent() ? credentials.get().getUsername() : null), isAdmin); }; }
@Override protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, final FilterChain filterChain) throws ServletException, IOException { Optional<Credentials> optionalCredentials = readFrom(request); if (optionalCredentials.isPresent()) { final Optional<HttpServletRequest> authRequest = tryToGetAuthenticatedRequest(request, optionalCredentials.get()); if (authRequest.isPresent()) { filterChain.doFilter(authRequest.get(), response); } else { unauthorized(response); } } else { unauthorized(response); } }
@Test public void shouldReturnEmptyCredentialsIfHeaderDoesNotExist() { // when final Optional<Credentials> credentials = Credentials.readFrom(httpServletRequest); // then assertThat(credentials.isPresent(), is(false)); }
@Test public void shouldReturnEmptyCredentialsIfPasswordNotSet() { // given mockHttpServletRequestWithAuthentication("someUsername:"); // when final Optional<Credentials> credentials = Credentials.readFrom(httpServletRequest); // then assertThat(credentials.isPresent(), is(false)); }
@Test public void shouldReturnEmptyCredentialsIfUsernameNotSet() { // given mockHttpServletRequestWithAuthentication(":password"); // when final Optional<Credentials> credentials = Credentials.readFrom(httpServletRequest); // then assertThat(credentials.isPresent(), is(false)); }
@Test public void shouldReturnCorrectCredentialsIfPasswordContainsColons() { // given mockHttpServletRequestWithAuthentication("user:pass:word"); // when final Optional<Credentials> credentials = Credentials.readFrom(httpServletRequest); // then assertThat(credentials.isPresent(), is(true)); assertThat(credentials.get().getUsername(), is("user")); assertThat(credentials.get().getPassword(), is("pass:word")); } }
@Test public void shouldBeAbleToReadCredentialsFromRequest() { // given mockHttpServletRequestWithAuthentication("someUsername:somePassword"); // when final Optional<Credentials> credentials = Credentials.readFrom(httpServletRequest); // then assertThat(credentials.isPresent(), is(true)); assertThat(credentials.get().getUsername(), is("someUsername")); assertThat(credentials.get().getPassword(), is("somePassword")); }