1.登录gitee,创建一个第三方登录的应用

首先找到设置中的第三方应用:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2.引入pom

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-oauth2-client</artifactId>
 </dependency>

3.application.yml

spring:
  security:
    oauth2:
      client:
        registration:
          gitee:
            #应用id
            client-id: 创建的应用中获取xxxxxxxxxxxxx
            #应用密钥
            client-secret: 创建应用中获取xxxxxxxxx
            #应用名称
            client-name: MyLinging
            #授权后重定向url
            redirect-uri: http://127.0.0.1:8080/login/oauth2/code/gitee
            #授权码模式
            authorization-grant-type: authorization_code
        provider:
          gitee:
            # Gitee 的授权 URL
            authorization-uri: https://gitee.com/oauth/authorize
            # token获取url
            token-uri: https://gitee.com/oauth/token
            # 用户信息获取url
            user-info-uri: https://gitee.com/api/v5/user
            # 码云用户信息中的用户名字段 这里就取id作为唯一标志
            user-name-attribute: id

4.配置文件

httpSecurity.oauth2Login(cus -> cus
   //登录认证入口(前端发起请求的路径)
   //例如:http://127.0.0.1:8080/oauth2/authorization/gitee
   .authorizationEndpoint(authorization -> authorization.baseUri("/oauth2/authorization"))
   //用户确认后,第三方服务器回调的路径
   .redirectionEndpoint(redirection -> redirection.baseUri("/login/oauth2/code/*"))
   // 处理第三方返回的用户信息
   .userInfoEndpoint(userInfo -> userInfo.userService(new DefaultOAuth2UserService()))
   // 三方认证成功后重定向的地址,此处本机测试,搭建前后端分离项目,授权后重定向前端首页地址,仅后端测试可注释掉不配置
   .defaultSuccessUrl("http://127.0.0.1:8081")
)

5.测试

在这里插入图片描述

  1. 点击gitee登录,访问登录授权的入口:http://127.0.0.1:8080/oauth2/authorization/gitee

  2. 访问后会重定向到gitee授权页面:https://gitee.com/oauth/authorize?response_type=code&client_id=xxxxxx&state=oihEUItlxWQEEsnz2in1VSo9w3Za7WUcwcShzQ1_IRg%3D&redirect_uri=http://127.0.0.1:8080/login/oauth2/code/gitee
    在这里插入图片描述

  3. 当用户点击同意授权时,会向gitee授权服务器请求授权获取code:https://gitee.com/oauth/authorize
    在这里插入图片描述

  4. 请求授权完后,回调到:http://127.0.0.1:8080/login/oauth2/code/gitee?code=xxxxxxxxxxx&state=oihEUItlxWQEEsnz2in1VSo9w3Za7WUcwcShzQ1_IRg%3D
    然后由springsecurity的OAuth2LoginAuthenticationFilter进行拦截,由OAuth2LoginAuthenticationProviderOAuth2AuthorizationCodeAuthenticationProvider根据code向gitee进行认证拿到token,然后根据token由DefaultOAuth2UserService的loadUser向gitee获取用户的信息,并封装DefaultOAuth2User对象保存在SecurityContextHolder中,然后认证完就重定向到首页。这里设置了重定向地址是http://127.0.0.1:8081/,如下:
    在这里插入图片描述

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