Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Method level annotations not working #35

Open
jain-arpit opened this issue Jun 18, 2020 · 0 comments
Open

Method level annotations not working #35

jain-arpit opened this issue Jun 18, 2020 · 0 comments

Comments

@jain-arpit
Copy link

jain-arpit commented Jun 18, 2020

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant