當(dāng)前位置:
首頁(yè) >
前端技术
> javascript
>内容正文
javascript
SpringSecurity分布式整合之common工具模块创建
生活随笔
收集整理的這篇文章主要介紹了
SpringSecurity分布式整合之common工具模块创建
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
通用模塊
創(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.leon</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>leon_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>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";@Testpublic void generateKey() throws Exception {RsaUtils.generateKey(publicFile, privateFile, "leon", 2048);} }執(zhí)行后查看D:\auth_key目錄發(fā)現(xiàn)私鑰和公鑰文件生成成功
總結(jié)
以上是生活随笔為你收集整理的SpringSecurity分布式整合之common工具模块创建的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: SpringSecurity分布式整合之
- 下一篇: SpringSecurity分布式整合之