添加依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-oauth2-client</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-security</artifactId>
  8. </dependency>
  9. <dependency>
  10. <groupId>org.springframework.boot</groupId>
  11. <artifactId>spring-boot-starter-web</artifactId>
  12. </dependency>

注册 OAuth 应用

在 GitHub 官网上注册一个新的 OAuth 应用,地址是 https://github.com/settings/applications/new,打开页面如图所:
Spring Security OAtho2.0实现GitHub 快捷登录 - 图1

  • Application name:应用名称,必填项。
  • Homepage URL:主页 URL,必填项。在本地开发时,将其设置为本地登录页即可。
  • Application description:应用的说明,选填项,置空即可。
  • Authorization callback URL:OAuth 认证的重定向地址,必填项,本地开发环节可设置为 http://localhost:8080/login/oauth2/code/github。

当用户通过用户代理(浏览器)成功登录 GitHub,并且用户在批准页(Approva Page)授权允许注册的客户端应用访问自己的用户数据后,GitHub 会将授权码(Code)通过重定向的方式传递给客户端应用。 Spring Security OAuth 默认的重定向模板是 {baseUrl}/login/oauth2/code/{registrationId},registrationId 是 ClientRegistration 的唯一 ID,通常以接入的 OAuth 服务提供商的简称来命名即可,所以此处设置为 github。

单击 “Register application” 按钮,即可注册得到 Client ID 和 Client Secret 信息:

Spring Security OAtho2.0实现GitHub 快捷登录 - 图2

配置 application.yml

前面在工程的 pom 文件中引入了相关依赖包,并且在 GitHub 上成功注册了一个 OAuth 客户端应用,接下来需要在配置文件 application.yml 中增加相应配置。

  1. spring:
  2. security:
  3. oauth2:
  4. client:
  5. registration:
  6. github:
  7. client-id: 116114c3a9f406111f58
  8. client-secret: 93fb4272bade1842fce6fa51e3ae0f40817d4466

说明:

(1)spring.security.oauth2.client.registration 是 OAuth 客户端所有属性的基础前缀。

(2)registration 下面的 github 是 ClientRegistration 的唯一 ID。

另外,client-id 和 client-secret 需要替换为前面在 GitHub 上注册得到的 clientId 和 clientSecret。

编写测试 controller

测试

(1)进入默认登录页localhost:8080/login,可以发现提供了 GitHub 的登陆跳转:
Spring Security OAtho2.0实现GitHub 快捷登录 - 图3

(2)点击‘GitHub’,进行认证:
Spring Security OAtho2.0实现GitHub 快捷登录 - 图4

看一下浏览器地址:

  1. https://github.com/login/oauth/authorize
  2. ?response_type=code
  3. &client_id=116114c3a9f406111f58
  4. &scope=read:user
  5. &state=O98bsosrtkbhhplyHbfOlXTUvd0RGzUEeOObv0xNPNo%3D
  6. &redirect_uri=http://localhost:8080/login/oauth2/code/github

单击 “Authorize andyzhaozhao” 按钮,以允许 OAuth 客户端应用访问 GitHub 的用户数据。此时 OAuth 客户端应用会调用用户数据接口(the UserInf Endpoint),创建认证对象。

我们此时请求localhost:8080/hello, 浏览器将打印字符串 “hello,user:×××”。

Spring Security OAtho2.0实现GitHub 快捷登录 - 图5