Spring Cloud Oauth2 初探

Spring Cloud Oauth2 初探

关键字

OAuth2 spring cloud spring security

你需要知道的

一个原则: 使用前一定先看官方文档,看不懂再来搜寻第三方资料。

为何开始

一个Spring框架的应用,需要一种能够保护 API 接口的实现,尝试过 OAuth1.0 ,发现更多的是有关OAuth2.0 的讨论,且Spring Security 也有队OAuth2的支持,于是转而使用OAuth2

环境

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 已经包含在 Starter 中,无需再次声明,以保持 pom 简洁。

OAuth2 Authorization Server

要使用OAuth2 服务器,仅需要使用 @EnableAuthorizationServer注解。

此外OAuth2 Server还依赖于Spring Security,还需要加上@EnableWebSecurity注解。
当然,这还不够,根据Spring Security官方文档,你还需要继承WebSecurityConfigurerAdapter类以使Security配置生效。
你可以继承但不做任何改动,以使用默认配置。

默认的WebSecurity安全配置与OAuth2Server安全配置不会产生冲突,无需过滤/oauth/**端点。

该注解(@EnableAuthorizationServer)可以加在任何@Configuration注解的地方,推荐放在相关的配置类上,而不推荐放在入口类**Application上。

OAuthServerConfig.class

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

启动程序,可以看到 OAuth2 的相关接口已经实现了,Spring 的自动配置已经为我们做了许多工作了,以致于我们可以开箱即用。

值得注意的是,自动配置类为我们生成了一个用户名为:user的 "user" 和一个 "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

尝试携带上面的信息进行GET请求:
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

会跳转到/login页面进行登录验证,填入 user 和 log 中的密码 d457f3b2-a3d7-4ace-bfaf-44ab7bfd8ccc即可验证通过。

重新跳转回授权页面,选择Approve同意并进行授权后,页面跳转至redirect_url并携带code信息。

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

取得 code 之后,就可以向服务器继续请求access-token了,使用 POST 方法继续请求。

需要注意的是你需要添加 Basic Auth 信息在请求头,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

不出意外,你将会看到以下信息:

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

至此,我们已经完成了一整个authorization_code类型的OAuth2授权了。

OAuth Resource Server

依赖

同样的,你只需要一个依赖:

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

//todo: 未完成...

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,290评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,399评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,021评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,034评论 0 207
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,412评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,651评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,902评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,605评论 0 199
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,339评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,586评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,076评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,400评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,060评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,083评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,851评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,685评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,595评论 2 270

推荐阅读更多精彩内容