Description
Hey! I followed your blog to implement JWT with spring security but i am running into problem when using @secured("IS_AUTHENTICATED_ANONYMOUSLY") at controller action. It is not working there. what i want is to protect everything except some actions but when doing this getting 401 error. I am not passing any "Authorization" header. here is my config:
@OverRide
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/",
"/favicon.ico",
"//*.png",
"//.gif",
"/**/.svg",
"//*.jpg",
"//.html",
"/**/.css",
"//*.js")
.permitAll()
.antMatchers("/v2/api-docs", "/configuration/", "/swagger*/", "/webjars/")
.permitAll()
.antMatchers("/", "/assets/", "/swagger-ui.html")
.permitAll()
.antMatchers("/api/auth/")
.permitAll()
.anyRequest()
.authenticated();
http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
and below is jwtAuthentication filter
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
try {
String jwt = getJwtFromRequest(request);
if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) {
Long userId = tokenProvider.getUserIdFromJWT(jwt);
UserDetails userDetails = userDetailsService.loadUserById(userId);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
} catch (Exception ex) {
log.error("Could not set user authentication in security context", ex);
}
filterChain.doFilter(request, response);
}
please help.