JwtAuthenticationFilter extends AbstractAuthenticationProcessingFilter { @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { String header = request.getHeader("Authorization"); if (header == null || !header.startsWith("Bearer ")) { throw new BadCredentialsException("No JWT token found in request headers, header: " + header); } String[] tokens = header.split(" "); if (tokens.length != 2) { throw new BadCredentialsException("Wrong authentication header format: " + header); } return new UsernamePasswordAuthenticationToken(tokens[0], tokens[1]); } JwtAuthenticationFilter(); @Override Authentication attemptAuthentication(HttpServletRequest request,
      HttpServletResponse response);  }
@Test public void nullHeader() throws Exception { when(request.getHeader("Authorization")).thenReturn(null); assertThatThrownBy(() -> filter.attemptAuthentication(request, null)) .isInstanceOf(BadCredentialsException.class); }
@Test public void notBearer() throws Exception { when(request.getHeader("Authorization")).thenReturn("foo bar"); assertThatThrownBy(() -> filter.attemptAuthentication(request, null)) .isInstanceOf(BadCredentialsException.class); }
@Test public void wrongFormat() throws Exception { when(request.getHeader("Authorization")).thenReturn("foo bar foo"); assertThatThrownBy(() -> filter.attemptAuthentication(request, null)) .isInstanceOf(BadCredentialsException.class); }
@Test public void correctHeader() throws Exception { when(request.getHeader("Authorization")).thenReturn("Bearer bar"); Authentication authentication = filter.attemptAuthentication(request, null); assertThat(authentication.getPrincipal().toString()).isEqualTo("Bearer"); assertThat(authentication.getCredentials().toString()).isEqualTo("bar"); }