SpringSecurity:OAuth2 Client 结合GitHub授权案例(特简单版) ...

打印 上一主题 下一主题

主题 910|帖子 910|积分 2730

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源码中可以看出,回调地址的固定写法:
    1. public class OAuth2LoginAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    2.     public static final String DEFAULT_FILTER_PROCESSES_URI = "/login/oauth2/code/*";
    3.     private static final String AUTHORIZATION_REQUEST_NOT_FOUND_ERROR_CODE = "authorization_request_not_found";
    4.     private static final String CLIENT_REGISTRATION_NOT_FOUND_ERROR_CODE = "client_registration_not_found";
    5.     private ClientRegistrationRepository clientRegistrationRepository;
    6.     private OAuth2AuthorizedClientRepository authorizedClientRepository;
    7.     private AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository;
    8.     private Converter<OAuth2LoginAuthenticationToken, OAuth2AuthenticationToken> authenticationResultConverter;
    9.     public OAuth2LoginAuthenticationFilter(ClientRegistrationRepository clientRegistrationRepository, OAuth2AuthorizedClientService authorizedClientService) {
    10.         this(clientRegistrationRepository, authorizedClientService, "/login/oauth2/code/*");
    11.     }
    12.     //省略.....
    13. }   
    复制代码
    第二步:点击Register application后就会跳转到如下界面,这时可以创建密钥(必须)和上传应用logo(非必须)
    创建密钥时需要输入密码,得到密钥后请妥善保存,更新信息后密钥就不再显示
    在更新前可以将ClientID 和 Client secrets以及 回调URL  保存一下,等下会用到

3.2 开始编码

创建一个基本的springboot项目,我这里的spring boot版本是:2.7.11,所以spring security的版本是5.7以上的,可能存在语法差异

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

    授权Authorize

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

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

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


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

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

知者何南

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表