前言
上一篇我們已經(jīng)用最簡單的方式并徘,搭建了一個(gè)授權(quán)方式是 client_credentials 的 Oauth2 的流程暗赶。那么現(xiàn)在,在此基礎(chǔ)上荐类,我們就再往前邁一步怖现,我們把 client 信息和 token 存儲(chǔ)到數(shù)據(jù)庫當(dāng)中,方便我們管理掉冶。并且密碼需要保證安全真竖,那么就需要加密脐雪。目標(biāo)明確,那我們開始吧恢共!
client&token存儲(chǔ)到數(shù)據(jù)庫
步驟:
- 數(shù)據(jù)庫準(zhǔn)備:只創(chuàng)建我們需要用到的表
- 添加數(shù)據(jù)庫相關(guān)依賴:使用 mysql 數(shù)據(jù)庫
- Oauth 存儲(chǔ)配置的設(shè)置
- 驗(yàn)證
數(shù)據(jù)庫準(zhǔn)備
在本地?cái)?shù)據(jù)庫战秋,創(chuàng)建兩張表:
- 一張表存儲(chǔ) client 相關(guān)信息
- 另一張表存儲(chǔ) token
# client 相關(guān)信息
create table oauth_client_details
(
client_id VARCHAR(256) PRIMARY KEY comment '必填,Oauth2 client_id',
resource_ids VARCHAR(256) comment '可選讨韭,資源id集合脂信,多個(gè)資源用英文逗號(hào)隔開',
client_secret VARCHAR(256) comment '必填,Oauth2 client_secret',
scope VARCHAR(256) comment '必填透硝,Oauth2 權(quán)限范圍狰闪,比如 read,write等可自定義',
authorized_grant_types VARCHAR(256) comment '必填濒生,Oauth2 授權(quán)類型埋泵,支持類型:authorization_code,password,refresh_token,implicit,client_credentials,多個(gè)用英文逗號(hào)隔開',
web_server_redirect_uri VARCHAR(256) comment '可選罪治,客戶端的重定向URI,當(dāng)grant_type為authorization_code或implicit時(shí),此字段是需要的',
authorities VARCHAR(256) comment '可選丽声,指定客戶端所擁有的Spring Security的權(quán)限值',
access_token_validity INTEGER comment '可選,access_token的有效時(shí)間值(單位:秒)觉义,不填寫框架(類refreshTokenValiditySeconds)默認(rèn)12小時(shí)',
refresh_token_validity INTEGER comment '可選雁社,refresh_token的有效時(shí)間值(單位:秒),不填寫框架(類refreshTokenValiditySeconds)默認(rèn)30天',
additional_information VARCHAR(4096) comment '預(yù)留字段晒骇,格式必須是json',
autoapprove VARCHAR(256) comment '該字段適用于grant_type="authorization_code"的情況下霉撵,用戶是否自動(dòng)approve操作'
);
# token 存儲(chǔ)
create table oauth_access_token
(
token_id VARCHAR(256) comment 'MD5加密后存儲(chǔ)的access_token',
token BLOB comment 'access_token序列化的二進(jìn)制數(shù)據(jù)格式',
authentication_id VARCHAR(256) PRIMARY KEY comment '主鍵,其值是根據(jù)當(dāng)前的username(如果有),client_id與scope通過MD5加密生成的,具體實(shí)現(xiàn)參見DefaultAuthenticationKeyGenerator',
user_name VARCHAR(256),
client_id VARCHAR(256),
authentication BLOB comment '將OAuth2Authentication對象序列化后的二進(jìn)制數(shù)據(jù)',
refresh_token VARCHAR(256) comment 'refresh_token的MD5加密后的數(shù)據(jù)'
);
之后洪囤,我們需要添加自定義 Client 信息徒坡。本次演示添加的 Client 信息如下(盡量能不配置就不配置):
INSERT INTO oauth_client_details (client_id, resource_ids, client_secret, scope, authorized_grant_types, web_server_redirect_uri, authorities, access_token_validity, refresh_token_validity, additional_information, autoapprove) VALUES ('gold', 'res', '{noop}123456', 'write', 'client_credentials', null, null, null, null, null, null);
說明
- 在官方給出的源碼當(dāng)中箍鼓,是有對應(yīng)的 schema.sql 文件崭参,這里只創(chuàng)建涉及我們示例中需要的表
- 對兩張表的操作,我們可以去看這兩個(gè)類:JdbcClientDetailsService & JdbcTokenStore
- 此外本示例款咖,添加了 resource_ids 何暮,注意在配置
ResourceServerSecurityConfigurer
中對應(yīng)
Pom
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
認(rèn)證服務(wù)器代碼修改
@Configuration
@EnableAuthorizationServer
public class MyAuthorizationServerConfigurer extends AuthorizationServerConfigurerAdapter {
private final DataSource dataSource;
public MyAuthorizationServerConfigurer(DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.jdbc(dataSource);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(new JdbcTokenStore(dataSource));
}
}
上述代碼只顯示改動(dòng)的部分,修改 client 的配置和 tokenStore 的配置铐殃,都進(jìn)行添加數(shù)據(jù)源即可
請求 token
下面的請求是在 postman 中進(jìn)行的海洼。 base_url 為設(shè)置的全局變量,實(shí)際為 http://127.0.0.1:8080
獲取資源
觀察數(shù)據(jù)庫
由于 token 在數(shù)據(jù)庫是存儲(chǔ)的是二進(jìn)制形式富腊,但是我們通過 client_id 數(shù)據(jù)坏逢,可以看出是我們剛剛請求的 client。
到此為止我們已經(jīng)是實(shí)現(xiàn)了,把 client 及 token 信息存儲(chǔ)到數(shù)據(jù)庫了是整,這樣更便于我們對 client 及 token 數(shù)據(jù)的管理肖揣。但是數(shù)據(jù)庫存儲(chǔ)明文密碼是不安全,那么接下來浮入,我們對 client_secret 進(jìn)行加密龙优。
client_secret 加密
配置 passwordEncoder
SpringBoot Oauth 本身支持的加密算法有很多種,詳細(xì)信息可以看類 PasswordEncoderFactories
事秀,包括我們最常用的 MD5彤断、SHA 等,我們使用 bcrypt 加密算法易迹, 那么直接配置支持全部算法的 passwordEncoder 宰衙,即 DelegatingPasswordEncoder
。
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.jdbc(dataSource).passwordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder());
}
加密 client_secret
既然我們這次使用 bcrypt 加密睹欲, 直接可以找到 BCryptPasswordEncoder
供炼,通過它可以給我們的密碼進(jìn)行加密,并把密碼存儲(chǔ)于數(shù)據(jù)庫當(dāng)中句伶。
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class PasswordEncodeUtil {
private static final BCryptPasswordEncoder bcryptEncoder = new BCryptPasswordEncoder();
public static String bcryptEncode(String password) {
return bcryptEncoder.encode(password);
}
public static String genOauthEncodePwd(String password) {
return "{bcrypt}" + bcryptEncode(password);
}
public static void main(String[] args) {
String oriPwd = "123456";
System.out.println(genOauthEncodePwd(oriPwd));
}
}
原密碼:123456
加密后密碼:{bcrypt}10$NPxtsEUMmBGTlzVXlT.scubSCXNEDlBAq2r2t7iQFB/.RaNBlh0nO
注意:加密密碼的前綴 大括號(hào) "{xxx}"劲蜻,是指定算法名稱陆淀。因?yàn)榭蚣苤С侄喾N算法那么必須需要帶有算法前綴考余。
請求獲取 token
下面的請求是在 postman 中進(jìn)行的。 base_url 為設(shè)置的全局變量轧苫,實(shí)際為 http://127.0.0.1:8080
請求資源
小結(jié)
本文主要是以 client_credentials 的授權(quán)方式楚堤,把 client 和 token 信息存儲(chǔ)在數(shù)據(jù)庫當(dāng)中,來方便我們管理含懊。同時(shí)身冬,為了保證密碼的安全,我們把 client_secret 用 bcrypt 算法進(jìn)行了加密操作岔乔,并存儲(chǔ)到數(shù)據(jù)庫當(dāng)中酥筝。挺簡單的吧,那動(dòng)起來雏门,實(shí)現(xiàn)一下吧嘿歌!
個(gè)人水平有限,歡迎大家指正茁影,一起交流哦~~~
demo:https://github.com/goldpumpkin/learn-demo/tree/master/springboot-oauth
Reference: