Spring Security OAuth2 單點登入

廢物大師兄發表於2021-11-08

1. OAuth 2.0

OAuth(Open Authorization)為使用者資源的授權提供了一個安全的、開放而又簡易的標準。最簡單的理解,我們可以看一下微信OAuth2.0授權登入流程:

 

通過OAuth2可以授權第三方應用訪問資源擁有者在這個平臺的資源。舉個例子,用微信登入某個手機APP,此時會讓彈窗讓使用者授權,使用者同意以後,這個APP就可以獲取使用者的資源(比如:暱稱、頭像、openid等)進行登入了。在這個過程中,使用者的微信賬戶就是資源,資源的所有者是使用者,第三方應用是這個APP。

常用的授權型別(Authorization Grant)有如下種:

  • 授權碼(Authorization Code): 使用者授權後獲取授權碼,通過授權碼獲取access_token
  • 密碼(Resource Owner Password Credentials):不用先獲取授權碼,而是直接拿著資源所有者的密碼去獲取access_token

下面重點關注授權碼模式,因為接下來會利用OAuth2實現單店的登入

關於OAuth 2.0請參考下面的文件

https://datatracker.ietf.org/doc/html/rfc6749

https://oauth.net/2/

 

Client 可以理解為第三方應用,比如:微博

User-Agent 可以理解為瀏覽器,比如:使用者的Chrome瀏覽器

Resource-Owner 可以理解為使用者,比如:微信使用者

Authorization Server 可以理解為認證中心,比如:微信開放平臺

整個過程可以表述為,使用者開啟瀏覽器訪問微博,選擇微信登入,使用者掃碼後在手機端進行授權,微博拿到授權碼並向微信開放平臺獲取令牌,之後微博變可以獲取到使用者的暱稱和頭像等資源,然後登入成功。

2. 單點登入

單點登入(Single Sign On),簡稱為 SSO,是比較流行的企業業務整合的解決方案之一。SSO的定義是在多個應用系統中,使用者只需要登入一次就可以訪問所有相互信任的應用系統。 

利用Spring Security OAuth2的話,流程大概是這樣的,我自己畫了一個時序圖:

3. Spring Security OAuth 2

首先,明確幾個角色

Authorization Server :授權伺服器 

Resource Server :資源伺服器,就是使用者可以訪問的資源,那我們接下來單點登入來講,訂單管理系統、使用者管理系統、商品管理系統、客服管理系統等等這些都是資源伺服器

Client :客戶端,它是需要訪問資源伺服器的。如果是傳統的那種,可以把它理解成一個Java應用,如果是前後端分離的,可以把它理解為一個瀏覽器

3.1. 授權伺服器配置

最重要的依賴

<dependency>
    <groupId>org.springframework.security.oauth.boot</groupId>
    <artifactId>spring-security-oauth2-autoconfigure</artifactId>
    <version>2.5.5</version>
</dependency>

完整的pom.xml如下: 

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>auth-server</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>auth-server</name>

    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security.oauth.boot</groupId>
            <artifactId>spring-security-oauth2-autoconfigure</artifactId>
            <version>2.5.5</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

application.yml

server:
  port: 8080
  servlet:
    context-path: /auth   # User Accounts and Authentication (UAA)
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/sso?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: 123456
  jpa:
    database: mysql
    show-sql: true
  redis:
    host: 192.168.10.31
    port: 6379
    password: 123456
logging:
  level:
    org:
      springframework:
        security: debug

啟動類

package com.example.authserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * User Accounts and Authentication (UAA)
 *
 * @Author ChengJianSheng
 * @Date 2021/11/2
 */
@SpringBootApplication
public class AuthServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(AuthServerApplication.class, args);
    }

}

AuthorizationServerConfig.java

package com.example.authserver.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
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.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * @Author ChengJianSheng
 * @Date 2021/11/2
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Resource
    private DataSource dataSource;
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(clientDetailsService());
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore());
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.checkTokenAccess("permitAll()")   // isAuthenticated()
                .tokenKeyAccess("permitAll()")
                .allowFormAuthenticationForClients();
    }

    public ClientDetailsService clientDetailsService() {
        return new JdbcClientDetailsService(dataSource);
    }

    public TokenStore tokenStore() {
        return new RedisTokenStore(redisConnectionFactory);
    }

}

這裡,利用JdbcClientDetailsService從資料讀取客戶端

表結構如下:

