OAuth2中访问/oauth2/token报invalid_client问题的解决办法

遇到的问题:在使用postman调/oauth2/token这个接口的时候,报invalid_client。

解决的方案:

我在网上看了好多解决办法都没能解决我遇到的问题,于是我打开源码,源码在

org.springframework.security.oauth2.core.OAuth2ErrorCodes.

找到报invalid_client的地方,自己debug进去,看看哪些地方调用了INVALID_CLIENT。

然后右击INVALID_CLIENT,选择 find usages,发现是

org.springframework.security.oauth2.server.authorization.authentication.ClientSecretAuthenticationProvider类中的throwInvalidClient()方法封装了这个错误,然后一个断点打在这里,追查是哪里调用了这个方法。

我遇到的问题是最后追查到ClientSecretAuthenticationProvider这个类的authenticate()方法中,我们可以看到是passwordEncoder.matches(clientSecret,registeredClient.getClientSecret())这行出了问题。

我自己定义了一个passwordEncoder,然后重写了matches方法。我原本的maches方法是这样的。

 

修改成了这样:

@Component
public class SSOPasswordEncoder implements PasswordEncoder {
    @Override
    public String encode(CharSequence rawPassword) {
        return rawPassword.toString();
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        String digestPassword = null;
        if(rawPassword instanceof String){
            digestPassword = rawPassword.toString();
        }else{
            digestPassword = StringUtil.getDigest(rawPassword.toString());
        }
        return encode(digestPassword).equals(encodedPassword);
    }
}

得到了正确的结果。

总结:即使有的时候报错都是invalid_client,但是导致invalid_client的原因可是不尽相同的,所以最好的办法就是找到是哪里抛出来的invalid_client,然后找到所有调用invalid_client的地方,都打上断点,一点点debug进去,看看是哪个条件不满足,最后抛了这个错误,然后修正那个不正确的条件,得以解决问题。

  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Java 实现 OAuth2 客户端通常需要使用 OAuth2 客户端库,以下是使用 Spring Security OAuth2 客户端的示例代码: 1. 添加依赖 在 pom.xml 文件添加以下依赖: ```xml <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2-client</artifactId> <version>5.2.5.RELEASE</version> </dependency> ``` 2. 配置授权服务器信息 在 application.yml 或 application.properties 文件添加授权服务器信息: ```yaml spring: security: oauth2: client: registration: my-client: client-id: my-client-id client-secret: my-client-secret authorization-grant-type: authorization_code redirect-uri: '{baseUrl}/login/oauth2/code/{registrationId}' scope: user client-name: My Client provider: my-provider: authorization-uri: https://example.com/oauth2/authorize token-uri: https://example.com/oauth2/token user-info-uri: https://example.com/oauth2/userinfo user-name-attribute: sub ``` 其,`my-client` 和 `my-provider` 是自定义的标识符,用于区分不同的客户端和提供商。`client-id` 和 `client-secret` 是从授权服务器获取的客户端 ID 和密钥。`authorization-grant-type` 指定授权类型,这里是授权码模式。`redirect-uri` 是回调 URL,用于接收授权码。`scope` 是请求的权限范围,这里是请求用户信息。`authorization-uri` 是授权服务器的授权页面 URL,`token-uri` 是获取访问令牌的 URL,`user-info-uri` 是获取用户信息的 URL,`user-name-attribute` 是用户标识符在用户信息的属性名。 3. 创建登录页面 在 Thymeleaf 模板创建登录页面: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Login Page</title> </head> <body> <div th:if="${param.error}"> Invalid username and password. </div> <div th:if="${param.logout}"> You have been logged out. </div> <h2>Login with OAuth2</h2> <a th:href="@{/oauth2/authorization/my-provider}">Login with My Provider</a> </body> </html> ``` 其,`/oauth2/authorization/my-provider` 是登录链接,`my-provider` 是之前配置的提供商标识符。 4. 创建回调页面 在 Thymeleaf 模板创建回调页面: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>OAuth2 Callback Page</title> </head> <body> <script> function closeWindow() { window.opener.location.reload(); window.close(); } closeWindow(); </script> </body> </html> ``` 其,使用 JavaScript 关闭弹出窗口并刷新父窗口。 5. 创建安全配置 创建一个继承 `WebSecurityConfigurerAdapter` 的安全配置类: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/login**", "/webjars/**") .permitAll() .anyRequest() .authenticated() .and() .oauth2Login() .loginPage("/") .defaultSuccessURL("/home") .failureUrl("/?error=true") .and() .logout() .logoutSuccessUrl("/") .permitAll(); } } ``` 其,`configure()` 方法配置了请求授权规则和 OAuth2 登录的相关参数,`.antMatchers()` 指定了不需要认证的 URL,`.oauth2Login()` 配置了 OAuth2 登录的参数,`.loginPage()` 指定了登录页面 URL,`.defaultSuccessURL()` 指定了登录成功后的默认 URL,`.failureUrl()` 指定了登录失败后的 URL,`.logout()` 配置了注销登录的参数。 6. 创建控制器 创建一个控制器处理回调请求和获取用户信息: ```java @Controller public class OAuth2Controller { @GetMapping("/home") public String home(Model model, OAuth2AuthenticationToken authentication) { OAuth2AuthorizedClient client = authorizedClientService.loadAuthorizedClient(authentication.getAuthorizedClientRegistrationId(), authentication.getName()); model.addAttribute("userName", client.getPrincipalName()); return "home"; } @GetMapping("/login") public String login() { return "login"; } @GetMapping("/logout") public String logout() { return "logout"; } @Autowired private OAuth2AuthorizedClientService authorizedClientService; @GetMapping("/login/oauth2/code/{registrationId}") public String callback(@PathVariable String registrationId, OAuth2AuthenticationToken authentication) { OAuth2AuthorizedClient client = authorizedClientService.loadAuthorizedClient(registrationId, authentication.getName()); return "redirect:/home"; } } ``` 其,`home()` 方法获取用户信息并返回到 home.html 模板,`login()` 方法返回到登录页面,`logout()` 方法返回到注销页面,`callback()` 方法处理回调请求并获取 OAuth2 客户端。 这就是使用 Spring Security OAuth2 客户端实现 OAuth2 客户端的基本流程。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值