When you execute context.setAuthentication(authentication)
the authentication is only valid for the current request. So for the second /me
request you need to set the authentication as well.
Therefore you need to authenticate the user on a per-request base. That can be done by implementing a GenericFilterBean
:
public class CustomAuthenticationFilter extends GenericFilterBean {
private final AuthenticationManager authenticationManager;
public CustomAuthenticationFilter(
AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
/*
Note that you need to receive the authentication token in different manner now.
Usually headers are used for that.
*/
Authentication authenticate = authenticationManager.authenticate(request.getHeader("authToken"));
SecurityContext context = SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(request, response);
}
}
After implementing the filter you need to register it in the servlet container at the position where it is best suited. Spring Security handles the security filters per WebsecutiryConfigurer
, so you need to register your filter in the config of the respective configurer of your users.
As an example I put it after ConcurrentSessionFilter
:
@Configuration
@Order(1)
public static class UserWebSecurity extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
CustomAuthenticationFilter filter = new PlayerAuthenticationFilter(jwtService,
objectMapper);
http.addFilterAfter(filter, ConcurrentSessionFilter.class);
(...)
}
}
Check out the documentation about filter ordering to find the position best suited for your method.
Update
I wrote a more in-depth blog post about this topic. Fell free to check it out.