CREATE TABLE `oauth_client_details`  (
  `client_id` varchar(256) COMMENT '客戶端ID',
  `resource_ids` varchar(256),
  `client_secret` varchar(256) COMMENT '客戶端金鑰',
  `scope` varchar(256),
  `authorized_grant_types` varchar(256) COMMENT '授權型別',
  `web_server_redirect_uri` varchar(256),
  `authorities` varchar(256),
  `access_token_validity` int(11) COMMENT 'access_token的有效時間',
  `refresh_token_validity` int(11) COMMENT 'refresh_token的有效時間',
  `additional_information` varchar(4096),
  `autoapprove` varchar(256) COMMENT '是否允許自動授權',
  PRIMARY KEY (`client_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; 

此處,先把token儲存到redis中

最後是WebSecurityConfig.java

package com.example.authserver.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @Author ChengJianSheng
 * @Date 2021/11/2
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("zhangsan")
                .password(passwordEncoder().encode("123456")).roles("ADMIN")
                .and()
                .passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}

瀏覽器中輸入

http://localhost:8080/auth/oauth/authorize?response_type=code&client_id=hello&redirect_uri=http://www.baidu.com&scope=all

輸入使用者名稱和密碼後

然後,就可以獲取token了

curl -d "client_id=hello&client_secret=123456&grant_type=authorization_code&code=CdQFnL&redirect_uri=http://www.baidu.com" -X POST http://localhost:8080/auth/oauth/token

3.2. 資源伺服器配置

一般來講,資源伺服器和授權伺服器是分開的,所以,這裡我們也分成兩個專案

maven依賴和簽名授權伺服器一樣,不再贅述

這裡定義了Controller,它就是我們接下來要訪問的資源

package com.example.resourceserver.controller;

import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;

/**
 * @Author ChengJianSheng
 * @Date 2021/11/2
 */
@RestController
public class OrderController {

    @GetMapping("/info")
    public String info(Principal principal, Authentication authentication) {
        System.out.println(principal);
        System.out.println(authentication.getPrincipal());
        System.out.println(authentication.getAuthorities());
        return "hello world";
    }
}

當使用者拿著access_token訪問我們的資源的時候,資源伺服器應該首先校驗此access_token的合法性,那它去哪兒校驗呢?當然是授權伺服器,因為token是授權伺服器發放的,驗證自然也應該去授權伺服器那裡驗證。

授權伺服器有幾個端點需要記住:

  • /oauth/authorize :授權
  • /oauth/token :發放令牌
  • /oauth/check_token :校驗令牌

由於資源服務和授權服務是分開的,所以,為了校驗令牌,需要遠端呼叫授權服務的校驗令牌端點,於是乎:

package com.example.resourceserver.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
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;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;

/**
 * @Author ChengJianSheng
 * @Date 2021/11/2
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    private static final String RESOURCE_ID = "order-resource";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(RESOURCE_ID)
                .tokenServices(resourceServerTokenServices())
                .stateless(true);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/order/**").access("#oauth2.hasScope('all')")
                .anyRequest().authenticated()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .csrf().disable();
    }

    public ResourceServerTokenServices resourceServerTokenServices() {
        RemoteTokenServices remoteTokenServices = new RemoteTokenServices();
        remoteTokenServices.setCheckTokenEndpointUrl("http://localhost:8080/auth/oauth/check_token");
        remoteTokenServices.setClientId("hello");
        remoteTokenServices.setClientSecret("123456");
        return remoteTokenServices;
    }
}

啟動資源伺服器後,訪問 http://localhost:8081/order/info

至此,授權服務和資源服務都配置完成

4. JWT

前面我們知道,為了校驗客戶端傳過來的token,資源伺服器需要遠端訪問授權伺服器的/oauth/check_token端點。這樣的話,客戶端每請求一次,資源伺服器就要遠端呼叫一次授權伺服器,這對授權伺服器來說壓力還是很大的。

因為現在授權伺服器生成的令牌僅僅只是一個標識,沒有任何實際的意義,為了知道這個token代表的資訊是什麼,就必須遠端呼叫/oauth/check_token查詢資料庫才知道,這樣的話客戶端每次訪問資源伺服器都要去授權伺服器那裡查一下這個token代表啥含義,隨著訪問量的上升這對授權伺服器來說是一個不小的壓力。為了解決這個問題,為了每次不再需要去遠端呼叫授權伺服器來校驗token,需要使用jwt來生成token。當然,jwt有也有一個缺點,那就是jwt生成的token很難撤銷。廢話就不多說了,直接改造之前的程式碼:

首先是授權伺服器的改造

新增一個TokenStore的配置類

package com.example.authserver.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

/**
 * @Author ChengJianSheng
 * @Date 2021/11/3
 */
@Configuration
public class TokenStoreConfig {

    private static final String SIGN_KEY = "123123";

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        jwtAccessTokenConverter.setSigningKey(SIGN_KEY);
        return jwtAccessTokenConverter;
    }
}

然後是AuthorizationServerConfig

package com.example.authserver.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
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.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * @Author ChengJianSheng
 * @Date 2021/11/2
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Resource
    private DataSource dataSource;
    @Autowired
    private TokenStore tokenStore;
    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(clientDetailsService());
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore).accessTokenConverter(jwtAccessTokenConverter);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.checkTokenAccess("permitAll()")   // isAuthenticated()
                .tokenKeyAccess("permitAll()")
                .allowFormAuthenticationForClients();
    }

    public ClientDetailsService clientDetailsService() {
        return new JdbcClientDetailsService(dataSource);
    }


}

有一點需要注意,如果採用密碼模式的話,就需要在端點配置那裡配上 authenticationManager 和 userDetailsService ,因為密碼模式是客戶端直接拿著資源擁有者的使用者名稱和密碼來獲取access_token,因此需要對客戶端傳的使用者名稱密碼進行驗證,也就是執行認證過程,所以需要authenticationManager 和 userDetailsService。如果業務上授權型別只支援授權碼的話,就沒有必要設定它們。

@Autowired
private UserDetailsService userDetailsService;
@Autowired
private AuthenticationManager authenticationManager;

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.withClientDetails(clientDetailsService());
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    endpoints //.authenticationManager(authenticationManager)   如果授權型別支援密碼模式,就需要配置
              //.userDetailsService(userDetailsService)         如果採用密碼模式,就需要配置
            .tokenStore(tokenStore)
            .accessTokenConverter(jwtAccessTokenConverter);

}

接下來是資源伺服器的改造

我們不再需要RemoteTokenServices來遠端呼叫授權伺服器了,也不需要配置tokenServices了

首先是,把授權伺服器中的TokenStoreConfig.java拷貝過來

package com.example.resourceserver.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

/**
 * @Author ChengJianSheng
 * @Date 2021/11/3
 */
@Configuration
public class TokenStoreConfig {

    private static final String SIGN_KEY = "123123";

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        jwtAccessTokenConverter.setSigningKey(SIGN_KEY);
        return jwtAccessTokenConverter;
    }
}

然後是ResourceServerConfig

package com.example.resourceserver.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
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;
import org.springframework.security.oauth2.provider.token.TokenStore;

/**
 * @Author ChengJianSheng
 * @Date 2021/11/2
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    private static final String RESOURCE_ID = "order-resource";

    @Autowired
    private TokenStore tokenStore;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(RESOURCE_ID)
                .tokenStore(tokenStore)
                .stateless(true);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/order/**").access("#oauth2.hasScope('all')")
                .anyRequest().authenticated()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .csrf().disable();
    }
}

配置了tokenStore了以後,就可以自己解析客戶端傳的token了,再也不用去訪問授權伺服器了。這個可以打端點除錯,或者日誌開debug,都可以看得到的。

改造完成,用postman試一下

5. 前後端分離

如果是傳統的那種沒有做前後端分離的,頁面都寫在服務端的那種應用,那麼那個Java Web應用就是OAuth2中的一個Client, 這個時候用 @EnableOAuth2Sso 就好了,不再贅述,也不是重點,現在的專案基本都是前後端分離的,所以我們的重點應該在前後端分離的專案中如何利用OAuth2實現單點登入。

前後端分離的話,OAuth2的客戶端就不再是一個Java Web應用了,而是前端伺服器,我們可以簡單的理解成瀏覽器。這個時候,閘道器除了做路由轉發以外,還要負責校驗token,至於鑑權可以放在閘道器,也可以放在各資源伺服器去做,推薦在閘道器做。

6.  推薦閱讀

https://projects.spring.io/spring-security-oauth/docs/oauth2.html 

https://docs.spring.io/spring-security/site/docs/current/reference/html5/#oauth2 

https://docs.spring.io/spring-security-oauth2-boot/docs/current/reference/html5/ 

https://github.com/spring-projects/spring-security/wiki/OAuth-2.0-Migration-Guide 

 

相關文章