SpringSecurity在分布式環(huán)境下的使用流程分析
參考
來(lái)源于黑馬程序員: 手把手教你精通新版SpringSecurity
分布式認(rèn)證概念說(shuō)明
分布式認(rèn)證,即我們常說(shuō)的單點(diǎn)登錄,簡(jiǎn)稱(chēng)SSO,指的是在多應(yīng)用系統(tǒng)的項(xiàng)目中,用戶(hù)只需要登錄一次,就可以訪(fǎng) 問(wèn)所有互相信任的應(yīng)用系統(tǒng)。
分布式認(rèn)證流程圖
首先,我們要明確,在分布式項(xiàng)目中,每臺(tái)服務(wù)器都有各自獨(dú)立的session,而這些session之間是無(wú)法直接共享資 源的,所以,session通常不能被作為單點(diǎn)登錄的技術(shù)方案。最合理的單點(diǎn)登錄方案流程如下圖所示:

總結(jié)一下,單點(diǎn)登錄的實(shí)現(xiàn)分兩大環(huán)節(jié):
- **用戶(hù)認(rèn)證:**這一環(huán)節(jié)主要是用戶(hù)向認(rèn)證服務(wù)器發(fā)起認(rèn)證請(qǐng)求,認(rèn)證服務(wù)器給用戶(hù)返回一個(gè)成功的令牌token, 主要在認(rèn)證服務(wù)器中完成,即圖中的A系統(tǒng),注意A系統(tǒng)只能有一個(gè)。
- **身份校驗(yàn):**這一環(huán)節(jié)是用戶(hù)攜帶token去訪(fǎng)問(wèn)其他服務(wù)器時(shí),在其他服務(wù)器中要對(duì)token的真?zhèn)芜M(jìn)行檢驗(yàn),主 要在資源服務(wù)器中完成,即圖中的B系統(tǒng),這里B系統(tǒng)可以有很多個(gè)。
JWT介紹
概念說(shuō)明
從分布式認(rèn)證流程中,我們不難發(fā)現(xiàn),這中間起最關(guān)鍵作用的就是token,token的安全與否,直接關(guān)系到系統(tǒng)的 健壯性,這里我們選擇使用JWT來(lái)實(shí)現(xiàn)token的生成和校驗(yàn)。 JWT,全稱(chēng)JSON Web Token,官網(wǎng)地址https://jwt.io,是一款出色的分布式身份校驗(yàn)方案??梢陨蓆oken,也可以解析檢驗(yàn)token。
JWT生成的token由三部分組成
- 頭部:主要設(shè)置一些規(guī)范信息,簽名部分的編碼格式就在頭部中聲明。
- 載荷:token中存放有效信息的部分,比如用戶(hù)名,用戶(hù)角色,過(guò)期時(shí)間等,但是不要放密碼,會(huì)泄露!
- 簽名:將頭部與載荷分別采用base64編碼后,用“.”相連,再加入鹽,最后使用頭部聲明的編碼類(lèi)型進(jìn)行編 碼,就得到了簽名。【通過(guò)隨機(jī)鹽在進(jìn)行加密】
JWT生成token的安全性分析
從JWT生成的token組成上來(lái)看,要想避免token被偽造,主要就得看簽名部分了,而簽名部分又有三部分組成,其中頭部和載荷的base64編碼,幾乎是透明的,毫無(wú)安全性可言,那么最終守護(hù)token安全的重?fù)?dān)就落在了加入的鹽上面了!
試想:如果生成token所用的鹽與解析token時(shí)加入的鹽是一樣的。豈不是類(lèi)似于中國(guó)人民銀行把人民幣防偽技術(shù) 公開(kāi)了?大家可以用這個(gè)鹽來(lái)解析token,就能用來(lái)偽造token。這時(shí),我們就需要對(duì)鹽采用非對(duì)稱(chēng)加密的方式進(jìn)行加密,以達(dá)到生成token與校驗(yàn)token方所用的鹽不一致的安全效果!
非對(duì)稱(chēng)加密RSA介紹
- **基本原理:**同時(shí)生成兩把密鑰:私鑰和公鑰,私鑰隱秘保存,公鑰可以下發(fā)給信任客戶(hù)端
- 私鑰加密,持有私鑰或公鑰才可以解密
- 公鑰加密,持有私鑰才可解密
- 優(yōu)點(diǎn):安全,難以破解
- 缺點(diǎn):算法比較耗時(shí),為了安全,可以接受
- 歷史:三位數(shù)學(xué)家Rivest、Shamir 和 Adleman 設(shè)計(jì)了一種算法,可以實(shí)現(xiàn)非對(duì)稱(chēng)加密。這種算法用他們?nèi)?個(gè)人的名字縮寫(xiě):RSA。
【總結(jié)】:也就是說(shuō),我們加密信息的時(shí)候,使用的是公鑰,而驗(yàn)證token真?zhèn)蔚臅r(shí)候,使用的是公鑰
JWT相關(guān)工具類(lèi)
jar包
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.10.7</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.10.7</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.10.7</version>
<scope>runtime</scope>
</dependency>載荷對(duì)象
/**
* 為了方便后期獲取token中的用戶(hù)信息,將token中載荷部分單獨(dú)封裝成一個(gè)對(duì)象
*/
@Data
public class Payload<T> {
}JWT工具類(lèi)
/**
* 生成token以及校驗(yàn)token相關(guān)方法
*/
public class JwtUtils {
private static final String JWT_PAYLOAD_USER_KEY = "user";
/**
* 私鑰加密token
*
* @param userInfo 載荷中的數(shù)據(jù)
* @param privateKey 私鑰
* @param expire 過(guò)期時(shí)間,單位分鐘
* @return JWT
*/
public static String generateTokenExpireInMinutes(Object userInfo, PrivateKey privateKey, int expire) {
return Jwts.builder()
.claim(JWT_PAYLOAD_USER_KEY, JsonUtils.toString(userInfo))
.setId(createJTI())
.setExpiration(DateTime.now().plusMinutes(expire).toDate())
.signWith(privateKey, SignatureAlgorithm.RS256)
.compact();
}
/**
* 私鑰加密token
*
* @param userInfo 載荷中的數(shù)據(jù)
* @param privateKey 私鑰
* @param expire 過(guò)期時(shí)間,單位秒
* @return JWT
*/
public static String generateTokenExpireInSeconds(Object userInfo, PrivateKey privateKey, int expire) {
return Jwts.builder()
.claim(JWT_PAYLOAD_USER_KEY, JsonUtils.toString(userInfo))
.setId(createJTI())
.setExpiration(DateTime.now().plusSeconds(expire).toDate())
.signWith(privateKey, SignatureAlgorithm.RS256)
.compact();
}
/**
* 公鑰解析token
*
* @param token 用戶(hù)請(qǐng)求中的token
* @param publicKey 公鑰
* @return Jws<Claims>
*/
private static Jws<Claims> parserToken(String token, PublicKey publicKey) {
return Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
}
private static String createJTI() {
return new String(Base64.getEncoder().encode(UUID.randomUUID().toString().getBytes()));
}
/**
* 獲取token中的用戶(hù)信息
*
* @param token 用戶(hù)請(qǐng)求中的令牌
* @param publicKey 公鑰
* @return 用戶(hù)信息
*/
public static <T> Payload<T> getInfoFromToken(String token, PublicKey publicKey, Class<T> userType) {
Jws<Claims> claimsJws = parserToken(token, publicKey);
Claims body = claimsJws.getBody();
Payload<T> claims = new Payload<>();
claims.setId(body.getId());
claims.setUserInfo(JsonUtils.toBean(body.get(JWT_PAYLOAD_USER_KEY).toString(), userType));
claims.setExpiration(body.getExpiration());
return claims;
}
/**
* 獲取token中的載荷信息
*
* @param token 用戶(hù)請(qǐng)求中的令牌
* @param publicKey 公鑰
* @return 用戶(hù)信息
*/
public static <T> Payload<T> getInfoFromToken(String token, PublicKey publicKey) {
Jws<Claims> claimsJws = parserToken(token, publicKey);
Claims body = claimsJws.getBody();
Payload<T> claims = new Payload<>();
claims.setId(body.getId());
claims.setExpiration(body.getExpiration());
return claims;
}
}RSA工具類(lèi)
非對(duì)稱(chēng)加密工具列
public class RsaUtils {
private static final int DEFAULT_KEY_SIZE = 2048;
/**
* 從文件中讀取公鑰
*
* @param filename 公鑰保存路徑,相對(duì)于classpath
* @return 公鑰對(duì)象
* @throws Exception
*/
public static PublicKey getPublicKey(String filename) throws Exception {
byte[] bytes = readFile(filename);
return getPublicKey(bytes);
}
/**
* 從文件中讀取密鑰
*
* @param filename 私鑰保存路徑,相對(duì)于classpath
* @return 私鑰對(duì)象
* @throws Exception
*/
public static PrivateKey getPrivateKey(String filename) throws Exception {
byte[] bytes = readFile(filename);
return getPrivateKey(bytes);
}
/**
* 獲取公鑰
*
* @param bytes 公鑰的字節(jié)形式
* @return
* @throws Exception
*/
private static PublicKey getPublicKey(byte[] bytes) throws Exception {
bytes = Base64.getDecoder().decode(bytes);
X509EncodedKeySpec spec = new X509EncodedKeySpec(bytes);
KeyFactory factory = KeyFactory.getInstance("RSA");
return factory.generatePublic(spec);
}
/**
* 獲取密鑰
*
* @param bytes 私鑰的字節(jié)形式
* @return
* @throws Exception
*/
private static PrivateKey getPrivateKey(byte[] bytes) throws NoSuchAlgorithmException, InvalidKeySpecException {
bytes = Base64.getDecoder().decode(bytes);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytes);
KeyFactory factory = KeyFactory.getInstance("RSA");
return factory.generatePrivate(spec);
}
/**
* 根據(jù)密文,生存rsa公鑰和私鑰,并寫(xiě)入指定文件
*
* @param publicKeyFilename 公鑰文件路徑
* @param privateKeyFilename 私鑰文件路徑
* @param secret 生成密鑰的密文
*/
public static void generateKey(String publicKeyFilename, String privateKeyFilename, String secret, int keySize) throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
SecureRandom secureRandom = new SecureRandom(secret.getBytes());
keyPairGenerator.initialize(Math.max(keySize, DEFAULT_KEY_SIZE), secureRandom);
KeyPair keyPair = keyPairGenerator.genKeyPair();
// 獲取公鑰并寫(xiě)出
byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
publicKeyBytes = Base64.getEncoder().encode(publicKeyBytes);
writeFile(publicKeyFilename, publicKeyBytes);
// 獲取私鑰并寫(xiě)出
byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
privateKeyBytes = Base64.getEncoder().encode(privateKeyBytes);
writeFile(privateKeyFilename, privateKeyBytes);
}
private static byte[] readFile(String fileName) throws Exception {
return Files.readAllBytes(new File(fileName).toPath());
}
private static void writeFile(String destPath, byte[] bytes) throws IOException {
File dest = new File(destPath);
if (!dest.exists()) {
dest.createNewFile();
}
Files.write(dest.toPath(), bytes);
}
}SpringSecurity+JWT+RSA分布式認(rèn)證思路分析
SpringSecurity主要是通過(guò)過(guò)濾器來(lái)實(shí)現(xiàn)功能的!我們要找到SpringSecurity實(shí)現(xiàn)認(rèn)證和校驗(yàn)身份的過(guò)濾器! 回顧集中式認(rèn)證流程
用戶(hù)認(rèn)證
使用UsernamePasswordAuthenticationFilter過(guò)濾器中attemptAuthentication方法實(shí)現(xiàn)認(rèn)證功能,該過(guò)濾 器父類(lèi)中successfulAuthentication方法實(shí)現(xiàn)認(rèn)證成功后的操作。
身份校驗(yàn)
使用BasicAuthenticationFilter過(guò)濾器中doFilterInternal方法驗(yàn)證是否登錄,以決定能否進(jìn)入后續(xù)過(guò)濾器。 分析分布式認(rèn)證流程
用戶(hù)認(rèn)證
由于,分布式項(xiàng)目,多數(shù)是前后端分離的架構(gòu)設(shè)計(jì),我們要滿(mǎn)足可以接受異步post的認(rèn)證請(qǐng)求參數(shù),需要修 改UsernamePasswordAuthenticationFilter過(guò)濾器中attemptAuthentication方法,讓其能夠接收請(qǐng)求體。
另外,默認(rèn)successfulAuthentication方法在認(rèn)證通過(guò)后,是把用戶(hù)信息直接放入session就完事了,現(xiàn)在我 們需要修改這個(gè)方法,在認(rèn)證通過(guò)后生成token并返回給用戶(hù)。
身份校驗(yàn)
原來(lái)BasicAuthenticationFilter過(guò)濾器中doFilterInternal方法校驗(yàn)用戶(hù)是否登錄,就是看session中是否有用 戶(hù)信息,我們要修改為,驗(yàn)證用戶(hù)攜帶的token是否合法,并解析出用戶(hù)信息,交給SpringSecurity,以便于 后續(xù)的授權(quán)功能可以正常使用。
SpringSecurity+JWT+RSA分布式認(rèn)證實(shí)現(xiàn)
創(chuàng)建父工程并導(dǎo)入jar包
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.itheima</groupId>
<artifactId>springboot_security_jwt_rsa_parent</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>heima_common</module>
<module>heima_auth_server</module>
<module>heima_source_product</module>
</modules>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/>
</parent>
</project>通用模塊
創(chuàng)建通用子模塊并導(dǎo)入JWT相關(guān)jar包
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springboot_security_jwt_rsa_parent</artifactId>
<groupId>com.itheima</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>heima_common</artifactId>
<dependencies>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.10.7</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.10.7</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.10.7</version>
<scope>runtime</scope>
</dependency>
<!--jackson包-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.9</version>
</dependency>
<!--日志包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
</project>導(dǎo)入工具類(lèi)
工具類(lèi)如下

