添加依賴
<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:×××」。