spring Security oAuth2例子分析

oauth2

参考:
1.https://tools.ietf.org/html/draft-ietf-oauth-v2-31
2.http://projects.spring.io/spring-security-oauth/docs/oauth2.html

基于spring-security-oauth2,从https://github.com/spring-projects/spring-security-oauth/tree/master/samples/oauth2抽取出来的源码,父pom的不继承artifactId>spring-security-oauth-parent,主要是脱离spring boot独立出来的oauth2

在这个例子中的授权服务端和资源服务端是在同一个应用服务器.
一.在客户端tonr2:
1.使用OAuth2RestTemplate(即org.springframework.security.oauth.examples.config.WebMvcConfig.ResourceConfiguration.sparklrRestTemplate)向sparklr2发http://localhost:8080/sparklr2/photos?format=xml请求.
2.经org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter.doFilter过滤,然后正常执行请求前获取不到accessToken,抛异常给org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter.doFilter的Catch处理,这里进行会进行跳转redirectUser(redirect, request, response);然后再到this.redirectStrategy.sendRedirect(request, response, builder.build().encode().toUriString());这里再向sparklr2发http://localhost:8080/sparklr2/oauth/authorize?client_id=tonr&redirect_uri=http://localhost:8081/tonr2/sparklr/photos&response_type=code&scope=read%20write&state=1DvnAt这样的请求,也就是从这里开始获取授权码.

二.转到服务端sparklr2
3.经过spring security的org.springframework.security.web.FilterChainProxy过滤,用户没登录,将用户导向登录页面登录,登录完成后继续跳转到之前的获取授权码请求org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.authorize,然后接受请求.以下两行代码判断用户是否授权给客户端.
authorizationRequest = userApprovalHandler.checkForPreApproval(authorizationRequest,(Authentication) principal);
boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal);
//如果用户授权给了客户端
if (authorizationRequest.isApproved()) {
if (responseTypes.contains(“token”)) {
return getImplicitGrantResponse(authorizationRequest);
}
//直接响应获取授权码
if (responseTypes.contains(“code”)) {
return new ModelAndView(getAuthorizationCodeResponse(authorizationRequest,
(Authentication) principal));
}
}
//否则还要导向用户到 授权给客户端界面.
model.put(“authorizationRequest”, authorizationRequest);
return getUserApprovalPageResponse(model, authorizationRequest, (Authentication) principal);
4.假设用户还没授权过给客户端,用户在界面选择是否授权并提交,org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.approveOrDeny再接收请求,然后再响应获取授权码(当然用户都拒绝授权所有权限就会抛UserDeniedAuthorizationException异常,或者正常生成授权码),再根据回调url回到客户端.

三.获取授权码的响应回到客户端
5.回到org.springframework.security.oauth.examples.tonr.impl.SparklrServiceImpl.getSparklrPhotoIds再次发请求,此时又调用了sparklrRestTemplate,于是会再次调用org.springframework.security.oauth2.client.OAuth2RestTemplate.getAccessToken
这个方法会判断accessToken为null时会调用acquireAccessToken(OAuth2ClientContext oauth2Context)方法,
accessToken = accessTokenProvider.obtainAccessToken(resource, accessTokenRequest);
if (accessToken == null || accessToken.getValue() == null) {
throw new IllegalStateException(
“Access token provider returned a null access token, which is illegal according to the contract.”);
}
oauth2Context.setAccessToken(accessToken);
调用org.springframework.security.oauth2.client.token.AccessTokenProviderChain.obtainAccessToken的accessToken = obtainNewAccessTokenInternal(resource, request);
调用org.springframework.security.oauth2.client.token.AccessTokenProviderChain.obtainNewAccessTokenInternal的return tokenProvider.obtainAccessToken(details, request);
调用org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider.obtainAccessToken的return retrieveToken(request, resource, getParametersForTokenRequest(resource, request),getHeadersForTokenRequest(request));
调用org.springframework.security.oauth2.client.token.OAuth2AccessTokenSupport.retrieveToken的return getRestTemplate().execute(getAccessTokenUri(resource, form), getHttpMethod(),getRequestCallback(resource, form, headers), extractor , form.toSingleValueMap());这时就会向sparklr2发起获取accessToken的请求http://localhost:8080/sparklr2/oauth/token这里发的是POST请求,参数都在form里面的.