Payload.java
/**
* 為了方便后期獲取token中的用戶(hù)信息,將token中載荷部分單獨(dú)封裝成一個(gè)對(duì)象
*/
@Data
public class Payload<T> {
private String id;
private T userInfo;
private Date expiration;
}JsonUtil.java
public class JsonUtils {
public static final ObjectMapper mapper = new ObjectMapper();
private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class);
public static String toString(Object obj) {
if (obj == null) {
return null;
}
if (obj.getClass() == String.class) {
return (String) obj;
}
try {
return mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
logger.error("json序列化出錯(cuò):" + obj, e);
return null;
}
}
public static <T> T toBean(String json, Class<T> tClass) {
try {
return mapper.readValue(json, tClass);
} catch (IOException e) {
logger.error("json解析出錯(cuò):" + json, e);
return null;
}
}
public static <E> List<E> toList(String json, Class<E> eClass) {
try {
return mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, eClass));
} catch (IOException e) {
logger.error("json解析出錯(cuò):" + json, e);
return null;
}
}
public static <K, V> Map<K, V> toMap(String json, Class<K> kClass, Class<V> vClass) {
try {
return mapper.readValue(json, mapper.getTypeFactory().constructMapType(Map.class, kClass, vClass));
} catch (IOException e) {
logger.error("json解析出錯(cuò):" + json, e);
return null;
}
}
public static <T> T nativeRead(String json, TypeReference<T> type) {
try {
return mapper.readValue(json, type);
} catch (IOException e) {
logger.error("json解析出錯(cuò):" + json, e);
return null;
}
}
}jwtUitls.java
public class JwtUtils {
private static final String JWT_PAYLOAD_USER_KEY = "user";
/**
* 私鑰加密token
*
* @param userInfo 載荷中的數(shù)據(jù)
* @param privateKey 私鑰
* @param expire 過(guò)期時(shí)間,單位分鐘
* @return JWT
*/
public static String generateTokenExpireInMinutes(Object userInfo, PrivateKey privateKey, int expire) {
return Jwts.builder()
.claim(JWT_PAYLOAD_USER_KEY, JsonUtils.toString(userInfo))
.setId(createJTI())
.setExpiration(DateTime.now().plusMinutes(expire).toDate())
.signWith(privateKey, SignatureAlgorithm.RS256)
.compact();
}
/**
* 私鑰加密token
*
* @param userInfo 載荷中的數(shù)據(jù)
* @param privateKey 私鑰
* @param expire 過(guò)期時(shí)間,單位秒
* @return JWT
*/
public static String generateTokenExpireInSeconds(Object userInfo, PrivateKey privateKey, int expire) {
return Jwts.builder()
.claim(JWT_PAYLOAD_USER_KEY, JsonUtils.toString(userInfo))
.setId(createJTI())
.setExpiration(DateTime.now().plusSeconds(expire).toDate())
.signWith(privateKey, SignatureAlgorithm.RS256)
.compact();
}
/**
* 公鑰解析token
*
* @param token 用戶(hù)請(qǐng)求中的token
* @param publicKey 公鑰
* @return Jws<Claims>
*/
private static Jws<Claims> parserToken(String token, PublicKey publicKey) {
return Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
}
private static String createJTI() {
return new String(Base64.getEncoder().encode(UUID.randomUUID().toString().getBytes()));
}
/**
* 獲取token中的用戶(hù)信息
*
* @param token 用戶(hù)請(qǐng)求中的令牌
* @param publicKey 公鑰
* @return 用戶(hù)信息
*/
public static <T> Payload<T> getInfoFromToken(String token, PublicKey publicKey, Class<T> userType) {
Jws<Claims> claimsJws = parserToken(token, publicKey);
Claims body = claimsJws.getBody();
Payload<T> claims = new Payload<>();
claims.setId(body.getId());
claims.setUserInfo(JsonUtils.toBean(body.get(JWT_PAYLOAD_USER_KEY).toString(), userType));
claims.setExpiration(body.getExpiration());
return claims;
}
/**
* 獲取token中的載荷信息
*
* @param token 用戶(hù)請(qǐng)求中的令牌
* @param publicKey 公鑰
* @return 用戶(hù)信息
*/
public static <T> Payload<T> getInfoFromToken(String token, PublicKey publicKey) {
Jws<Claims> claimsJws = parserToken(token, publicKey);
Claims body = claimsJws.getBody();
Payload<T> claims = new Payload<>();
claims.setId(body.getId());
claims.setExpiration(body.getExpiration());
return claims;
}
}RsaUtils.java
public class RsaUtils {
private static final int DEFAULT_KEY_SIZE = 2048;
/**
* 從文件中讀取公鑰
*
* @param filename 公鑰保存路徑,相對(duì)于classpath
* @return 公鑰對(duì)象
* @throws Exception
*/
public static PublicKey getPublicKey(String filename) throws Exception {
byte[] bytes = readFile(filename);
return getPublicKey(bytes);
}
/**
* 從文件中讀取密鑰
*
* @param filename 私鑰保存路徑,相對(duì)于classpath
* @return 私鑰對(duì)象
* @throws Exception
*/
public static PrivateKey getPrivateKey(String filename) throws Exception {
byte[] bytes = readFile(filename);
return getPrivateKey(bytes);
}
/**
* 獲取公鑰
*
* @param bytes 公鑰的字節(jié)形式
* @return
* @throws Exception
*/
private static PublicKey getPublicKey(byte[] bytes) throws Exception {
bytes = Base64.getDecoder().decode(bytes);
X509EncodedKeySpec spec = new X509EncodedKeySpec(bytes);
KeyFactory factory = KeyFactory.getInstance("RSA");
return factory.generatePublic(spec);
}
/**
* 獲取密鑰
*
* @param bytes 私鑰的字節(jié)形式
* @return
* @throws Exception
*/
private static PrivateKey getPrivateKey(byte[] bytes) throws NoSuchAlgorithmException, InvalidKeySpecException {
bytes = Base64.getDecoder().decode(bytes);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytes);
KeyFactory factory = KeyFactory.getInstance("RSA");
return factory.generatePrivate(spec);
}
/**
* 根據(jù)密文,生存rsa公鑰和私鑰,并寫(xiě)入指定文件
*
* @param publicKeyFilename 公鑰文件路徑
* @param privateKeyFilename 私鑰文件路徑
* @param secret 生成密鑰的密文
*/
public static void generateKey(String publicKeyFilename, String privateKeyFilename, String secret, int keySize) throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
SecureRandom secureRandom = new SecureRandom(secret.getBytes());
keyPairGenerator.initialize(Math.max(keySize, DEFAULT_KEY_SIZE), secureRandom);
KeyPair keyPair = keyPairGenerator.genKeyPair();
// 獲取公鑰并寫(xiě)出
byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
publicKeyBytes = Base64.getEncoder().encode(publicKeyBytes);
writeFile(publicKeyFilename, publicKeyBytes);
// 獲取私鑰并寫(xiě)出
byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
privateKeyBytes = Base64.getEncoder().encode(privateKeyBytes);
writeFile(privateKeyFilename, privateKeyBytes);
}
private static byte[] readFile(String fileName) throws Exception {
return Files.readAllBytes(new File(fileName).toPath());
}
private static void writeFile(String destPath, byte[] bytes) throws IOException {
File dest = new File(destPath);
if (!dest.exists()) {
dest.createNewFile();
}
Files.write(dest.toPath(), bytes);
}
}在通用子模塊中編寫(xiě)測(cè)試類(lèi)生成rsa公鑰和私鑰
public class RsaUtilsTest {
private String publicFile = "D:\\auth_key\\rsa_key.pub";
private String privateFile = "D:\\auth_key\\rsa_key";
@Test
public void generateKey() throws Exception {
RsaUtils.generateKey(publicFile, privateFile, "heima", 2048);
}
}執(zhí)行后查看D:\auth_key目錄發(fā)現(xiàn)私鑰和公鑰文件生成成功

