Oauth2

Spring OAuth2(JDBC)

2020-08-14  本文已影响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中需要以下端点:

二、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中的配置器(如上代码所示):

Client Details配置

ClientDetailsServiceConfigurer可用来配置基于InMemory或JDBC的client details service实现。其重要属性如下:

本文的client details service实现是基于JDBC的,也就是JdbcClientDetailsService类。以下是Spring OAuth2 JDBC模式下会用到的全部表:

表的具体定义请参考:schema.sql

Tokens管理

AuthorizationServerTokenServices定义了一组操作用来管理tokens

当你要实现AuthorizationServerTokenServices接口时,可以考虑使用DefaultTokenServices这个类,它提供了各种策略来改变访问令牌的格式和存储。默认情况下,它通过随机值创建令牌(UUID.randomUUID()),并处理所有除了将令牌持久化委托给TokenStore的事务。令牌存储的默认方式是InMemory,当然还有其它一些实现。

本文示例代码将使用JdbcTokenStore,该存储模式会使用到oauth_access_tokenoauth_refresh_token这两张表。

授权类型

OAuth2协议一共定义了4个授权类型,分别是:

AuthorizationEndpoint可以支持的授权类型可通过AuthorizationServerEndpointsConfigurer进行配置。默认支持除了Resource Owner Password Credentials以外的所有授权类型。以下几个属性将影响授权类型:

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);
}
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接口来打开资源保护功能,并进行配置。可以配置以下功能:

@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

上一篇 下一篇

猜你喜欢

热点阅读