Spring Security OAtho2.0实现GitHub 快捷登录
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
注册OAuth应用
在GitHub官网上注册一个新的OAuth应用,地址是https://github.com/settings/applications/new,打开页面如图所:

- 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信息:

配置application.yml
前面在工程的pom文件中引入了相关依赖包,并且在GitHub上成功注册了一个OAuth客户端应用,接下来需要在配置文件application.yml中增加相应配置。
spring:
security:
oauth2:
client:
registration:
github:
client-id: 116114c3a9f406111f58
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的登陆跳转:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2I1Jg9nN-1599383906433)(8E38BB2683084B5681C9DA26F7B619AD)]](https://img-blog.csdnimg.cn/20200906172024778.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQwMTc5NDc5,size_16,color_FFFFFF,t_70#pic_center)
(2)点击‘GitHub’,进行认证:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WilK6o0r-1599383906436)(4D5BC0FFEAEE4DADA745960FCC964DAF)]](https://img-blog.csdnimg.cn/20200906172124376.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQwMTc5NDc5,size_16,color_FFFFFF,t_70#pic_center)
看一下浏览器地址:
https://github.com/login/oauth/authorize
?response_type=code
&client_id=116114c3a9f406111f58
&scope=read:user
&state=O98bsosrtkbhhplyHbfOlXTUvd0RGzUEeOObv0xNPNo%3D
&redirect_uri=http://localhost:8080/login/oauth2/code/github
单击“Authorize andyzhaozhao”按钮,以允许OAuth客户端应用访问GitHub的用户数据。此时OAuth客户端应用会调用用户数据接口(the UserInf Endpoint),创建认证对象。
我们此时请求localhost:8080/hello,浏览器将打印字符串“hello,user:×××”。
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-E9oOK1WR-1599383906437)(1A49275172524ACDB8FD6DCE7B53FC2A)]](https://img-blog.csdnimg.cn/202009061722535.png#pic_center)

浙公网安备 33010602011771号