RuoYi開發(fā)框架與第三方認(rèn)證系統(tǒng)集成起來的簡(jiǎn)單方法
背景
若依框架現(xiàn)在很火,很多團(tuán)隊(duì)與個(gè)人都使用它。作者看了看它最新的代碼,它的認(rèn)證方式有所不同,前后臺(tái)分離版本使用的是shiro(具體代碼:https://gitee.com/y_project/RuoYi/tree/master/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro),微服務(wù)版本使用的是JWT(具體代碼:https://gitee.com/y_project/RuoYi-Cloud/blob/master/ruoyi-common/ruoyi-common-security/src/main/java/com/ruoyi/common/security/service/TokenService.java#L44)。不過很多時(shí)候,我們的組織或公司都已經(jīng)構(gòu)建了自己的認(rèn)證系統(tǒng),這個(gè)時(shí)候如何把我們的若依開發(fā)的系統(tǒng)和我們的認(rèn)證系統(tǒng)集成在一起呢。這篇文章就給出全過程保姆式的方法演示。
準(zhǔn)備工作
搭建oauth2的認(rèn)證服務(wù)
這個(gè)服務(wù)我們是基于spring-security-oauth2來實(shí)現(xiàn)的。依賴pom.xml如下:
<!-- spring security 安全認(rèn)證 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- spring security oauth2 開放授權(quán) -->
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>${security.oauth2.version}</version>
</dependency>
oauth2認(rèn)證服務(wù)器的配置:
認(rèn)證服務(wù)配置
服務(wù)測(cè)試
訪問/oauth/token使用參數(shù)列表如下,注意我們這個(gè)地方grant_type用的是password。
OAuth 2.0中常見的grant_type:
- authorization_code:用于通過授權(quán)碼獲取訪問令牌,通常用于Web應(yīng)用程序或本機(jī)應(yīng)用程序中。
- password:用于通過用戶名和密碼獲取訪問令牌,通常用于受信任的客戶端(如移動(dòng)應(yīng)用程序)中。
- client_credentials:用于客戶端憑據(jù)(如應(yīng)用程序密鑰)獲取訪問令牌,通常用于機(jī)器到機(jī)器通信中。
- refresh_token:用于使用刷新令牌獲取新訪問令牌,通常用于在訪問令牌過期后更新訪問令牌。
client_id | |
client_secret | |
grant_type | password |
scope | |
username | |
password |
測(cè)試授權(quán)服務(wù)器的接口
正式工作
下面以前后臺(tái)分離版本的若依為例。
- 增加依賴:
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
- 去掉shiro相關(guān)代碼(因?yàn)槲覀兪腔趕pring-security-oauth來實(shí)現(xiàn)與認(rèn)證服務(wù)器的對(duì)接)。
- 在WebsecurityConfig類上添加注解@EnableOAuth2Sso。
改造websecurityconfig
- application.yml中添加客戶端配置。
security:
oauth2:
client:
clientId: *****
clientSecret: *****
accessTokenUri: ${auth-server}/oauth/token
userAuthorizationUri: ${auth-server}/oauth/authorize
resource:
userInfoUri: ${auth-server}/system/user/get
redirectUri: *****
其中userInfoUri是認(rèn)證服務(wù)器提供的獲取用戶信息的接口。
- 修改ruoyi-ui的login.js中的登錄方法,使得它訪問認(rèn)證服務(wù)器獲取token。
// 登錄方法
export function login(username, password, code, uuid) {
return root_request({
url: '/oauth/token',
method: 'post',
params: { username, password, code, uuid, client_id, client_secret, grant_type, scope }
})
}
上面的root_request是我們新建的一個(gè)axios實(shí)例,它訪問的是認(rèn)證服務(wù)器,而不是ruoyi的后臺(tái)。
const service = axios.create({
// axios中請(qǐng)求配置有baseURL選項(xiàng),表示請(qǐng)求URL公共部分
baseURL: '/cgroot',
// 超時(shí)
timeout: 10000
})
- vue.config.js中添加新的路由。
devServer: {
host: '0.0.0.0',
port: port,
proxy: {
// detail: https://cli.vuejs.org/config/#devserver-proxy
[process.env.VUE_APP_BASE_API]: {
target: `http://localhost:8080`,
changeOrigin: true,
pathRewrite: {
['^' + process.env.VUE_APP_BASE_API]: ''
}
},
['/cgroot']: {
target: `http://localhost:8880`,
changeOrigin: true,
pathRewrite: {
['^' + '/cgroot']: ''
}
}
},
disableHostCheck: true
},
- 獲取用戶的方法也要做修改。
/**
* 獲取用戶
**/
public static LoginUser getLoginUser()
{
try
{
OAuth2Authentication authentication = (OAuth2Authentication)getAuthentication();
Map<String, Object> userMap =
(Map<String, Object>) ((Map<String, Object>) authentication
.getUserAuthentication().getDetails()).get("data");
SysUser user = new SysUser();
Integer userId = (Integer) userMap.get("userId");
Integer proxyId = (Integer) userMap.get("proxyId");
String userName = (String) userMap.get("userName");
String avatar = (String) userMap.get("avatar");
String phonenumber = (String) userMap.get("phonenumber");
String email = (String) userMap.get("email");
String nickName = (String)userMap.get("nickName");
user.setUserId(Long.parseLong(String.valueOf(userId)));
user.setNickName(nickName);
user.setAvatar(avatar);
user.setPhonenumber(phonenumber);
user.setEmail(email);
user.setUserName(userName);
user.setProxyId(Long.parseLong(String.valueOf(proxyId)));
LoginUser loginUser = new LoginUser();
loginUser.setUser(user);
return loginUser;
}
catch (Exception e)
{
throw new CustomException("獲取用戶信息異常", HttpStatus.UNAUTHORIZED);
}
}
這樣便實(shí)現(xiàn)了ruoyi開發(fā)的系統(tǒng)與我們的第三方認(rèn)證服務(wù)的對(duì)接。當(dāng)然上面實(shí)現(xiàn)的是通過grant_type為password方式獲取token,如果通過authorization_code獲取token的話,上面的login方法里面需要用到重定向回來得到的code。
后記
上面的實(shí)現(xiàn)的關(guān)鍵是EnableOAuth2Sso這個(gè)注解,EnableOAuth2Sso是一個(gè)Spring Security的注解,用于在基于OAuth2的單點(diǎn)登錄(SSO)流程中啟用OAuth2 SSO支持。它實(shí)現(xiàn)在SpringSecurityFilterChain過濾器鏈上添加OAuth2ClientAuthenticationProcessingFilter這個(gè)用于登錄認(rèn)證的Filter。它攔截用戶的請(qǐng)求,并通過access_token獲取認(rèn)證服務(wù)器上的用戶信息,并創(chuàng)建Authentication登錄后憑證,并完成principal存儲(chǔ),讓人感覺像ruoyi直接訪問數(shù)據(jù)庫(kù)拿到用戶信息一樣。
創(chuàng)建Authentication
參考文章
https://www.cnblogs.com/trust-freedom/p/12002089.html(EnableOAuth2Sso原理)。
https://www.rfc-editor.org/rfc/rfc6749 (OAuth2 RFC)。