欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringSecurity在分布式環(huán)境下的使用流程分析

 更新時間:2025年02月17日 10:59:21   作者:java小羅_江西南昌  
文章介紹了Spring?Security在分布式環(huán)境下的使用,包括單點登錄(SSO)的概念、流程圖以及JWT(JSON?Web?Token)的生成和校驗,通過使用JWT和RSA非對稱加密,可以實現(xiàn)安全的分布式認證,感興趣的朋友一起看看吧

參考

來源于黑馬程序員: 手把手教你精通新版SpringSecurity

分布式認證概念說明

分布式認證,即我們常說的單點登錄,簡稱SSO,指的是在多應(yīng)用系統(tǒng)的項目中,用戶只需要登錄一次,就可以訪 問所有互相信任的應(yīng)用系統(tǒng)。

分布式認證流程圖

首先,我們要明確,在分布式項目中,每臺服務(wù)器都有各自獨立的session,而這些session之間是無法直接共享資 源的,所以,session通常不能被作為單點登錄的技術(shù)方案。最合理的單點登錄方案流程如下圖所示:

總結(jié)一下,單點登錄的實現(xiàn)分兩大環(huán)節(jié):

  • **用戶認證:**這一環(huán)節(jié)主要是用戶向認證服務(wù)器發(fā)起認證請求,認證服務(wù)器給用戶返回一個成功的令牌token, 主要在認證服務(wù)器中完成,即圖中的A系統(tǒng),注意A系統(tǒng)只能有一個。
  • **身份校驗:**這一環(huán)節(jié)是用戶攜帶token去訪問其他服務(wù)器時,在其他服務(wù)器中要對token的真?zhèn)芜M行檢驗,主 要在資源服務(wù)器中完成,即圖中的B系統(tǒng),這里B系統(tǒng)可以有很多個。

JWT介紹

概念說明

從分布式認證流程中,我們不難發(fā)現(xiàn),這中間起最關(guān)鍵作用的就是token,token的安全與否,直接關(guān)系到系統(tǒng)的 健壯性,這里我們選擇使用JWT來實現(xiàn)token的生成和校驗。 JWT,全稱JSON Web Token,官網(wǎng)地址https://jwt.io,是一款出色的分布式身份校驗方案??梢陨蓆oken,也可以解析檢驗token。

JWT生成的token由三部分組成

  • 頭部:主要設(shè)置一些規(guī)范信息,簽名部分的編碼格式就在頭部中聲明。
  • 載荷:token中存放有效信息的部分,比如用戶名,用戶角色,過期時間等,但是不要放密碼,會泄露!
  • 簽名:將頭部與載荷分別采用base64編碼后,用“.”相連,再加入,最后使用頭部聲明的編碼類型進行編 碼,就得到了簽名。【通過隨機鹽在進行加密】

JWT生成token的安全性分析

從JWT生成的token組成上來看,要想避免token被偽造,主要就得看簽名部分了,而簽名部分又有三部分組成,其中頭部和載荷的base64編碼,幾乎是透明的,毫無安全性可言,那么最終守護token安全的重擔(dān)就落在了加入的鹽上面了!

試想:如果生成token所用的鹽與解析token時加入的鹽是一樣的。豈不是類似于中國人民銀行把人民幣防偽技術(shù) 公開了?大家可以用這個鹽來解析token,就能用來偽造token。這時,我們就需要對鹽采用非對稱加密的方式進行加密,以達到生成token與校驗token方所用的鹽不一致的安全效果!

非對稱加密RSA介紹

  • **基本原理:**同時生成兩把密鑰:私鑰和公鑰,私鑰隱秘保存,公鑰可以下發(fā)給信任客戶端
  • 私鑰加密,持有私鑰或公鑰才可以解密
  • 公鑰加密,持有私鑰才可解密
  • 優(yōu)點:安全,難以破解
  • 缺點:算法比較耗時,為了安全,可以接受
  • 歷史:三位數(shù)學(xué)家Rivest、Shamir 和 Adleman 設(shè)計了一種算法,可以實現(xiàn)非對稱加密。這種算法用他們?nèi)?個人的名字縮寫:RSA。

【總結(jié)】:也就是說,我們加密信息的時候,使用的是公鑰,而驗證token真?zhèn)蔚臅r候,使用的是公鑰

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>

載荷對象

/**
* 為了方便后期獲取token中的用戶信息,將token中載荷部分單獨封裝成一個對象
*/
@Data
public class Payload<T> {
}

JWT工具類

/**
 * 生成token以及校驗token相關(guān)方法
 */