認(rèn)證服務(wù)
創(chuàng)建認(rèn)證服務(wù)工程并導(dǎo)入jar包
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springboot_security_jwt_rsa_parent</artifactId>
<groupId>com.itheima</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>heima_auth_server</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>com.itheima</groupId>
<artifactId>heima_common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
</dependencies>
</project>創(chuàng)建認(rèn)證服務(wù)配置文件
server:
port: 9001
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql:///security_authority
username: root
password: root
mybatis:
type-aliases-package: com.itheima.domain
configuration:
map-underscore-to-camel-case: true
logging:
level:
com.itheima: debug
rsa:
key:
pubKeyFile: D:\auth_key\id_key_rsa.pub
priKeyFile: D:\auth_key\id_key_rsa提供解析公鑰和私鑰的配置類(lèi)
@Data
@ConfigurationProperties(prefix = "heima.key")
public class RsaKeyProperties {
private String pubKeyPath;
private String priKeyPath;
private PublicKey publicKey;
private PrivateKey privateKey;
@PostConstruct
public void loadKey() throws Exception {
publicKey = RsaUtils.getPublicKey(pubKeyPath);
privateKey = RsaUtils.getPrivateKey(priKeyPath);
}
}創(chuàng)建認(rèn)證服務(wù)啟動(dòng)類(lèi)
@SpringBootApplication
@MapperScan("com.itheima.mapper")
@EnableConfigurationProperties(RsaKeyProperties.class)
public class AuthApplication {
public static void main(String[] args) {
SpringApplication.run(AuthApplication.class, args);
}
}將上面集中式案例中數(shù)據(jù)庫(kù)認(rèn)證相關(guān)代碼復(fù)制到認(rèn)證服務(wù)中
需要復(fù)制的代碼如果所示:

注意這里要去掉mapper中繼承的通用mapper接口,處理器類(lèi)上換成@RestController,這里前后端絕對(duì)分離,不能再跳轉(zhuǎn)頁(yè)面了,要返回?cái)?shù)據(jù)。
public class JwtLoginFilter extends UsernamePasswordAuthenticationFilter {
private AuthenticationManager authenticationManager;
private RsaKeyProperties prop;
public JwtLoginFilter(AuthenticationManager authenticationManager, RsaKeyProperties prop) {
this.authenticationManager = authenticationManager;
this.prop = prop;
}
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
try {
SysUser sysUser = new ObjectMapper().readValue(request.getInputStream(), SysUser.class);
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(sysUser.getUsername(), sysUser.getPassword());
return authenticationManager.authenticate(authRequest);
}catch (Exception e){
try {
response.setContentType("application/json;charset=utf-8");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
PrintWriter out = response.getWriter();
Map resultMap = new HashMap();
resultMap.put("code", HttpServletResponse.SC_UNAUTHORIZED);
resultMap.put("msg", "用戶(hù)名或密碼錯(cuò)誤!");
out.write(new ObjectMapper().writeValueAsString(resultMap));
out.flush();
out.close();
}catch (Exception outEx){
outEx.printStackTrace();
}
throw new RuntimeException(e);
}
}
public void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
SysUser user = new SysUser();
user.setUsername(authResult.getName());
user.setRoles((List<SysRole>) authResult.getAuthorities());
String token = JwtUtils.generateTokenExpireInMinutes(user, prop.getPrivateKey(), 24 * 60);
response.addHeader("Authorization", "Bearer "+token);
try {
response.setContentType("application/json;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
Map resultMap = new HashMap();
resultMap.put("code", HttpServletResponse.SC_OK);
resultMap.put("msg", "認(rèn)證通過(guò)!");
out.write(new ObjectMapper().writeValueAsString(resultMap));
out.flush();
out.close();
}catch (Exception outEx){
outEx.printStackTrace();
}
}
}編寫(xiě)檢驗(yàn)token過(guò)濾器
public class JwtVerifyFilter extends BasicAuthenticationFilter {
private RsaKeyProperties prop;
public JwtVerifyFilter(AuthenticationManager authenticationManager, RsaKeyProperties prop) {
super(authenticationManager);
this.prop = prop;
}
public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith("Bearer ")) {
//如果攜帶錯(cuò)誤的token,則給用戶(hù)提示請(qǐng)登錄!
chain.doFilter(request, response);
response.setContentType("application/json;charset=utf-8");
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
PrintWriter out = response.getWriter();
Map resultMap = new HashMap();
resultMap.put("code", HttpServletResponse.SC_FORBIDDEN);
resultMap.put("msg", "請(qǐng)登錄!");
out.write(new ObjectMapper().writeValueAsString(resultMap));
out.flush();
out.close();
} else {
//如果攜帶了正確格式的token要先得到token
String token = header.replace("Bearer ", "");
//驗(yàn)證tken是否正確
Payload<SysUser> payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), SysUser.class);
SysUser user = payload.getUserInfo();
if(user!=null){
UsernamePasswordAuthenticationToken authResult = new UsernamePasswordAuthenticationToken(user.getUsername(), null, user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authResult);
chain.doFilter(request, response);
}
}
}
}編寫(xiě)SpringSecurity配置類(lèi)
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
@Autowired
private RsaKeyProperties prop;
@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
//指定認(rèn)證對(duì)象的來(lái)源
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
}
//SpringSecurity配置信息
public void configure(HttpSecurity http) throws Exception {
http.csrf()
.disable()
.authorizeRequests()
.antMatchers("/product").hasAnyRole("USER")
.anyRequest()
.authenticated()
.and()
.addFilter(new JwtLoginFilter(super.authenticationManager(), prop))
.addFilter(new JwtVerifyFilter(super.authenticationManager(), prop))
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}啟動(dòng)測(cè)試認(rèn)證服務(wù)
認(rèn)證請(qǐng)求

