Spring Cloud Oauth2 初探

Spring Cloud Oauth2 初探

關(guān)鍵字

OAuth2 spring cloud spring security

你需要知道的

一個(gè)原則: 使用前一定先看官方文檔妙同,看不懂再來搜尋第三方資料。

為何開始

一個(gè)Spring框架的應(yīng)用,需要一種能夠保護(hù) API 接口的實(shí)現(xiàn)泼各,嘗試過 OAuth1.0 ,發(fā)現(xiàn)更多的是有關(guān)OAuth2.0 的討論,且Spring Security 也有隊(duì)OAuth2的支持查描,于是轉(zhuǎn)而使用OAuth2

環(huán)境

Frame version
Centos 7
Spring Boot 2.0.0.RELEASE
Spring Cloud Finchley.M8
Oracle JDK 1.8
IDE Idea

依賴

其中核心依賴僅有

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

其中 Spring Security 已經(jīng)包含在 Starter 中柏卤,無(wú)需再次聲明冬三,以保持 pom 簡(jiǎn)潔。

OAuth2 Authorization Server

要使用OAuth2 服務(wù)器缘缚,僅需要使用 @EnableAuthorizationServer注解勾笆。

此外OAuth2 Server還依賴于Spring Security,還需要加上@EnableWebSecurity注解桥滨。
當(dāng)然窝爪,這還不夠,根據(jù)Spring Security官方文檔齐媒,你還需要繼承WebSecurityConfigurerAdapter類以使Security配置生效蒲每。
你可以繼承但不做任何改動(dòng),以使用默認(rèn)配置喻括。

默認(rèn)的WebSecurity安全配置與OAuth2Server安全配置不會(huì)產(chǎn)生沖突邀杏,無(wú)需過濾/oauth/**端點(diǎn)。

該注解(@EnableAuthorizationServer)可以加在任何@Configuration注解的地方唬血,推薦放在相關(guān)的配置類上望蜡,而不推薦放在入口類**Application上。

OAuthServerConfig.class

@Configuration
@EnableAuthorizationServer
@EnableWebSecurity
public class Oauth2ServerConfig {
    /**
     * Spring Security 安全配置
     */
    @Configuration
    public static class CustomWebSecurityConfiguration extends WebSecurityConfigurerAdapter {}
}

啟動(dòng)程序刁品,可以看到 OAuth2 的相關(guān)接口已經(jīng)實(shí)現(xiàn)了泣特,Spring 的自動(dòng)配置已經(jīng)為我們做了許多工作了,以致于我們可以開箱即用挑随。

值得注意的是状您,自動(dòng)配置類為我們生成了一個(gè)用戶名為:user的 "user" 和一個(gè) "client" :

2018-03-24 21:20:22.916  INFO 931 --- [           main] .s.s.UserDetailsServiceAutoConfiguration : 

Using generated security password: d457f3b2-a3d7-4ace-bfaf-44ab7bfd8ccc