public class JwtUtils {
    private static final String JWT_PAYLOAD_USER_KEY = "user";
    /**
     * 私鑰加密token
     *
     * @param userInfo   載荷中的數(shù)據(jù)
     * @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   載荷中的數(shù)據(jù)
     * @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 公鑰的字節(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分布式認證思路分析

SpringSecurity主要是通過過濾器來實現(xiàn)功能的!我們要找到SpringSecurity實現(xiàn)認證和校驗身份的過濾器! 回顧集中式認證流程

用戶認證

使用UsernamePasswordAuthenticationFilter過濾器中attemptAuthentication方法實現(xiàn)認證功能,該過濾 器父類中successfulAuthentication方法實現(xiàn)認證成功后的操作。

身份校驗

使用BasicAuthenticationFilter過濾器中doFilterInternal方法驗證是否登錄,以決定能否進入后續(xù)過濾器。 分析分布式認證流程

用戶認證

由于,分布式項目,多數(shù)是前后端分離的架構(gòu)設(shè)計,我們要滿足可以接受異步post的認證請求參數(shù),需要修 改UsernamePasswordAuthenticationFilter過濾器中attemptAuthentication方法,讓其能夠接收請求體。

另外,默認successfulAuthentication方法在認證通過后,是把用戶信息直接放入session就完事了,現(xiàn)在我 們需要修改這個方法,在認證通過后生成token并返回給用戶。

身份校驗

原來BasicAuthenticationFilter過濾器中doFilterInternal方法校驗用戶是否登錄,就是看session中是否有用 戶信息,我們要修改為,驗證用戶攜帶的token是否合法,并解析出用戶信息,交給SpringSecurity,以便于 后續(xù)的授權(quán)功能可以正常使用。

SpringSecurity+JWT+RSA分布式認證實現(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)入工具類

工具類如下

image-20200920210659250

Payload.java

/**
 * 為了方便后期獲取token中的用戶信息,將token中載荷部分單獨封裝成一個對象
 */
@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序列化出錯:" + 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解析出錯:" + 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解析出錯:" + 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解析出錯:" + 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解析出錯:" + 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     過期時間,單位分鐘
     * @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     過期時間,單位秒
     * @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;
    }
}

RsaUtils.java

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 公鑰的字節(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);
    }
}

在通用子模塊中編寫測試類生成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)私鑰和公鑰文件生成成功

image-20200920211051749

認證服務(wù)

創(chuàng)建認證服務(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)建認證服務(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

提供解析公鑰和私鑰的配置類

@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)建認證服務(wù)啟動類

@SpringBootApplication
@MapperScan("com.itheima.mapper")
@EnableConfigurationProperties(RsaKeyProperties.class)
public class AuthApplication {
    public static void main(String[] args) {
    	SpringApplication.run(AuthApplication.class, args);
    }
}

將上面集中式案例中數(shù)據(jù)庫認證相關(guān)代碼復(fù)制到認證服務(wù)中

需要復(fù)制的代碼如果所示:

image-20200920211547261

注意這里要去掉mapper中繼承的通用mapper接口,處理器類上換成@RestController,這里前后端絕對分離,不能再跳轉(zhuǎn)頁面了,要返回數(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", "用戶名或密碼錯誤!");
                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", "認證通過!");
            out.write(new ObjectMapper().writeValueAsString(resultMap));
            out.flush();
            out.close();
        }catch (Exception outEx){
            outEx.printStackTrace();
        }
    }
}

編寫檢驗token過濾器

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 ")) {
            //如果攜帶錯誤的token,則給用戶提示請登錄!
            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", "請登錄!");
            out.write(new ObjectMapper().writeValueAsString(resultMap));
            out.flush();
            out.close();
        } else {
            //如果攜帶了正確格式的token要先得到token
            String token = header.replace("Bearer ", "");
            //驗證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);
            }
        }
    }
}

編寫SpringSecurity配置類

@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();
    }
    //指定認證對象的來源
    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);
    }
}

啟動測試認證服務(wù)

認證請求

image-20200920213350978

認證通過結(jié)果

image-20200920213403708

token在Headers中:

image-20200920213423316

驗證認證請求

image-20200920213442797

資源服務(wù)

說明

資源服務(wù)可以有很多個,這里只拿產(chǎn)品服務(wù)為例,記住,資源服務(wù)中只能通過公鑰驗證認證。不能簽發(fā)token!

創(chuàng)建產(chǎn)品服務(wù)并導(dǎo)入jar包

根據(jù)實際業(yè)務(wù)導(dǎo)包即可,咱們就暫時和認證服務(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>

編寫產(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

編寫讀取公鑰的配置類

@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;
    }
}

編寫啟動類