四.再次向服务端获取accessToken
org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken接收请求,处理生成accessToken(是一个UUID,实际上包含的授权信息还是在服务端,只是这个UUID会对应Authentication),
这个例子生成accessToken在org.springframework.security.oauth2.provider.token.DefaultTokenServices.createAccessToken(org.springframework.security.oauth2.provider.OAuth2Authentication, org.springframework.security.oauth2.common.OAuth2RefreshToken)
然后调用tokenStore.storeAccessToken(accessToken, authentication);保存到服务端,这里的tokenStore使用InMemoryTokenStore实现.(用户的认证信息可以保存到redis来将资源服务器和授权服务器分离,springDataRedis又提供了方便,redis增加了集群,如果可靠,就没必要持久化到数据库了)

五.获取accessToken的响应回到客户端
org.springframework.security.oauth2.client.OAuth2RestTemplate.acquireAccessToken这个方法会将得到的accessToken保存到OAuth2ClientContext.以后用户用这个accessToken来访问受保护的资源(直接访问资源服务端,当然这里授权服务端和资源服务端连在一起)就可以了.

六.访问受资源服务端保护的资源(前面没有特别说明的服务端都是指授权服务端)
1.先看看客户端再向资源服务端发起请求org.springframework.security.oauth.examples.tonr.impl.SparklrServiceImpl.getSparklrPhotoIds的sparklrRestTemplate.getForObject(URI.create(sparklrPhotoListURL), byte[].class)
2.资源服务端接受请求org.springframework.security.oauth.examples.sparklr.mvc.PhotoController.getPhoto,进入这个方法之前肯定要做验证的

因为授权服务端和资源服务端混在一起,再加上我们一般的Security自定义有一套,这个WebSecurity就共有三套HttpSecurity(放在org.springframework.security.config.annotation.web.builders.WebSecurity.securityFilterChainBuilders),在我理解,前面这两套没有启用全局,最后一套是希望有更多的自定义权限控制交给开发者,在这个例子当中,在服务端,只注册了一个FilterChainProxy拦截器,如果不理解spring security的启用全局方法,可先参考http://blog.csdn.net/xiejx618/article/details/44026469),不理PhotoController的代理是由JDK生成还是CGLIB生成.其实也先不理AOP,这里的AOP是控制在Controller的方法上,Filter的作用要比AOP走在前面.因为AOP是调用目标对象的方法才会触发AOP,而Filter的调用比Servlet还要前,更不用说进入Controller的方法.
org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerSecurityConfiguration.configure(org.springframework.security.config.annotation.web.builders.HttpSecurity)
org.springframework.security.oauth.examples.sparklr.config.OAuth2ServerConfig.ResourceServerConfiguration.configure(org.springframework.security.config.annotation.web.builders.HttpSecurity)
org.springframework.security.oauth.examples.sparklr.config.SecurityConfiguration.configure(org.springframework.security.config.annotation.web.builders.HttpSecurity)

情况一:下面假设用户没获取accessToken,直接访问/tonr2/sparklr/photos会是什么情况
很明显应该先由第一套HttpSecurity的配置起作用,生成了一个FilterSecurityInterceptor Filter
a.org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter的invoke(fi);
b.org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoker的InterceptorStatusToken token = super.beforeInvocation(fi);
c.org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation的this.accessDecisionManager.decide(authenticated, object, attributes);
又回到了熟悉的三者.authenticated为AnonymousAuthenticationToken的一个实例,FilterInvocation的一个实例,attributes为装有WebExpressionConfigAttribute的数组,经过这方法一判断,就会抛org.springframework.security.oauth2.client.resource.UserRedirectRequiredException,然后带用户去登录.

情况二:走正常流程,用户获取完accessToken再访问受保护资源的跟踪,发起请求GET http://localhost:8080/sparklr2/photos?format=xml(OAuth2RestTemplate的context有保存accessToken,发请求时将这个accessToken放进了请求头)
这次就是第二套HttpSecurity的配置起作用,
在资源服务端启动的时候,会调用
org.springframework.security.config.annotation.web.builders.WebSecurity.performBuild的securityFilterChains.add(securityFilterChainBuilder.build());
当securityFilterChainBuilder为资源服务端的那套HttpSecurity进入
org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.configure
private void configure() throws Exception {
Collection

你可能感兴趣的:(spring Security oAuth2例子分析)