2018-03-24 21:20:23.181  INFO 931 --- [           main] .s.o.p.e.FrameworkEndpointHandlerMapping : Mapped "{[/oauth/authorize]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.authorize(java.util.Map<java.lang.String, java.lang.Object>,java.util.Map<java.lang.String, java.lang.String>,org.springframework.web.bind.support.SessionStatus,java.security.Principal)
2018-03-24 21:20:23.183  INFO 931 --- [           main] .s.o.p.e.FrameworkEndpointHandlerMapping : Mapped "{[/oauth/authorize],methods=[POST],params=[user_oauth_approval]}" onto public org.springframework.web.servlet.View org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.approveOrDeny(java.util.Map<java.lang.String, java.lang.String>,java.util.Map<java.lang.String, ?>,org.springframework.web.bind.support.SessionStatus,java.security.Principal)
2018-03-24 21:20:23.185  INFO 931 --- [           main] .s.o.p.e.FrameworkEndpointHandlerMapping : Mapped "{[/oauth/token],methods=[GET]}" onto public org.springframework.http.ResponseEntity<org.springframework.security.oauth2.common.OAuth2AccessToken> org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.getAccessToken(java.security.Principal,java.util.Map<java.lang.String, java.lang.String>) throws org.springframework.web.HttpRequestMethodNotSupportedException
2018-03-24 21:20:23.185  INFO 931 --- [           main] .s.o.p.e.FrameworkEndpointHandlerMapping : Mapped "{[/oauth/token],methods=[POST]}" onto public org.springframework.http.ResponseEntity<org.springframework.security.oauth2.common.OAuth2AccessToken> org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(java.security.Principal,java.util.Map<java.lang.String, java.lang.String>) throws org.springframework.web.HttpRequestMethodNotSupportedException
2018-03-24 21:20:23.186  INFO 931 --- [           main] .s.o.p.e.FrameworkEndpointHandlerMapping : Mapped "{[/oauth/check_token]}" onto public java.util.Map<java.lang.String, ?> org.springframework.security.oauth2.provider.endpoint.CheckTokenEndpoint.checkToken(java.lang.String)
2018-03-24 21:20:23.186  INFO 931 --- [           main] .s.o.p.e.FrameworkEndpointHandlerMapping : Mapped "{[/oauth/confirm_access]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.security.oauth2.provider.endpoint.WhitelabelApprovalEndpoint.getAccessConfirmation(java.util.Map<java.lang.String, java.lang.Object>,javax.servlet.http.HttpServletRequest) throws java.lang.Exception
2018-03-24 21:20:23.186  INFO 931 --- [           main] .s.o.p.e.FrameworkEndpointHandlerMapping : Mapped "{[/oauth/error]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.security.oauth2.provider.endpoint.WhitelabelErrorEndpoint.handleError(javax.servlet.http.HttpServletRequest)
2018-03-24 21:20:23.536  INFO 931 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/oauth/token'], Ant [pattern='/oauth/token_key'], Ant [pattern='/oauth/check_token']]], [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@2287395, org.springframework.security.web.context.SecurityContextPersistenceFilter@41b64020, org.springframework.security.web.header.HeaderWriterFilter@15fb4566, org.springframework.security.web.authentication.logout.LogoutFilter@3b009e7b, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@3e33b52e, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@78910096, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@79e7188e, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@535a518c, org.springframework.security.web.session.SessionManagementFilter@29896529, org.springframework.security.web.access.ExceptionTranslationFilter@6a15b73, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@7741d346]
2018-03-24 21:20:23.563  INFO 931 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher@1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@ac91282, org.springframework.security.web.context.SecurityContextPersistenceFilter@67332b1e, org.springframework.security.web.header.HeaderWriterFilter@39941489, org.springframework.security.web.csrf.CsrfFilter@536b71b4, org.springframework.security.web.authentication.logout.LogoutFilter@1e5eb20a, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@1e8fb66f, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@60cb1ed6, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@3d8d17a3, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@7e34b127, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@679dd234, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@7f79edee, org.springframework.security.web.session.SessionManagementFilter@6f5d0190, org.springframework.security.web.access.ExceptionTranslationFilter@789c3057, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@1f9d4b0e]
2018-03-24 21:20:23.726  INFO 931 --- [           main] a.OAuth2AuthorizationServerConfiguration : Initialized OAuth2 Client

security.oauth2.client.client-id = 64b5dabe-a97c-4f60-8492-acd24fc7599d
security.oauth2.client.client-secret = f8934b27-c7d6-4821-bd7e-1f7270e7e7b8

嘗試攜帶上面的信息進(jìn)行GET請(qǐng)求:
http://127.0.0.1:8080/oauth/authorize?client_id=64b5dabe-a97c-4f60-8492-acd24fc7599d&response_type=code&scope=user&redirect_uri=http://www.baidu.com