@SpringBootApplication
@MapperScan("com.itheima.mapper")
@EnableConfigurationProperties(RsaKeyProperties.class)
public class AuthSourceApplication {
    public static void main(String[] args) {
        SpringApplication.run(AuthSourceApplication.class, args);
    }
}

復(fù)制認證服務(wù)中,用戶對象,角色對象和校驗認證的接口

這時目錄結(jié)構(gòu)如圖:

image-20200920214004611

復(fù)制認證服務(wù)中SpringSecurity配置類做修改,去掉“增加自定義認證過濾器”即可!

@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);
    }
}

編寫產(chǎn)品處理器

@RestController
@RequestMapping("/product")
public class ProductController {
    @GetMapping
    public String findAll(){
    	return "產(chǎn)品測試成功!";
    }
}

啟動產(chǎn)品服務(wù)做測試

攜帶token

image-20200920214127083

在產(chǎn)品處理器上添加訪問需要ADMIN角色

@RestController
@RequestMapping("/product")
public class ProductController {
    @Secured("ROLE_ADMIN")
    @GetMapping
    public String findAll(){
    	return "產(chǎn)品測試成功!";
    }
}

重啟測試權(quán)限不足

image-20200920214208492

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

image-20200920214220620

重新認證獲取新token再測試OK了!

image-20200920214234884

到此這篇關(guān)于SpringSecurity在分布式環(huán)境下的使用的文章就介紹到這了,更多相關(guān)SpringSecurity分布式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • IntelliJ IDEA基于SpringBoot如何搭建SSM開發(fā)環(huán)境的步驟詳解

    IntelliJ IDEA基于SpringBoot如何搭建SSM開發(fā)環(huán)境的步驟詳解

    這篇文章主要介紹了IntelliJ IDEA基于SpringBoot如何搭建SSM開發(fā)環(huán)境,本文分步驟通過圖文并茂的形式給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-10-10
  • Java9以后的垃圾回收的具體用法

    Java9以后的垃圾回收的具體用法

    這篇文章主要介紹了Java9以后的垃圾回收的具體用法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-10-10
  • 樹莓派.GPRS.短信接收器

    樹莓派.GPRS.短信接收器

    這篇文章主要介紹了樹莓派.GPRS.短信接收器的相關(guān)知識,需要的朋友可以參考下
    2017-10-10
  • 如何實現(xiàn)java遞歸 處理權(quán)限管理菜單樹或分類

    如何實現(xiàn)java遞歸 處理權(quán)限管理菜單樹或分類

    這篇文章主要介紹了如何實現(xiàn)java遞歸 處理權(quán)限管理菜單樹或分類,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-01-01
  • Java兩種方法計算出階乘尾部連續(xù)0的個數(shù)

    Java兩種方法計算出階乘尾部連續(xù)0的個數(shù)

    這篇文章主要介紹了Java兩種方法計算出階乘尾部連續(xù)0的個數(shù),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-03-03
  • java不通過配置文件初始化logger示例

    java不通過配置文件初始化logger示例

    這篇文章主要介紹了java不通過配置文件初始化logger示例,需要的朋友可以參考下
    2014-05-05
  • 動態(tài)上傳jar包熱部署的實戰(zhàn)詳解

    動態(tài)上傳jar包熱部署的實戰(zhàn)詳解

    開發(fā)系統(tǒng)過程中遇到的一個需求,系統(tǒng)給定一個接口,用戶可以自定義開發(fā)該接口的實現(xiàn),并將實現(xiàn)打成jar包,上傳到系統(tǒng)中。系統(tǒng)完成熱部署,并切換該接口的實現(xiàn)。本文詳細介紹了實現(xiàn)方法,需要的可以參考一下
    2022-10-10
  • Android接入微信支付的方法

    Android接入微信支付的方法

    這篇文章主要介紹了Android接入微信支付的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-05-05
  • MyBatis執(zhí)行動態(tài)SQL的方法

    MyBatis執(zhí)行動態(tài)SQL的方法

    今天小編就為大家分享一篇關(guān)于MyBatis執(zhí)行動態(tài)SQL的方法,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2018-12-12
  • Java中通過Class類獲取Class對象的方法詳解

    Java中通過Class類獲取Class對象的方法詳解

    這篇文章主要給大家介紹了關(guān)于Java中通過Class類獲取Class對象的方法,文中通過示例代碼介紹的非常詳細,對大家學(xué)習(xí)或者使用java具有一定的參考學(xué)習(xí)價值,需要的朋友們下面跟著小編來一起學(xué)習(xí)學(xué)習(xí)吧。
    2017-08-08

最新評論