Spring Cloud集成Oauth2踩坑:报401错/Unsupported grant type
整合Oauth时的踩坑记录
·
目录
在springcloud集成Oauth2的时候调用
/oauth/token去获取token时密码模式和授权模式分别报错报401和Unsupported grant type:
关键代码:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin")
.password(passwordEncoder().encode("123456"))
.roles("USER","ADMIN")
.authorities(AuthorityUtils.commaSeparatedStringToAuthorityList("p1,p2"));
//这里配置全局用户信息
}
}
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
PasswordEncoder passwordEncoder;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//基于内存便于测试
clients.inMemory()// 使用in-memory存储
.withClient("auth")// client_id
//.secret("secret")//未加密
.secret(this.passwordEncoder.encode("secret"))//加密
//.resourceIds("res1")//资源列表
.authorizedGrantTypes("authorization_code", "password", "client_credentials", "implicit", "refresh_token")// 该client允许的授权类型authorization_code,password,refresh_token,implicit,client_credentials
.scopes("all", "ROLE_ADMIN", "ROLE_USER")// 允许的授权范围
//.autoApprove(false)//false跳转到授权页面
//加上验证回调地址
.redirectUris("http://baidu.com");
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.allowFormAuthenticationForClients()
.passwordEncoder(new BCryptPasswordEncoder()); //2.第二处
}
}
问题1:授权码模式报401
错误截图:unauthrized:
解决方案如下:
问题2:授权码模式报密码模式时报:o.s.s.o.provider.endpoint.TokenEndpoint : Handling error: UnsupportedGrantTypeException, Unsupported grant type
错误截图:
解决方案如下:
一直认为是我的grant_type设置不对,去打断点的时候一直只能获取到authorization_code一个,而找不到列表里面的password和我的参数匹配,就反应过来应该是哪里少了配置,查阅资料才发现需要加上AuthenticationManager
需要在 AuthorizationServerConfig中加上如下代码:
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
AuthenticationManager authenticationManager;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
super.configure(endpoints);
endpoints.authenticationManager(authenticationManager);
}
}
如果出现启动时找不到AuthenticationManager这个bean,需要去WebSecurityConfig里实例化一下
/**
* 重新实例化bean
*/
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
加上之后成功获取到
更多推荐
已为社区贡献1条内容
所有评论(0)