I was using spring security to handle authentication via jwt that is passed in the request`s header:
public class JwtAuthConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.anyRequest().authenticated().and()
.oauth2ResourceServer().jwt();
}
}
Now the JWT token is passed to my application in a cookie. I wrote a filter that takes the jwt from the cookie and adds it to the request`s header :
@Component
public class JwtCookieFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse)res;
Cookie[] cookies = request.getCookies();
String jwt = this.getTokenFromCookie(cookies); // Inner method
if(jwt == null)
{
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
HttpRequestWithHeaders requestWithHeaders = new HttpRequestWithHeaders (request);
HttpRequestWithHeaders .addHeader("Authorization",jwt);
chain.doFilter(requestWithHeaders, response);
}
Now I'm not sure after what step my filter should run (configure method in springSecurity). I tried using the following but I keep getting 401 error (Unathorized) :
http.addFilterBefore(new JwtCookieFilter(), UsernamePasswordAuthenticationFilter.class);