javascript
SpringSecurity分布式整合之实现思路分析
JWT相關(guān)工具類
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中的用戶信息,將token中載荷部分單獨(dú)封裝成一個(gè)對(duì)象 */ @Data public class Payload<T> {}JWT工具類
/*** 生成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 過期時(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 過期時(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 用戶請(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中的用戶信息** @param token 用戶請(qǐng)求中的令牌* @param publicKey 公鑰* @return 用戶信息*/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 用戶請(qǐng)求中的令牌* @param publicKey 公鑰* @return 用戶信息*/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工具類
非對(duì)稱加密工具列
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公鑰和私鑰,并寫入指定文件** @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();// 獲取公鑰并寫出byte[] publicKeyBytes = keyPair.getPublic().getEncoded();publicKeyBytes = Base64.getEncoder().encode(publicKeyBytes);writeFile(publicKeyFilename, publicKeyBytes);// 獲取私鑰并寫出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主要是通過過濾器來實(shí)現(xiàn)功能的!我們要找到SpringSecurity實(shí)現(xiàn)認(rèn)證和校驗(yàn)身份的過濾器! 回顧集中式認(rèn)證流程
用戶認(rèn)證
使用UsernamePasswordAuthenticationFilter過濾器中attemptAuthentication方法實(shí)現(xiàn)認(rèn)證功能,該過濾 器父類中successfulAuthentication方法實(shí)現(xiàn)認(rèn)證成功后的操作。
身份校驗(yàn)
使用BasicAuthenticationFilter過濾器中doFilterInternal方法驗(yàn)證是否登錄,以決定能否進(jìn)入后續(xù)過濾器。 分析分布式認(rèn)證流程
用戶認(rèn)證
由于,分布式項(xiàng)目,多數(shù)是前后端分離的架構(gòu)設(shè)計(jì),我們要滿足可以接受異步post的認(rèn)證請(qǐng)求參數(shù),需要修 改UsernamePasswordAuthenticationFilter過濾器中attemptAuthentication方法,讓其能夠接收請(qǐng)求體。
另外,默認(rèn)successfulAuthentication方法在認(rèn)證通過后,是把用戶信息直接放入session就完事了,現(xiàn)在我 們需要修改這個(gè)方法,在認(rèn)證通過后生成token并返回給用戶。
身份校驗(yàn)
原來BasicAuthenticationFilter過濾器中doFilterInternal方法校驗(yàn)用戶是否登錄,就是看session中是否有用 戶信息,我們要修改為,驗(yàn)證用戶攜帶的token是否合法,并解析出用戶信息,交給SpringSecurity,以便于 后續(xù)的授權(quán)功能可以正常使用。
總結(jié)
以上是生活随笔為你收集整理的SpringSecurity分布式整合之实现思路分析的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpringSecurity集中式整合之
- 下一篇: gradle idea java ssm