美文网首页Oauth2
Spring OAuth2(JDBC)

Spring OAuth2(JDBC)

作者: 随风摇摆水杉树 | 来源:发表于2020-08-14 21:40 被阅读0次

一、Spring OAuth2

Spring OAuth2是OAuth2协议的完整实现,如果你对OAuth2协议不了解可以先看OAuth2介绍
Spring OAuth2服务端实现可分为Authorization ServiceResource Service,这两个服务可以是同一个应用,也可以是两个应用,甚至是多个Resource Service共享一个Authorization Service
Spring MVC Controller用来处理token请求,Spring Security Filters用来处理访问受保护资源的请求。
为了实现Authorization ServiceSpring 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 servicetoken services的实现,并且可全局启用或禁用服务的某些方面。另外可以为每个client专门配置权限,使其能够使用某些授权机制和访问授权。
@EnableAuthorizationServer注解和AuthorizationServerConfigurer接口可用来配置Authorization Server,不过一般通过继承AuthorizationServerConfigurerAdapterAuthorizationServerConfigurer空的实现类)来配置。

@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 endpointtoken endpointtoken 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_tokenoauth_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 ServerAuthorization 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
请求code时输入用户名密码.png

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

请求code时需要用户确认.png 用户同意后返回code值.png

获取到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
使用code值换取token值.png
Implicit授权方式

Implicit授权方式不需要通过code值换取token值,用户授权后直接返回token值。

请求token URL:http://localhost:8080/start_oauth2/oauth/authorize?client_id=oauth-demon&response_type=token
Implicit请求token时输入用户名密码.png Implicit请求token时需要用户确认.png Implicit用户同意后返回token值.png
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
Resource Owner Password Credentials请求token值.png
Client Credentials授权方式
请求token URL:http://localhost:8080/start_oauth2/oauth/token?grant_type=client_credentials&client_id=oauth-demon&client_secret=1234567
Client Credentials请求token值.png

五、参考源码

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

相关文章

网友评论

    本文标题:Spring OAuth2(JDBC)

    本文链接:https://www.haomeiwen.com/subject/rqrhdktx.html