3)OAuth2 Client 结合GitHub授权案例
本随笔说明:这仅作为OAuth2 Client初次使用的案例,所以写得很简单,有许多的不足之处。
OAuth2 Client(OAuth2客户端)是指使用OAuth2协议与授权服务器进行通信并获取访问令牌的应用程序或服务。OAuth2客户端代表最终用户(资源拥有者)向授权服务器请求授权,并使用授权后的访问令牌来访问受保护的资源服务器。
OAuth2客户端的主要任务是与授权服务器进行身份验证和授权流程,以获取访问令牌。这样,它可以使用该令牌来向资源服务器发出请求,获取和操作受保护的资源。
OAuth2客户端通常包含以下功能和组件:
- 客户端凭据(Client Credentials):OAuth2客户端必须拥有一个唯一的客户端凭据,包括客户端ID和客户端密钥(或密码)。这些凭据用于在与授权服务器进行通信时进行身份验证和授权。
- 授权请求:OAuth2客户端向授权服务器发送授权请求,包括请求的权限范围和重定向URL。它会提供自己的客户端凭据以进行身份验证。
- 授权回调处理:OAuth2客户端需要能够接收和处理来自授权服务器的授权回调。这是授权服务器将授权码或访问令牌传递回客户端的方式。
- 访问令牌的管理:OAuth2客户端负责管理访问令牌的获取、刷新和失效。它应该能够安全地存储和使用
3.1 GitHub设置
官方文档:https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/creating-an-oauth-app
- 点击自己头像/进入Settings/ 进入Developer settings(左边导航栏最下面)/ 进入OAuth Apps;然后注册新应用程序

- 注册新应用程序
第一步:

值得注意的是,如果回调地址不是/login/oauth2/code/*,仅仅是回调失败,但是授权会成功。其次就是在spring security中/login/oauth2/code是固定的,而/github是自己指定的,即最后一个是动态的。
从spring security源码中可以看出,回调地址的固定写法:- public class OAuth2LoginAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
- public static final String DEFAULT_FILTER_PROCESSES_URI = "/login/oauth2/code/*";
- private static final String AUTHORIZATION_REQUEST_NOT_FOUND_ERROR_CODE = "authorization_request_not_found";
- private static final String CLIENT_REGISTRATION_NOT_FOUND_ERROR_CODE = "client_registration_not_found";
- private ClientRegistrationRepository clientRegistrationRepository;
- private OAuth2AuthorizedClientRepository authorizedClientRepository;
- private AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository;
- private Converter<OAuth2LoginAuthenticationToken, OAuth2AuthenticationToken> authenticationResultConverter;
- public OAuth2LoginAuthenticationFilter(ClientRegistrationRepository clientRegistrationRepository, OAuth2AuthorizedClientService authorizedClientService) {
- this(clientRegistrationRepository, authorizedClientService, "/login/oauth2/code/*");
- }
- //省略.....
- }
复制代码 第二步:点击Register application后就会跳转到如下界面,这时可以创建密钥(必须)和上传应用logo(非必须)
创建密钥时需要输入密码,得到密钥后请妥善保存,更新信息后密钥就不再显示
在更新前可以将ClientID 和 Client secrets以及 回调URL 保存一下,等下会用到

3.2 开始编码
创建一个基本的springboot项目,我这里的spring boot版本是:2.7.11,所以spring security的版本是5.7以上的,可能存在语法差异
- spring security和oauth2 client的maven依赖
- <dependency>
- <groupId>org.springframework.security</groupId>
- <artifactId>spring-security-test</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-oauth2-client</artifactId>
- </dependency>
复制代码 - yml配置文件
spring.security.oauth2.client.registration是固定写法,会有提示,而后面的为自定义内容,不会有提示- server:
- port: 8080
- spring:
- security:
- oauth2:
- client:
- registration:
- github:
- client-id: Client ID # 自己的客户端ID
- client-secret: Client secrets # 自己的密钥
- redirect-uri: 回调URL # 必须和GitHub上填的回调地址一致
复制代码 - SpringSecurity配置文件
.oauth2Login()使用oauth2登录认证- package com.yang.springsecurityoauthclient01.config;
- //省略导包
- @Configuration
- @EnableWebSecurity
- @EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true,jsr250Enabled = true)
- public class WebSecurityConfig {
- @Bean
- SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
- return http.authorizeRequests()
- .anyRequest().authenticated()
- .and()
- .oauth2Login() //使用oauth2认证 (需要在配置文件中配置服务,否则可能会启动失败 )
- .and()
- .csrf().disable()
- .build();
- }
- }
复制代码 - controller 控制层编写
- package com.yang.springsecurityoauthclient01.controller;
- //省略导包
- @RestController
- public class HelloController {
- @GetMapping("/index")
- public String index(){
- return "主页~~~";
- }
-
- /**
- * @return GitHub的授权信息
- */
- @GetMapping("/hello")
- public DefaultOAuth2User hello(){
- Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
- return (DefaultOAuth2User) authentication.getPrincipal();
- }
- }
复制代码 - 最终结果
访问http://localhost:8080/index,点击GitHub进行授权验证

授权Authorize

访问http://localhost:8080/hello得到授权信息:

- 撤销用户授权
撤销授权后重启程序,之前的用户就需要进行重新进行授权了。

最后最后需要注意的是,同一个账号在短时间内别试得太多,不然会出现如下情况,解决办法也很简单,等就是了~~~

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |