Spring security always returns HTTP 403

前端 未结 7 2124
逝去的感伤
逝去的感伤 2020-12-28 17:07

I have configured a custom Filter that grants a spring authority for every URL other than /login :

public class TokenFilter impleme         


        
7条回答
  •  北荒
    北荒 (楼主)
    2020-12-28 17:44

    I know that this is a very old question but I just had the same error and I didn't find any solution on the internet.
    It is correct that 403 means that the user is authenticated but not authorized to get a resource. This is related to the claims part in your JWT.
    Your JWT builder needs to set proper claims for the user :

    List grantedAuthorities = AuthorityUtils
                    .commaSeparatedStringToAuthorityList("ROLE_USER");
    
    Jwts.builder()//
                    .setIssuer(...)//
                    .setSubject(...)//
                    .setAudience(...)
    
                    // This is the part that you missed
    
                    .claim("authorities",
                            grantedAuthorities.stream()
                            .map(GrantedAuthority::getAuthority)
                            .collect(Collectors.toList()))
    
                    // Ends here
    
                    .setIssuedAt(date)//
                    .setExpiration(new Date(date.getTime() + jwtExpirationMs))
                    .signWith(SignatureAlgorithm.HS512, signingKey)//
                    .compact();
    

    My WebSecurity configuration :

    public class WebSecurity extends WebSecurityConfigurerAdapter {
    
    ...
    
    @Override
        protected void configure(HttpSecurity http) throws Exception {
    
            http.cors().and().csrf().disable()//
                    .authorizeRequests()//
                    .antMatchers(...).permitAll()//
                    .anyRequest().authenticated()
                    .and()
                    .sessionManagement()//
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
            http.addFilterAfter(authenticationJwtTokenFilter(), BasicAuthenticationFilter.class);
        }
    

提交回复
热议问题