callicoder / spring-security-react-ant-design-polls-app

Full Stack Polls App built using Spring Boot, Spring Security, JWT, React, and Ant Design
https://www.callicoder.com/spring-boot-spring-security-jwt-mysql-react-app-part-1/
1.77k stars 1.07k forks source link

Method level annotations not working #35

Open jain-arpit opened 4 years ago

jain-arpit commented 4 years ago

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.