一、Spring OAuth2
Spring OAuth2是OAuth2协议的完整实现,如果你对OAuth2协议不了解可以先看OAuth2介绍。
Spring OAuth2服务端实现可分为Authorization Service
和Resource Service
,这两个服务可以是同一个应用,也可以是两个应用,甚至是多个Resource Service
共享一个Authorization Service
。
Spring MVC Controller
用来处理token请求,Spring Security Filters
用来处理访问受保护资源的请求。
为了实现Authorization Service
,Spring Security Filters
中需要以下端点:
-
AuthorizationEndpoint
用于授权请求,Default URL:/oauth/authorize
-
TokenEndpoint
用于访问令牌请求,Default URL:/oauth/token
为了实现Resource Service
需要以下filter
: -
OAuth2AuthenticationProcessingFilter
根据已授权的access token
来验证请求是否有效
以上内容Spring OAuth2都已经提供,只要简单配置Spring Framework就会自动帮我们加载。
二、Authorization Server配置
在配置Authorization Server
时,必须考虑client
获取访问令牌的授予类型(例如authorization code
, user credentials
, refresh token
)。服务配置可用于提供client details service
和token services
的实现,并且可全局启用或禁用服务的某些方面。另外可以为每个client
专门配置权限,使其能够使用某些授权机制和访问授权。
@EnableAuthorizationServer
注解和AuthorizationServerConfigurer
接口可用来配置Authorization Server
,不过一般通过继承AuthorizationServerConfigurerAdapter
(AuthorizationServerConfigurer
空的实现类)来配置。
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
}
}
以下功能将委托给由Spring创建并传递到AuthorizationServerConfigurer
中的配置器(如上代码所示):
-
ClientDetailsServiceConfigurer
用来配置client details service
的实现类,比如是JDBC实现还是InMemory实现 -
AuthorizationServerSecurityConfigurer
用来配置token endpoint
的安全约束 -
AuthorizationServerEndpointsConfigurer
用来配置authorization endpoint
、token endpoint
、token service
Client Details配置
ClientDetailsServiceConfigurer
可用来配置基于InMemory或JDBC的client details service
实现。其重要属性如下:
-
clientId
: (必须)客户端ID -
secret
:(对于受信任的客户端是必需的)客户端密钥。 -
scope
:客户端的范围限制。如果未定义或为空(默认值),则客户端不受范围限制 -
authorizedGrantTypes
:授权客户使用的授权类型。默认值为空 -
authorities
:授予客户端的权限(常规的Spring Security权限)。
本文的client details service
实现是基于JDBC的,也就是JdbcClientDetailsService
类。以下是Spring OAuth2 JDBC模式下会用到的全部表:
- oauth_client_details(JdbcClientDetailsService模式下使用)
- oauth_client_token(客户端实现下才会使用)
- oauth_access_token(JdbcTokenStore模式下使用)
- oauth_refresh_token(JdbcTokenStore模式下使用)
- oauth_code(JdbcAuthorizationCodeServices模式下会使用)
- oauth_approvals(JdbcApprovalStore模式下会使用)
表的具体定义请参考:schema.sql
Tokens管理
AuthorizationServerTokenServices
定义了一组操作用来管理tokens
:
- 创建
access token
后需要存储它,以便后续客户端访问资源时可以引用这个令牌。 -
access token
用于加载身份验证信息
当你要实现AuthorizationServerTokenServices
接口时,可以考虑使用DefaultTokenServices
这个类,它提供了各种策略来改变访问令牌的格式和存储。默认情况下,它通过随机值创建令牌(UUID.randomUUID()
),并处理所有除了将令牌持久化委托给TokenStore
的事务。令牌存储的默认方式是InMemory,当然还有其它一些实现。
-
InMemoryTokenStore
比较适合单服务应用(例如,低流量,并且在发生故障的情况下不进行热备份)。大多数项目都可以按这种方式启动,特别在开发模式下比较方便,因为这种方式不需要引入额外的依赖。 -
JdbcTokenStore
将令牌存储在关系数据库中,这种方式可以使令牌在多个服务器或者组件之间共享。 -
JwtTokenStore(JSON Web Token (JWT))
将授权信息编码到令牌本身中(因此根本没有后端存储,这是一个很大的优势)。缺点是您不能随意撤销令牌,因此它们的授权期限通常很短,并且撤消是在刷新令牌中进行的。另一个缺点是,如果您在令牌中存储了大量用户凭证信息,则令牌会变得很大。从数据持久化角度来讲,JwtTokenStore
不是一个真正意义上的令牌存储仓库,但是它在DefaultTokenServices
中扮演着跟其它存储方式同样的角色。
本文示例代码将使用JdbcTokenStore
,该存储模式会使用到oauth_access_token
、oauth_refresh_token
这两张表。
授权类型
OAuth2协议一共定义了4个授权类型,分别是:
- Authorization Code
- Implicit
- Resource Owner Password Credentials
- Client Credentials
AuthorizationEndpoint
可以支持的授权类型可通过AuthorizationServerEndpointsConfigurer
进行配置。默认支持除了Resource Owner Password Credentials
以外的所有授权类型。以下几个属性将影响授权类型:
- authenticationManager 通过注入
AuthenticationManager
可以开启Resource Owner Password Credentials
授权类型 - userDetailsService 如果您注入
UserDetailsService
或者全局配置了一个(例如GlobalAuthenticationManagerConfigurer
),当请求refresh token
时会对用户身份信息进行检查,确保账号有效(这个还需要根据授权类型来判断,因为有些授权类型只有client身份验证,没有user身份验证,请查看下面代码片段)
DefaultTokenServices
第145~154行代码
OAuth2Authentication authentication = tokenStore.readAuthenticationForRefreshToken(refreshToken);
if (this.authenticationManager != null && !authentication.isClientOnly()) {
// The client has already been authenticated, but the user authentication might be old now, so give it a
// chance to re-authenticate.
Authentication user = new PreAuthenticatedAuthenticationToken(authentication.getUserAuthentication(), "", authentication.getAuthorities());
user = authenticationManager.authenticate(user);
Object details = authentication.getDetails();
authentication = new OAuth2Authentication(authentication.getOAuth2Request(), user);
authentication.setDetails(details);
}
- authorizationCodeServices 用来设置
AuthorizationCodeServices
服务,可以选择用JDBC或InMemory方式来存储code
值,主要用于Authorization Code
授权方式 - implicitGrantService 用于
Implicit
授权模式的服务 - tokenGranter 扩展授权模式,可用来自定义
Authorization Server配置源码
package com.drw.start.oauth2.config;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.approval.TokenApprovalStore;
import org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler;
import org.springframework.security.oauth2.provider.approval.UserApprovalHandler;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Autowired
private TokenStore tokenStore;
@Autowired
private UserApprovalHandler userApprovalHandler;
@Autowired
private AuthenticationManager authenticationManager;
//将Authorization Code存储到数据库中,只有grant_type=authorization_code才有效
/*@Autowired
private AuthorizationCodeServices authorizationCodeServices;*/
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
/*clients.inMemory()
.withClient("oauth-demon")
.accessTokenValiditySeconds(100*1)
.refreshTokenValiditySeconds(200*1)
.authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit", "client_credentials")
.authorities("ROLE_CLIENT")
.redirectUris("http://baidu.com")
//.autoApprove(true)//静默授权,用户无感知
.scopes("read", "write", "trust")
.secret("{noop}1234567");//不对密码进行加密*/
clients.withClientDetails(new JdbcClientDetailsService(dataSource));
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore).userApprovalHandler(userApprovalHandler)
.authenticationManager(authenticationManager);
//.authorizationCodeServices(authorizationCodeServices);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.realm("oauth2.0 test");
oauthServer.allowFormAuthenticationForClients();
//oauthServer.checkTokenAccess("permitAll()"); /oauth/check_token默认关闭,如果要使用需要打开
}
@Bean
public TokenStore tokenStore(DataSource dataSource) {
//return new InMemoryTokenStore();
return new JdbcTokenStore(dataSource);
}
@Bean
public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore, ClientDetailsService clientDetailsService){
TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
handler.setTokenStore(tokenStore);
handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
handler.setClientDetailsService(clientDetailsService);
return handler;
}
@Bean
public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception {
TokenApprovalStore store = new TokenApprovalStore();
store.setTokenStore(tokenStore);
return store;
}
//将Authorization Code存储到数据库中,只有grant_type=authorization_code才有效
/*@Bean
public JdbcAuthorizationCodeServices jdbcAuthorizationCodeServices(DataSource dataSource) {
return new JdbcAuthorizationCodeServices(dataSource);
}*/
}
三、Resource Server配置
Resource Server
(可以与Authorization Server
在同一应用中,也可以在不同应用中)提供受OAuth2令牌保护的资源。Spring OAuth提供了实现此保护的Spring Security身份验证过滤器。您可以通过@Configuration class
添加@EnableResourceServer
注解然后实现ResourceServerConfigurer
接口来打开资源保护功能,并进行配置。可以配置以下功能:
- tokenServices
ResourceServerTokenServices
接口的实现类对象 - resourceId 资源ID(可选,但建议使用,并且将由
Authorization Server
验证),这个ID会在创建client
的时候分配给它,然后授权服务器会验证client
的ID与资源的ID是否一致,如果不一致就拒绝访问。 - 其他扩展功能(例如,tokenExtractor用于从传入请求中提取令牌)
- 请求受保护资源的匹配器(默认为全部)
- 受保护资源的访问规则(默认为简单的“已验证”)
- Spring Security中HttpSecurity配置器所允许的受保护资源的其它自定义设置。
@EnableResourceServer
注解会自动在Spring Security过滤器链中添加OAuth2AuthenticationProcessingFilter
过滤器。
本文采用Resource Server
与Authorization Server
在同一个应用中,所以没有额外的配置,也就是使用默认的DefaultTokenServices
。
Resource Server配置源码
package com.drw.start.oauth2.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
private static final String RESOURCE_ID = "oauth2_resource_api";
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(RESOURCE_ID).stateless(false);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.anonymous()
.disable()
.requestMatchers()
.antMatchers("/resource/**")
.and()
.authorizeRequests()
.antMatchers("/resource/**")
.access("#oauth2.clientHasRole('ROLE_CLIENT')")
.and()
.exceptionHandling()
//.accessDeniedHandler(new OAuth2AccessDeniedHandler());
.accessDeniedHandler(new MyOAuth2AccessDeniedHandler())//已登录的时候处理
.authenticationEntryPoint(new MyOAuth2AuthenticationEntryPoint());//没有登录的时候处理
}
}
四、OAuth2授权实践
Authorization Code授权方式
请求code URL:http://localhost:8080/start_oauth2/oauth/authorize?response_type=code&client_id=oauth-demon&redirect_uri=http://baidu.com&state=123

OAuth2协议并没有规定/oauth/authorize
端点需要用户身份验证,这个验证是Spring security要求。


获取到code
值后,就可以用code
值换取token
值了。
请求token URL:http://localhost:8080/start_oauth2/oauth/token?client_id=oauth-demon&grant_type=authorization_code&redirect_uri=http://baidu.com&code=AQZoLD&client_secret=1234567

Implicit授权方式
Implicit授权方式不需要通过code
值换取token
值,用户授权后直接返回token
值。
请求token URL:http://localhost:8080/start_oauth2/oauth/authorize?client_id=oauth-demon&response_type=token



Resource Owner Password Credentials授权方式
请求token URL:http://localhost:8080/start_oauth2/oauth/token?grant_type=password&username=oauthuser&password=123&client_id=oauth-demon&client_secret=1234567

Client Credentials授权方式
请求token URL:http://localhost:8080/start_oauth2/oauth/token?grant_type=client_credentials&client_id=oauth-demon&client_secret=1234567

五、参考源码
https://gitee.com/jack_junjie/demo-start-oauth2
六、参考资源
https://projects.spring.io/spring-security-oauth/docs/oauth2.html
https://github.com/spring-projects/spring-security-oauth/tree/master/samples/oauth2
网友评论