認(rèn)證通過(guò)結(jié)果

token在Headers中:

驗(yàn)證認(rèn)證請(qǐng)求

資源服務(wù)
說(shuō)明
資源服務(wù)可以有很多個(gè),這里只拿產(chǎn)品服務(wù)為例,記住,資源服務(wù)中只能通過(guò)公鑰驗(yàn)證認(rèn)證。不能簽發(fā)token!
創(chuàng)建產(chǎn)品服務(wù)并導(dǎo)入jar包
根據(jù)實(shí)際業(yè)務(wù)導(dǎo)包即可,咱們就暫時(shí)和認(rèn)證服務(wù)一樣了。
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springboot_security_jwt_rsa_parent</artifactId>
<groupId>com.itheima</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>heima_source_product</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>com.itheima</groupId>
<artifactId>heima_common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
</dependencies>
</project>編寫(xiě)產(chǎn)品服務(wù)配置文件
切記這里只能有公鑰地址!
server:
port: 9002
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql:///security_authority
username: root
password: root
mybatis:
type-aliases-package: com.itheima.domain
configuration:
map-underscore-to-camel-case: true
logging:
level:
com.itheima: debug
rsa:
key:
pubKeyFile: D:\auth_key\id_key_rsa.pub編寫(xiě)讀取公鑰的配置類(lèi)
@ConfigurationProperties("rsa.key")
public class RsaKeyProperties {
private String pubKeyFile;
private PublicKey publicKey;
@PostConstruct
public void createRsaKey() throws Exception {
publicKey = RsaUtils.getPublicKey(pubKeyFile);
}
public String getPubKeyFile() {
return pubKeyFile;
}
public void setPubKeyFile(String pubKeyFile) {
this.pubKeyFile = pubKeyFile;
}
public PublicKey getPublicKey() {
return publicKey;
}
public void setPublicKey(PublicKey publicKey) {
this.publicKey = publicKey;
}
}編寫(xiě)啟動(dòng)類(lèi)
@SpringBootApplication
@MapperScan("com.itheima.mapper")
@EnableConfigurationProperties(RsaKeyProperties.class)
public class AuthSourceApplication {
public static void main(String[] args) {
SpringApplication.run(AuthSourceApplication.class, args);
}
}復(fù)制認(rèn)證服務(wù)中,用戶(hù)對(duì)象,角色對(duì)象和校驗(yàn)認(rèn)證的接口
這時(shí)目錄結(jié)構(gòu)如圖:

