Spring Cloud Oauth2 初探

Spring Cloud Oauth2 初探

关键字

OAuth2 spring cloud spring security

你需要知道的

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

  • 你需要熟悉OAuth2.0的相关规范,以及各种授权方式的应用场景与流程。
  • Spring Security 官方文档
  • Spring OAuth2 官方文档

为何开始

一个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

依赖

其中核心依赖仅有


  org.springframework.cloud
  spring-cloud-starter-oauth2

其中 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.util.Map,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.util.Map,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.provider.endpoint.TokenEndpoint.getAccessToken(java.security.Principal,java.util.Map) 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.provider.endpoint.TokenEndpoint.postAccessToken(java.security.Principal,java.util.Map) 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 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,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

依赖

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


  org.springframework.cloud
  spring-cloud-starter-oauth2

//todo: 未完成...

你可能感兴趣的:(Spring Cloud Oauth2 初探)