Spring Boot 2/Spring Security 5:无法获取OAUTH2令牌问题求助
解决Spring Boot 2 OAuth2令牌服务403 CSRF报错问题
嘿,我之前也踩过这个坑!这个CSRF Token has been associated to this client的报错,本质是你的OAuth2客户端配置里开启了CSRF保护,但请求时没提供对应的令牌,或者你的客户端类型根本不需要CSRF保护。下面给你几个针对性的解决方案:
1. 给机密客户端关闭CSRF(最适合你的场景)
看你用的是password授权模式,还带了client:secret的客户端凭证,这属于机密客户端(比如后端服务调用),这种客户端完全不需要CSRF保护。你只需要在AuthorizationServer的配置里,给这个客户端单独关闭CSRF:
@Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("client") .secret("{noop}secret") // 注意:Spring Boot 2要求密码带编码器前缀,noop是明文示例,生产用BCrypt的话换{bcrypt} .authorizedGrantTypes("password") .scopes("read", "write") .csrfDisabled(true); // 关键:给这个客户端关闭CSRF校验 } // 别忘了配置AuthenticationManager、TokenStore这些必要组件哦 @Autowired private AuthenticationManager authenticationManager; @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authenticationManager(authenticationManager); } }
2. 临时全局关闭CSRF(仅用于测试)
如果你只是想快速验证是不是CSRF的问题,可以全局关闭AuthorizationServer的CSRF保护,不过生产环境别这么干,风险太高:
@Override public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { security .tokenKeyAccess("permitAll()") .checkTokenAccess("isAuthenticated()") .allowFormAuthenticationForClients() .csrfDisabled(true); // 全局关闭CSRF }
3. 检查请求格式和参数
再确认下你的curl请求是不是正确的,必须是POST方法,参数用x-www-form-urlencoded格式:
curl client:secret@localhost:8080/oauth/token -d "grant_type=password&username=你的用户名&password=你的密码"
如果请求里不小心带了CSRF的Cookie但没提交_csrf参数,也会触发这个报错,这种情况可以清空Cookie再试。
最后提个小细节:Spring Boot 2里的密码编码器一定要配置对,比如用BCrypt的话,要在配置类里注入PasswordEncoder,并把客户端密码换成加密后的字符串,前缀加{bcrypt}。
内容的提问来源于stack exchange,提问作者Adeynack
相关产品推荐
相关产品推荐

