Postman Spring Security OAuth 2 中 GET 请求上的 403 禁止错误

问题描述

在 Postman 中点击 GET 请求时,我一直收到 403 Forbidden Error。我在 Spring Security 中使用 OAuth。

下面是我的代码

授权服务器配置

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        clients
                .inMemory()
                .withClient("ClientId")
                .secret("secret")
                .authorizedGrantTypes("client_credentials","password")
                .scopes("user_info")
                .autoApprove(true);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager);
    }

}

资源服务器配置

@EnableResourceServer
@Configuration
public class ResourceServerConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserDetailsService customUserDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
   
         http.csrf().disable();
         http.authorizeRequests()
                .antMatchers("/rest/register").permitAll()
                .antMatchers("**/rest/hello/**").hasRole("ADMIN")
                .anyRequest().authenticated();

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.parentAuthenticationManager(authenticationManager)
                .userDetailsService(customUserDetailsService);
    }

}

我的 REST 端点

@RestController
@RequestMapping("/rest/hello")
public class HelloResource {

    @GetMapping("/principal")
    public Principal user(Principal principal) {
        return principal;
    }

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/helloworld")
    public String hello() {
        return "Hello World";
    }

}

我什至禁用了 csrf

http.csrf().disable();

不知道怎么回事。每次它都会给出 403 Forbidden 错误。我已经尝试了很多东西,但仍然每次都会出现 403 错误

这是我点击的 GET 请求

http://localhost:8081/auth/rest/hello/helloworld

我收到以下错误

{
    "timestamp": 1613757523622,"status": 403,"error": "Forbidden","message": "Access Denied","path": "/auth/rest/hello/helloworld"
}

请帮我解决这个问题。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)