Reputation: 2171
What I'm trying to accomplish is a jwt token-based authentication for my rest api. Everything under /api should only be accessible with a token.
I have the following configure method in my web security configuration:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authenticationProvider(authenticationProvider())
.csrf().disable()
.authorizeRequests().antMatchers("/api/**").authenticated()
.and()
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint())
.and()
.addFilterBefore(authenticationFilter(),BasicAuthenticationFilter.class)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
And this is the filter:
public class JwtAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
public JwtAuthenticationFilter(AuthenticationManager manager) {
super("/api/**");
this.setAuthenticationManager(manager);
}
@Override
protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
return true;
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith("Bearer ")) {
throw new JwtTokenMissingException("No JWT token found in request headers");
}
String authToken = header.substring(7);
JwtAuthenticationToken authRequest = new JwtAuthenticationToken(authToken);
return getAuthenticationManager().authenticate(authRequest);
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult)
throws IOException, ServletException {
super.successfulAuthentication(request, response, chain, authResult);
chain.doFilter(request, response);
}
}
My problem is that the filter is now applied to every url, not just the ones with the /api prefix.
I'm aware of the fact that my "configure" method might be wrong, but what should it look like? All I want to accomplish is to use the filter for the /api path.
+1 question: why are there two values to configure the path to which the filter will be applied? (once as a parameter to the antMatchers method in the configuration, and then a constructor argument "filterProcessesUrl" for AbstractAuthenticationProcessingFilter). How do these values relate to each other, and which one should I use?
Upvotes: 2
Views: 1482
Reputation: 2171
The problem was this part:
@Override
protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
return true;
}
I copied it and never realised it was there.
Upvotes: 1