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
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