復(fù)制認(rèn)證服務(wù)中SpringSecurity配置類(lèi)做修改,去掉“增加自定義認(rèn)證過(guò)濾器”即可!
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private RsaKeyProperties prop;
//SpringSecurity配置信息
public void configure(HttpSecurity http) throws Exception {
http.csrf()
.disable()
.authorizeRequests()
.antMatchers("/product").hasAnyRole("USER")
.anyRequest()
.authenticated()
.and()
.addFilter(new JwtVerifyFilter(super.authenticationManager(), prop))
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}編寫(xiě)產(chǎn)品處理器
@RestController
@RequestMapping("/product")
public class ProductController {
@GetMapping
public String findAll(){
return "產(chǎn)品測(cè)試成功!";
}
}啟動(dòng)產(chǎn)品服務(wù)做測(cè)試
攜帶token

在產(chǎn)品處理器上添加訪(fǎng)問(wèn)需要ADMIN角色
@RestController
@RequestMapping("/product")
public class ProductController {
@Secured("ROLE_ADMIN")
@GetMapping
public String findAll(){
return "產(chǎn)品測(cè)試成功!";
}
}重啟測(cè)試權(quán)限不足

在數(shù)據(jù)庫(kù)中手動(dòng)給用戶(hù)添加ADMIN角色

