添加依赖
<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,打开页面如图所:
git
- Application name:应用名称,必填项。
- Homepage URL:主页URL,必填项。在本地开发时,将其设置为本地登陆页便可。
- Application description:应用的说明,选填项,置空便可。
- Authorization callback URL:OAuth 认证的重定向地址,必填项,本地开发环节可设置为http://localhost:8080/login/oauth2/code/github。
当用户经过用户代理(浏览器)成功登陆GitHub,而且用户在批准页(Approva Page)受权容许注册的客户端应用访问本身的用户数据后,GitHub会将受权码(Code)经过重定向的方式传递给客户端应用。github
Spring Security OAuth默认的重定向模板是{baseUrl}/login/oauth2/code/{registrationId},registrationId是ClientRegistration的惟一ID,一般以接入的OAuth服务提供商的简称来命名便可,因此此处设置为github。web
单击“Register application”按钮,便可注册获得Client ID和Client Secret信息:spring
配置application.yml
前面在工程的pom文件中引入了相关依赖包,而且在GitHub上成功注册了一个OAuth客户端应用,接下来须要在配置文件application.yml中增长相应配置。浏览器
spring: security: oauth2: client: registration: github: client-id: 116114c3a9f406111f58 client-secret: 93fb4272bade1842fce6fa51e3ae0f40817d4466
说明:app
(1)spring.security.oauth2.client.registration是OAuth客户端全部属性的基础前缀。spring-boot
(2)registration下面的github是ClientRegistration的惟一ID。测试
另外,client-id和client-secret须要替换为前面在GitHub上注册获得的clientId和clientSecret。spa
编写测试controller
测试
(1)进入默认登陆页localhost:8080/login
,能够发现提供了GitHub的登录跳转:
代理
(2)点击‘GitHub’,进行认证:
看一下浏览器地址:
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:×××”。