解决方案:
- 首先检查WebSecurityConfigurerAdapter是否配置正确
@Configuration public class OAuth2ResourceServerConfigurer extends ResourceServerConfigurerAdapter { @Autowired private TokenStore tokenStore; @Override public void configure(HttpSecurity http) throws Exception { http //白名单 .authorizeRequests() .antMatchers(UserConstants.WHITE_LIST).permitAll() //包含资源权限才可以 .anyRequest().authenticated() .and() .csrf().disable() .headers().frameOptions().disable(); } // 。。。 }
- 其次再检查AuthorizationServerConfigurerAdapter中配置的请求方式(如果你想用get获得请求的话)
@Configuration public class OAuth2AuthorizationServer extends AuthorizationServerConfigurerAdapter { @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) { DefaultAccessTokenConverter defaultAccessTokenConverter = new DefaultAccessTokenConverter(); defaultAccessTokenConverter.setUserTokenConverter(new AuthenticationConverter()); endpoints.authenticationManager(authenticationManager) .tokenStore(tokenStore()) .accessTokenConverter(defaultAccessTokenConverter) .userDetailsService(userDetailsService) // 默认只有POST,这里要加入需要的请求方式 .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT,HttpMethod.DELETE, HttpMethod.OPTIONS) .exceptionTranslator(exceptionTranslator()); } //..... }
- 再检查你的实际请求千万别用post-json的方式,详情可以看下org.springframework.security.oauth2.provider.endpoint.TokenEndpoint中的源码,里面对/oauth/token只支持到了get和post表单方式。
- 如果非想用post-json方式,可以自己拓展,可以参考:springsecurity oauth2 json传参获取token_ljx476617740的博客-CSDN博客,思路就是接完json参数,再重新封装Principal和Map参数
- 如果自己重写登录接口的话,建议:获取token接口不要使用/oauth/token这个路径,否则在某些oauth2版本中也会弹框