【问题标题】:Spring security + JWT 403 forbidden errorSpring security + JWT 403 禁止错误
【发布时间】:2020-07-31 20:20:48
【问题描述】:

所以,我正在尝试使用 SpringSecurity 和 JWT 令牌来保护 api。我可以获得令牌,但每次我尝试使用令牌访问受保护的端点时,我都会得到 403 Forbidden。我有一个包含角色和用户的数据库。 这是我的春季安全配置:

 httpSecurity.csrf().disable().cors().disable()
            // dont authenticate this particular request
            .authorizeRequests().antMatchers("/authenticate", "/register").permitAll()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .antMatchers("/system/**").hasRole("ADMIN")
            //.antMatchers("/system").permitAll()
            // all other requests need to be authenticated
                    //.anyRequest().permitAll()
            .and().
            // make sure we use stateless session; session won't be used to
            // store user's state.
                    exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    // Add a filter to validate the tokens with every request
    httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);

我试了调试,可以解码token,可以访问用户信息,可以得到一个包含角色的用户对象。这就是为什么我真的不知道发生了什么。

这是我在 RequestFilter 类中的过滤方法:

String username = null;
String jwtToken = null;
// JWT Token is in the form "Bearer token". Remove Bearer word and get
// only the Token
if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
    jwtToken = requestTokenHeader.substring(7);
    try {
        username = jwtTokenUtil.getUsernameFromToken(jwtToken);
    } catch (IllegalArgumentException e) {
        System.out.println("Unable to get JWT Token");
    }
} else {
    logger.warn("JWT Token does not begin with Bearer String");
}       // Once we get the token validate it.
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {           UserDetails userDetails = this.jwtUserDetailsService.loadUserByUsername(username);          // if token is valid configure Spring Security to manually set
    // authentication
    if (jwtTokenUtil.validateToken(jwtToken, userDetails)) {                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
            userDetails, null, userDetails.getAuthorities());
        usernamePasswordAuthenticationToken
                .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        // After setting the Authentication in the context, we specify
        // that the current user is authenticated. So it passes the
        // Spring Security Configurations successfully.
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
    }
}
chain.doFilter(request, response);

抱歉这么长的消息:)

【问题讨论】:

    标签: spring security jwt


    【解决方案1】:

    您需要在SimpleGrantedAuthority 前加上ROLE_。
    在您的 UserDetailsService 中添加类似的内容。

    String ROLE_PREFIX = "ROLE_";
    authorities.add(new SimpleGrantedAuthority(ROLE_PREFIX + user.getRole()));
    

    【讨论】:

    • 并将 hasRole("ADMIN") 保留在 securityconfig 中?
    • 仍然,我得到 403
    【解决方案2】:

    在您的安全配置中,而不是:

        hasRole("ADMIN")
    

    尝试:

        hasAuthority("ROLE_ADMIN")
    

    【讨论】:

      猜你喜欢
      • 2020-12-18
      • 2017-11-11
      • 2018-12-24
      • 2018-10-31
      • 2020-04-20
      • 2015-08-16
      • 2015-07-24
      • 2018-01-14
      • 2020-10-10
      相关资源
      最近更新 更多