Spring Cloud集成Oauth2踩坑:报401错/Unsupported grant type

3 篇文章 0 订阅

目录

关键代码:

问题1:授权码模式报401

错误截图:unauthrized:

解决方案如下:

问题2:授权码模式报密码模式时报:o.s.s.o.provider.endpoint.TokenEndpoint  : Handling error: UnsupportedGrantTypeException, Unsupported grant type

错误截图: 

解决方案如下:


在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:

解决方案如下:

反复检查了我的代码和参数,察觉到我的请求都没有到达接口就已经返回了401的错误,那么一定是我的参数有问题,检查了不下十遍,在这里卡了两天,终于发现自己踩坑在哪里!!!朋友们authorization里面的参数不是账号密码啊。。。是代码里设置的client_id和secret !!!

问题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();
    }

 加上之后成功获取到

Spring Cloud集成OAuth2密码模式需要进行以下步骤: 1. 添加依赖 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-oauth2</artifactId> </dependency> ``` 2. 配置授权服务器 在application.yml文件中配置OAuth2授权服务器: ``` server: port: 9090 spring: security: oauth2: client: client-id: client client-secret: secret access-token-uri: http://localhost:8080/oauth/token user-authorization-uri: http://localhost:8080/oauth/authorize resource: user-info-uri: http://localhost:8080/user ``` 3. 配置安全配置 在SecurityConfig中配置安全配置: ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/oauth/**").permitAll() .anyRequest().authenticated() .and() .formLogin().permitAll() .and() .csrf().disable(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user").password("{noop}password").roles("USER"); } @Bean public PasswordEncoder passwordEncoder() { return NoOpPasswordEncoder.getInstance(); } } ``` 4. 配置资源服务器 在ResourceServerConfig中配置资源服务器: ``` @Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { http.authorizeRequests().anyRequest().authenticated(); } @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.resourceId("resource"); } } ``` 5. 测试 使用Postman等工具发送POST请求到http://localhost:9090/oauth/token,请求参数如下: ``` grant_type:password username:user password:password client_id:client client_secret:secret ``` 如果授权成功,会返回access_token,使用access_token发送GET请求到http://localhost:9090/user,即可获取用户信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值