javascript
SpringSecurity分布式整合之实现思路分析
JWT相關工具類
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>載荷對象
/** * 為了方便后期獲取token中的用戶信息,將token中載荷部分單獨封裝成一個對象 */ @Data public class Payload<T> {}JWT工具類
/*** 生成token以及校驗token相關方法*/ public class JwtUtils {private static final String JWT_PAYLOAD_USER_KEY = "user";/*** 私鑰加密token** @param userInfo 載荷中的數據* @param privateKey 私鑰* @param expire 過期時間,單位分鐘* @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 載荷中的數據* @param privateKey 私鑰* @param expire 過期時間,單位秒* @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 用戶請求中的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 用戶請求中的令牌* @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 用戶請求中的令牌* @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工具類
非對稱加密工具列
public class RsaUtils {private static final int DEFAULT_KEY_SIZE = 2048;/*** 從文件中讀取公鑰** @param filename 公鑰保存路徑,相對于classpath* @return 公鑰對象* @throws Exception*/public static PublicKey getPublicKey(String filename) throws Exception {byte[] bytes = readFile(filename);return getPublicKey(bytes);}/*** 從文件中讀取密鑰** @param filename 私鑰保存路徑,相對于classpath* @return 私鑰對象* @throws Exception*/public static PrivateKey getPrivateKey(String filename) throws Exception {byte[] bytes = readFile(filename);return getPrivateKey(bytes);}/*** 獲取公鑰** @param bytes 公鑰的字節形式* @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 私鑰的字節形式* @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);}/*** 根據密文,生存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分布式認證思路分析
SpringSecurity主要是通過過濾器來實現功能的!我們要找到SpringSecurity實現認證和校驗身份的過濾器! 回顧集中式認證流程
用戶認證
使用UsernamePasswordAuthenticationFilter過濾器中attemptAuthentication方法實現認證功能,該過濾 器父類中successfulAuthentication方法實現認證成功后的操作。
身份校驗
使用BasicAuthenticationFilter過濾器中doFilterInternal方法驗證是否登錄,以決定能否進入后續過濾器。 分析分布式認證流程
用戶認證
由于,分布式項目,多數是前后端分離的架構設計,我們要滿足可以接受異步post的認證請求參數,需要修 改UsernamePasswordAuthenticationFilter過濾器中attemptAuthentication方法,讓其能夠接收請求體。
另外,默認successfulAuthentication方法在認證通過后,是把用戶信息直接放入session就完事了,現在我 們需要修改這個方法,在認證通過后生成token并返回給用戶。
身份校驗
原來BasicAuthenticationFilter過濾器中doFilterInternal方法校驗用戶是否登錄,就是看session中是否有用 戶信息,我們要修改為,驗證用戶攜帶的token是否合法,并解析出用戶信息,交給SpringSecurity,以便于 后續的授權功能可以正常使用。
總結
以上是生活随笔為你收集整理的SpringSecurity分布式整合之实现思路分析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpringSecurity集中式整合之
- 下一篇: SpringSecurity分布式整合之