重新認(rèn)證獲取新token再測(cè)試OK了!

到此這篇關(guān)于SpringSecurity在分布式環(huán)境下的使用的文章就介紹到這了,更多相關(guān)SpringSecurity分布式內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringSecurity實(shí)現(xiàn)動(dòng)態(tài)權(quán)限校驗(yàn)的過(guò)程
- SpringSecurity在單機(jī)環(huán)境下使用方法詳解
- SpringBoot3.x接入Security6.x實(shí)現(xiàn)JWT認(rèn)證的完整步驟
- SpringSecurity安全框架的使用
- Spring?Clou整合?Security?+?Oauth2?+?jwt實(shí)現(xiàn)權(quán)限認(rèn)證的詳細(xì)過(guò)程
- Spring Security的持久化用戶(hù)和授權(quán)實(shí)現(xiàn)方式
相關(guān)文章
IntelliJ IDEA基于SpringBoot如何搭建SSM開(kāi)發(fā)環(huán)境的步驟詳解
這篇文章主要介紹了IntelliJ IDEA基于SpringBoot如何搭建SSM開(kāi)發(fā)環(huán)境,本文分步驟通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10
如何實(shí)現(xiàn)java遞歸 處理權(quán)限管理菜單樹(shù)或分類(lèi)
這篇文章主要介紹了如何實(shí)現(xiàn)java遞歸 處理權(quán)限管理菜單樹(shù)或分類(lèi),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-01-01
Java兩種方法計(jì)算出階乘尾部連續(xù)0的個(gè)數(shù)
這篇文章主要介紹了Java兩種方法計(jì)算出階乘尾部連續(xù)0的個(gè)數(shù),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
動(dòng)態(tài)上傳jar包熱部署的實(shí)戰(zhàn)詳解
開(kāi)發(fā)系統(tǒng)過(guò)程中遇到的一個(gè)需求,系統(tǒng)給定一個(gè)接口,用戶(hù)可以自定義開(kāi)發(fā)該接口的實(shí)現(xiàn),并將實(shí)現(xiàn)打成jar包,上傳到系統(tǒng)中。系統(tǒng)完成熱部署,并切換該接口的實(shí)現(xiàn)。本文詳細(xì)介紹了實(shí)現(xiàn)方法,需要的可以參考一下2022-10-10
MyBatis執(zhí)行動(dòng)態(tài)SQL的方法
今天小編就為大家分享一篇關(guān)于MyBatis執(zhí)行動(dòng)態(tài)SQL的方法,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2018-12-12
Java中通過(guò)Class類(lèi)獲取Class對(duì)象的方法詳解
這篇文章主要給大家介紹了關(guān)于Java中通過(guò)Class類(lèi)獲取Class對(duì)象的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用java具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面跟著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2017-08-08

