I am working on a Spring Boot Service, which is receiving JWT Token generated in another service in the request header. My goal is to verify the validity of the JWT Token in my Spring Boot Application.
After researching a while I've decided to use WebSecurityConfig from Spring Security and to have some kind of a middleware which is actually a filter.
I have configured the filter to be applied not on all request that are defined in my application. But regardless of this the filter is applied on requests that are configured as permitAll().
I am totally confused by this all and can't figure out what I am missing. Finally I have decided to ask for help. Please help.
Here is my code.
Security config:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
JWTAuthenticationFilter jwtAuthenticationFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/req").permitAll()
.and()
.authorizeRequests()
.anyRequest().authenticated()
.and()
// And filter other requests to check the presence of JWT in header
.addFilterBefore(jwtAuthenticationFilter,
BasicAuthenticationFilter.class);
}
@Override
public void configure(WebSecurity webSecurity) {
webSecurity
.ignoring()
.antMatchers("/req");
}
}
Filter:
@Component
public class JWTAuthenticationFilter extends GenericFilterBean {
@Autowired
TokenAuthenticationService tokenAuthenticationService = new TokenAuthenticationService();
@Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain filterChain)
throws IOException, ServletException {
boolean authentication = tokenAuthenticationService
.getAuthentication((HttpServletRequest)request);
if (!authentication) {
((HttpServletResponse) response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
filterChain.doFilter(request,response);
}
}
Authentication Service:
@Component
class TokenAuthenticationService {
@Value("${security.authentication.token.secret}")
private String SECRET;
@Value("${security.authentication.token.token_prefix}")
private String TOKEN_PREFIX;
@Value("${security.authentication.token.header_string}")
private String HEADER_STRING;
boolean getAuthentication(HttpServletRequest request) throws UnsupportedEncodingException {
String token = request.getHeader(HEADER_STRING);
if (token != null) {
// parse the token.
DecodedJWT jwt;
try {
Algorithm algorithm = Algorithm.HMAC256(SECRET);
JWTVerifier verifier = JWT.require(algorithm)
.build(); //Reusable verifier instance
jwt = verifier.verify(token);
return true;
} catch (UnsupportedEncodingException exception){
//UTF-8 encoding not supported
UnsupportedEncodingException ex = exception;
return false;
} catch (JWTVerificationException exception){
//Invalid signature/claims
JWTVerificationException ex = exception;
return false;
}
}
return false;
}
}