Spring security + JWT 403禁止访问错误

4

我正在尝试使用SpringSecurity和JWT令牌来保护API。我可以获取令牌,但每次尝试使用令牌访问受保护的端点时,都会收到403 Forbidden的错误。我有一个包含角色和用户信息的数据库。 这是我的Spring Security配置:

 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);

我尝试进行调试,令牌可以被解码,访问用户信息并获得包含角色的用户对象。这就是为什么我真的不知道发生了什么。

调试变量:

下面是来自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);

抱歉这条消息有点长 :)

2个回答

7
你需要给SimpleGrantedAuthority加上ROLE_前缀。
在你的UserDetailsService中添加类似以下的内容。
String ROLE_PREFIX = "ROLE_";
authorities.add(new SimpleGrantedAuthority(ROLE_PREFIX + user.getRole()));

1
在securityconfig中保留hasRole("ADMIN")吗? - Aymane EL Jahrani
仍然出现403错误。 - Aakarsh Gupta

1
在您的安全配置中,不要使用以下方式:
    hasRole("ADMIN")

尝试:

    hasAuthority("ROLE_ADMIN")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接