會(huì)跳轉(zhuǎn)到/login頁(yè)面進(jìn)行登錄驗(yàn)證,填入 user 和 log 中的密碼 d457f3b2-a3d7-4ace-bfaf-44ab7bfd8ccc即可驗(yàn)證通過兜挨。

重新跳轉(zhuǎn)回授權(quán)頁(yè)面膏孟,選擇Approve同意并進(jìn)行授權(quán)后,頁(yè)面跳轉(zhuǎn)至redirect_url并攜帶code信息拌汇。

https://www.baidu.com/?code=bPVWmn

取得 code 之后,就可以向服務(wù)器繼續(xù)請(qǐng)求access-token了柒桑,使用 POST 方法繼續(xù)請(qǐng)求。

需要注意的是你需要添加 Basic Auth 信息在請(qǐng)求頭噪舀,username 為 "client_id" ,password為 "client_secret"

http://127.0.0.1:8080/oauth/token?grant_type=authorization_code&code=bPVWmn&redirect_uri=http://www.baidu.com&scope=user

不出意外魁淳,你將會(huì)看到以下信息:

{
  "access_token":"9d646451-c672-4aa6-a864-2e10ed0f29f1",
  "token_type":"bearer",
  "refresh_token":"d7c1c3ca-a30e-4889-b993-abf32822117d",
  "expires_in":42138,
  "scope":"user"
}

至此飘诗,我們已經(jīng)完成了一整個(gè)authorization_code類型的OAuth2授權(quán)了。

OAuth Resource Server

依賴

同樣的界逛,你只需要一個(gè)依賴:

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

//todo: 未完成...

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末昆稿,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子息拜,更是在濱河造成了極大的恐慌溉潭,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,997評(píng)論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件少欺,死亡現(xiàn)場(chǎng)離奇詭異喳瓣,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)赞别,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,603評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門畏陕,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人氯庆,你說我怎么就攤上這事蹭秋。” “怎么了堤撵?”我有些...
    開封第一講書人閱讀 163,359評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵仁讨,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我实昨,道長(zhǎng)洞豁,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,309評(píng)論 1 292
  • 正文 為了忘掉前任荒给,我火速辦了婚禮丈挟,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘志电。我一直安慰自己曙咽,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,346評(píng)論 6 390
  • 文/花漫 我一把揭開白布挑辆。 她就那樣靜靜地躺著例朱,像睡著了一般。 火紅的嫁衣襯著肌膚如雪鱼蝉。 梳的紋絲不亂的頭發(fā)上洒嗤,一...
    開封第一講書人閱讀 51,258評(píng)論 1 300
  • 那天,我揣著相機(jī)與錄音魁亦,去河邊找鬼渔隶。 笑死,一個(gè)胖子當(dāng)著我的面吹牛洁奈,可吹牛的內(nèi)容都是我干的间唉。 我是一名探鬼主播绞灼,決...
    沈念sama閱讀 40,122評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼呈野!你這毒婦竟也來了镀赌?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,970評(píng)論 0 275
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤际跪,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后喉钢,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體姆打,經(jīng)...
    沈念sama閱讀 45,403評(píng)論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,596評(píng)論 3 334
  • 正文 我和宋清朗相戀三年肠虽,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了幔戏。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,769評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡税课,死狀恐怖闲延,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情韩玩,我是刑警寧澤垒玲,帶...
    沈念sama閱讀 35,464評(píng)論 5 344
  • 正文 年R本政府宣布,位于F島的核電站找颓,受9級(jí)特大地震影響合愈,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜击狮,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,075評(píng)論 3 327
  • 文/蒙蒙 一佛析、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧彪蓬,春花似錦寸莫、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,705評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至捣郊,卻和暖如春辽狈,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背呛牲。 一陣腳步聲響...
    開封第一講書人閱讀 32,848評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工刮萌, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人娘扩。 一個(gè)月前我還...
    沈念sama閱讀 47,831評(píng)論 2 370
  • 正文 我出身青樓着茸,卻偏偏與公主長(zhǎng)得像壮锻,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子涮阔,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,678評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容