SpringBoot+SpringSecurity+JWT整合實(shí)現(xiàn)單點(diǎn)登錄SSO史上最全詳解
作者:波波烤鴨
blog.csdn.net/qq_38526573/article/details/103409430
一、什么是單點(diǎn)登陸
單點(diǎn)登錄(Single Sign On),簡(jiǎn)稱(chēng)為 SSO,是目前比較流行的企業(yè)業(yè)務(wù)整合的解決方案之一。SSO的定義是在多個(gè)應(yīng)用系統(tǒng)中,用戶(hù)只需要登錄一次就可以訪問(wèn)所有相互信任的應(yīng)用系統(tǒng)
二、簡(jiǎn)單的運(yùn)行機(jī)制
單點(diǎn)登錄的機(jī)制其實(shí)是比較簡(jiǎn)單的,用一個(gè)現(xiàn)實(shí)中的例子做比較。某公園內(nèi)部有許多獨(dú)立的景點(diǎn),游客可以在各個(gè)景點(diǎn)門(mén)口單獨(dú)買(mǎi)票。對(duì)于需要游玩所有的景點(diǎn)的游客,這種買(mǎi)票方式很不方便,需要在每個(gè)景點(diǎn)門(mén)口排隊(duì)買(mǎi)票,錢(qián)包拿 進(jìn)拿出的,容易丟失,很不安全。于是絕大多數(shù)游客選擇在大門(mén)口買(mǎi)一張通票(也叫套票),就可以玩遍所有的景點(diǎn)而不需要重新再買(mǎi)票。他們只需要在每個(gè)景點(diǎn)門(mén) 口出示一下剛才買(mǎi)的套票就能夠被允許進(jìn)入每個(gè)獨(dú)立的景點(diǎn)。單點(diǎn)登錄的機(jī)制也一樣,如下圖所示,
用戶(hù)認(rèn)證:這一環(huán)節(jié)主要是用戶(hù)向認(rèn)證服務(wù)器發(fā)起認(rèn)證請(qǐng)求,認(rèn)證服務(wù)器給用戶(hù)返回一個(gè)成功的令牌token,主要在認(rèn)證服務(wù)器中完成,即圖中的認(rèn)證系統(tǒng),注意認(rèn)證系統(tǒng)只能有一個(gè)。身份校驗(yàn):這一環(huán)節(jié)是用戶(hù)攜帶token去訪問(wèn)其他服務(wù)器時(shí),在其他服務(wù)器中要對(duì)token的真?zhèn)芜M(jìn)行檢驗(yàn),主要在資源服務(wù)器中完成,即圖中的應(yīng)用系統(tǒng)2 3
三、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)方案。可以生成token,也可以解析檢驗(yàn)token。
JWT生成的token由三部分組成:
頭部:主要設(shè)置一些規(guī)范信息,簽名部分的編碼格式就在頭部中聲明。載荷:token中存放有效信息的部分,比如用戶(hù)名,用戶(hù)角色,過(guò)期時(shí)間等,但是不要放密碼,會(huì)泄露!簽名:將頭部與載荷分別采用base64編碼后,用“.”相連,再加入鹽,最后使用頭部聲明的編碼類(lèi)型進(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。
四、SpringSecurity整合JWT
1.認(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)功能可以正常使用。
2.具體實(shí)現(xiàn)
為了演示單點(diǎn)登錄的效果,我們?cè)O(shè)計(jì)如下項(xiàng)目結(jié)構(gòu)
2.1父工程創(chuàng)建
因?yàn)楸景咐枰獎(jiǎng)?chuàng)建多個(gè)系統(tǒng),所以我們使用maven聚合工程來(lái)實(shí)現(xiàn),首先創(chuàng)建一個(gè)父工程,導(dǎo)入springboot的父依賴(lài)即可
????org.springframework.boot
????spring-boot-starter-parent
????2.1.3.RELEASE
????
123456
2.2公共工程創(chuàng)建
然后創(chuàng)建一個(gè)common工程,其他工程依賴(lài)此系統(tǒng)
導(dǎo)入JWT相關(guān)的依賴(lài)
<dependencies>
????<dependency>
????????<groupId>io.jsonwebtokengroupId>
????????<artifactId>jjwt-apiartifactId>
????????<version>0.10.7version>
????dependency>
????<dependency>
????????<groupId>io.jsonwebtokengroupId>
????????<artifactId>jjwt-implartifactId>
????????<version>0.10.7version>
????????<scope>runtimescope>
????dependency>
????<dependency>
????????<groupId>io.jsonwebtokengroupId>
????????<artifactId>jjwt-jacksonartifactId>
????????<version>0.10.7version>
????????<scope>runtimescope>
????dependency>
????
????<dependency>
????????<groupId>com.fasterxml.jackson.coregroupId>
????????<artifactId>jackson-databindartifactId>
????????<version>2.9.9version>
????dependency>
????
????<dependency>
????????<groupId>org.springframework.bootgroupId>
????????<artifactId>spring-boot-starter-loggingartifactId>
????dependency>
????<dependency>
????????<groupId>joda-timegroupId>
????????<artifactId>joda-timeartifactId>
????dependency>
????<dependency>
????????<groupId>org.projectlombokgroupId>
????????<artifactId>lombokartifactId>
????dependency>
????<dependency>
????????<groupId>org.springframework.bootgroupId>
????????<artifactId>spring-boot-starter-testartifactId>
????dependency>
dependencies>
123456789101112131415161718192021222324252627282930313233343536373839404142
創(chuàng)建相關(guān)的工具類(lèi)
Payload
/**
?*?@program:?springboot-54-security-jwt-demo
?*?@description:
?*?@author:?波波烤鴨
?*?@create:?2019-12-03?10:28
?*/
@Data
public?class?Payload?<T>{
????private?String?id;
????private?T?userInfo;
????private?Date?expiration;
}
123456789101112
JsonUtils
package?com.dpb.utils;
import?com.fasterxml.jackson.core.JsonProcessingException;
import?com.fasterxml.jackson.core.type.TypeReference;
import?com.fasterxml.jackson.databind.ObjectMapper;
import?org.slf4j.Logger;
import?org.slf4j.LoggerFactory;
import?java.io.IOException;
import?java.util.List;
import?java.util.Map;
/**
?*?@author:?波波烤鴨
?**/
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?toBean(String?json,?Class?tClass) ?{
????????try?{
????????????return?mapper.readValue(json,?tClass);
????????}?catch?(IOException?e)?{
????????????logger.error("json解析出錯(cuò):"?+?json,?e);
????????????return?null;
????????}
????}
????public?static??List?toList(String?json,?Class?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??Map?toMap(String?json,?Class?kClass,?Class?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?nativeRead(String?json,?TypeReference?type) ?{
????????try?{
????????????return?mapper.readValue(json,?type);
????????}?catch?(IOException?e)?{
????????????logger.error("json解析出錯(cuò):"?+?json,?e);
????????????return?null;
????????}
????}
}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
JwtUtils
package?com.dpb.utils;
import?com.dpb.domain.Payload;
import?io.jsonwebtoken.Claims;
import?io.jsonwebtoken.Jws;
import?io.jsonwebtoken.Jwts;
import?io.jsonwebtoken.SignatureAlgorithm;
import?org.joda.time.DateTime;
import?java.security.PrivateKey;
import?java.security.PublicKey;
import?java.util.Base64;
import?java.util.UUID;
/**
?*?@author:?波波烤鴨
?*?生成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
?????*/
????private?static?Jws?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??Payload?getInfoFromToken(String?token,?PublicKey?publicKey,?Class?userType) ? {
????????Jws?claimsJws?=?parserToken(token,?publicKey);
????????Claims?body?=?claimsJws.getBody();
????????Payload?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??Payload?getInfoFromToken(String?token,?PublicKey?publicKey)? {
????????Jws?claimsJws?=?parserToken(token,?publicKey);
????????Claims?body?=?claimsJws.getBody();
????????Payload?claims?=?new?Payload<>();
????????claims.setId(body.getId());
????????claims.setExpiration(body.getExpiration());
????????return?claims;
????}
}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
RsaUtils
package?com.dpb.utils;
import?java.io.File;
import?java.io.IOException;
import?java.nio.file.Files;
import?java.security.*;
import?java.security.spec.InvalidKeySpecException;
import?java.security.spec.PKCS8EncodedKeySpec;
import?java.security.spec.X509EncodedKeySpec;
import?java.util.Base64;
/**
?*?@author?波波烤鴨
?*/
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);
????}
}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
在通用子模塊中編寫(xiě)測(cè)試類(lèi)生成rsa公鑰和私鑰
/**
?*?@program:?springboot-54-security-jwt-demo
?*?@description:
?*?@author:?波波烤鴨
?*?@create:?2019-12-03?11:08
?*/
public?class?JwtTest?{
????private?String?privateKey?=?"c:/tools/auth_key/id_key_rsa";
????private?String?publicKey?=?"c:/tools/auth_key/id_key_rsa.pub";
????@Test
????public?void?test1()?throws?Exception{
????????RsaUtils.generateKey(publicKey,privateKey,"dpb",1024);
????}
}
1234567891011121314151617
2.3認(rèn)證系統(tǒng)創(chuàng)建
接下來(lái)我們創(chuàng)建我們的認(rèn)證服務(wù)。
導(dǎo)入相關(guān)的依賴(lài)
<dependencies>
????<dependency>
????????<groupId>org.springframework.bootgroupId>
????????<artifactId>spring-boot-starter-webartifactId>
????dependency>
????<dependency>
????????<groupId>org.springframework.bootgroupId>
????????<artifactId>spring-boot-starter-securityartifactId>
????dependency>
????<dependency>
????????<artifactId>security-jwt-commonartifactId>
????????<groupId>com.dpbgroupId>
????????<version>1.0-SNAPSHOTversion>
????dependency>
????<dependency>
????????<groupId>mysqlgroupId>
????????<artifactId>mysql-connector-javaartifactId>
????????<version>5.1.47version>
????dependency>
????<dependency>
????????<groupId>org.mybatis.spring.bootgroupId>
????????<artifactId>mybatis-spring-boot-starterartifactId>
????????<version>2.1.0version>
????dependency>
????<dependency>
????????<groupId>com.alibabagroupId>
????????<artifactId>druidartifactId>
????????<version>1.1.10version>
????dependency>
????<dependency>
????????<groupId>org.springframework.bootgroupId>
????????<artifactId>spring-boot-configuration-processorartifactId>
????????<optional>trueoptional>
????dependency>
dependencies>
1234567891011121314151617181920212223242526272829303132333435
創(chuàng)建配置文件
spring:
??datasource:
????driver-class-name:?com.mysql.jdbc.Driver
????url:?jdbc:mysql://localhost:3306/srm
????username:?root
????password:?123456
????type:?com.alibaba.druid.pool.DruidDataSource
mybatis:
??type-aliases-package:?com.dpb.domain
??mapper-locations:?classpath:mapper/*.xml
logging:
??level:
????com.dpb:?debug
rsa:
??key:
????pubKeyFile:?c:\tools\auth_key\id_key_rsa.pub
????priKeyFile:?c:\tools\auth_key\id_key_rsa
1234567891011121314151617
提供公鑰私鑰的配置類(lèi)
package?com.dpb.config;
import?com.dpb.utils.RsaUtils;
import?lombok.Data;
import?org.springframework.boot.context.properties.ConfigurationProperties;
import?org.springframework.context.annotation.Configuration;
import?javax.annotation.PostConstruct;
import?java.security.PrivateKey;
import?java.security.PublicKey;
/**
?*?@program:?springboot-54-security-jwt-demo
?*?@description:
?*?@author:?波波烤鴨
?*?@create:?2019-12-03?11:25
?*/
@Data
@ConfigurationProperties(prefix?=?"rsa.key")
public?class?RsaKeyProperties?{
????private?String?pubKeyFile;
????private?String?priKeyFile;
????private?PublicKey?publicKey;
????private?PrivateKey?privateKey;
????/**
?????*?系統(tǒng)啟動(dòng)的時(shí)候觸發(fā)
?????*?@throws?Exception
?????*/
????@PostConstruct
????public?void?createRsaKey()?throws?Exception?{
????????publicKey?=?RsaUtils.getPublicKey(pubKeyFile);
????????privateKey?=?RsaUtils.getPrivateKey(priKeyFile);
????}
}
1234567891011121314151617181920212223242526272829303132333435363738
創(chuàng)建啟動(dòng)類(lèi)
/**
?*?@program:?springboot-54-security-jwt-demo
?*?@description:?啟動(dòng)類(lèi)
?*?@author:?波波烤鴨
?*?@create:?2019-12-03?11:23
?*/
@SpringBootApplication
@MapperScan("com.dpb.mapper")
@EnableConfigurationProperties(RsaKeyProperties.class)
public?class?App?{
????public?static?void?main(String[]?args)?{
????????SpringApplication.run(App.class,args);
????}
}
123456789101112131415
完成數(shù)據(jù)認(rèn)證的邏輯
pojo
package?com.dpb.domain;
import?com.fasterxml.jackson.annotation.JsonIgnore;
import?lombok.Data;
import?org.springframework.security.core.GrantedAuthority;
/**
?*?@program:?springboot-54-security-jwt-demo
?*?@description:
?*?@author:?波波烤鴨
?*?@create:?2019-12-03?15:21
?*/
@Data
public?class?RolePojo?implements?GrantedAuthority?{
????private?Integer?id;
????private?String?roleName;
????private?String?roleDesc;
????@JsonIgnore
????@Override
????public?String?getAuthority()?{
????????return?roleName;
????}
}
12345678910111213141516171819202122232425
package?com.dpb.domain;
import?com.fasterxml.jackson.annotation.JsonIgnore;
import?lombok.Data;
import?org.springframework.security.core.GrantedAuthority;
import?org.springframework.security.core.authority.SimpleGrantedAuthority;
import?org.springframework.security.core.userdetails.UserDetails;
import?java.util.ArrayList;
import?java.util.Collection;
import?java.util.List;
/**
?*?@program:?springboot-54-security-jwt-demo
?*?@description:
?*?@author:?波波烤鴨
?*?@create:?2019-12-03?11:33
?*/
@Data
public?class?UserPojo?implements?UserDetails?{
????private?Integer?id;
????private?String?username;
????private?String?password;
????private?Integer?status;
????private?List?roles;
????@JsonIgnore
????@Override
????public?Collection?extends?GrantedAuthority>?getAuthorities()?{
????????List?auth?=?new?ArrayList<>();
????????auth.add(new?SimpleGrantedAuthority("ADMIN"));
????????return?auth;
????}
????@Override
????public?String?getPassword()?{
????????return?this.password;
????}
????@Override
????public?String?getUsername()?{
????????return?this.username;
????}
????@JsonIgnore
????@Override
????public?boolean?isAccountNonExpired()?{
????????return?true;
????}
????@JsonIgnore
????@Override
????public?boolean?isAccountNonLocked()?{
????????return?true;
????}
????@JsonIgnore
????@Override
????public?boolean?isCredentialsNonExpired()?{
????????return?true;
????}
????@JsonIgnore
????@Override
????public?boolean?isEnabled()?{
????????return?true;
????}
}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
Mapper接口
public?interface?UserMapper?{
????public?UserPojo?queryByUserName(@Param("userName")?String?userName);
}
123
Mapper映射文件
mapper
????????PUBLIC?"-//mybatis.org//DTD?Mapper?3.0//EN"
????????"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper?namespace="com.dpb.mapper.UserMapper">
????<select?id="queryByUserName"?resultType="UserPojo">
????????select?*?from?t_user?where?username?=?#{userName}
????select>
mapper>
123456789
Service
public?interface?UserService?extends?UserDetailsService?{
}
123
@Service
@Transactional
public?class?UserServiceImpl?implements?UserService?{
????@Autowired
????private?UserMapper?mapper;
????@Override
????public?UserDetails?loadUserByUsername(String?s)?throws?UsernameNotFoundException?{
????????UserPojo?user?=?mapper.queryByUserName(s);
????????return?user;
????}
}
1234567891011121314
自定義認(rèn)證過(guò)濾器
package?com.dpb.filter;
import?com.dpb.config.RsaKeyProperties;
import?com.dpb.domain.RolePojo;
import?com.dpb.domain.UserPojo;
import?com.dpb.utils.JwtUtils;
import?com.fasterxml.jackson.databind.ObjectMapper;
import?net.bytebuddy.agent.builder.AgentBuilder;
import?org.springframework.security.authentication.AuthenticationManager;
import?org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import?org.springframework.security.core.Authentication;
import?org.springframework.security.core.AuthenticationException;
import?org.springframework.security.core.authority.SimpleGrantedAuthority;
import?org.springframework.security.core.userdetails.User;
import?org.springframework.security.core.userdetails.UserDetails;
import?org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import?javax.servlet.FilterChain;
import?javax.servlet.ServletException;
import?javax.servlet.http.HttpServletRequest;
import?javax.servlet.http.HttpServletResponse;
import?java.io.IOException;
import?java.io.PrintWriter;
import?java.util.ArrayList;
import?java.util.HashMap;
import?java.util.List;
import?java.util.Map;
/**
?*?@program:?springboot-54-security-jwt-demo
?*?@description:
?*?@author:?波波烤鴨
?*?@create:?2019-12-03?11:57
?*/
public?class?TokenLoginFilter?extends?UsernamePasswordAuthenticationFilter?{
????private?AuthenticationManager?authenticationManager;
????private?RsaKeyProperties?prop;
????public?TokenLoginFilter(AuthenticationManager?authenticationManager,?RsaKeyProperties?prop)?{
????????this.authenticationManager?=?authenticationManager;
????????this.prop?=?prop;
????}
????public?Authentication?attemptAuthentication(HttpServletRequest?request,?HttpServletResponse?response)?throws?AuthenticationException?{
????????try?{
????????????UserPojo?sysUser?=?new?ObjectMapper().readValue(request.getInputStream(),?UserPojo.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?{
????????UserPojo?user?=?new?UserPojo();
????????user.setUsername(authResult.getName());
????????user.setRoles((List)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();
????????}
????}
}
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
自定義校驗(yàn)token的過(guò)濾器
package?com.dpb.filter;
import?com.dpb.config.RsaKeyProperties;
import?com.dpb.domain.Payload;
import?com.dpb.domain.UserPojo;
import?com.dpb.utils.JwtUtils;
import?com.fasterxml.jackson.databind.ObjectMapper;
import?org.springframework.security.authentication.AuthenticationManager;
import?org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import?org.springframework.security.core.context.SecurityContextHolder;
import?org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import?javax.servlet.FilterChain;
import?javax.servlet.ServletException;
import?javax.servlet.http.HttpServletRequest;
import?javax.servlet.http.HttpServletResponse;
import?java.io.IOException;
import?java.io.PrintWriter;
import?java.util.HashMap;
import?java.util.Map;
/**
?*?@program:?springboot-54-security-jwt-demo
?*?@description:
?*?@author:?波波烤鴨
?*?@create:?2019-12-03?12:39
?*/
public?class?TokenVerifyFilter??extends?BasicAuthenticationFilter?{
????private?RsaKeyProperties?prop;
????public?TokenVerifyFilter(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?payload?=?JwtUtils.getInfoFromToken(token,?prop.getPublicKey(),?UserPojo.class);
????????????UserPojo?user?=?payload.getUserInfo();
????????????if(user!=null){
????????????????UsernamePasswordAuthenticationToken?authResult?=?new?UsernamePasswordAuthenticationToken(user.getUsername(),?null,?user.getAuthorities());
????????????????SecurityContextHolder.getContext().setAuthentication(authResult);
????????????????chain.doFilter(request,?response);
????????????}
????????}
????}
}
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
###編寫(xiě)SpringSecurity的配置類(lèi)
package?com.dpb.config;
import?com.dpb.filter.TokenLoginFilter;
import?com.dpb.filter.TokenVerifyFilter;
import?com.dpb.service.UserService;
import?org.springframework.beans.factory.annotation.Autowired;
import?org.springframework.context.annotation.Bean;
import?org.springframework.context.annotation.Configuration;
import?org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import?org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import?org.springframework.security.config.annotation.web.builders.HttpSecurity;
import?org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import?org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import?org.springframework.security.config.http.SessionCreationPolicy;
import?org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
/**
?*?@program:?springboot-54-security-jwt-demo
?*?@description:
?*?@author:?波波烤鴨
?*?@create:?2019-12-03?12:41
?*/
@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("/user/query").hasAnyRole("ADMIN")
????????????????.anyRequest()
????????????????.authenticated()
????????????????.and()
????????????????.addFilter(new?TokenLoginFilter(super.authenticationManager(),?prop))
????????????????.addFilter(new?TokenVerifyFilter(super.authenticationManager(),?prop))
????????????????.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
????}
}
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
啟動(dòng)服務(wù)測(cè)試
啟動(dòng)服務(wù)
通過(guò)Postman來(lái)訪問(wèn)測(cè)試
根據(jù)token信息我們?cè)L問(wèn)其他資源
2.4資源系統(tǒng)創(chuàng)建
說(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ù)一樣了。
接下來(lái)我們?cè)賱?chuàng)建一個(gè)資源服務(wù)
導(dǎo)入相關(guān)的依賴(lài)
<dependencies>
????<dependency>
????????<groupId>org.springframework.bootgroupId>
????????<artifactId>spring-boot-starter-webartifactId>
????dependency>
????<dependency>
????????<groupId>org.springframework.bootgroupId>
????????<artifactId>spring-boot-starter-securityartifactId>
????dependency>
????<dependency>
????????<artifactId>security-jwt-commonartifactId>
????????<groupId>com.dpbgroupId>
????????<version>1.0-SNAPSHOTversion>
????dependency>
????<dependency>
????????<groupId>mysqlgroupId>
????????<artifactId>mysql-connector-javaartifactId>
????????<version>5.1.47version>
????dependency>
????<dependency>
????????<groupId>org.mybatis.spring.bootgroupId>
????????<artifactId>mybatis-spring-boot-starterartifactId>
????????<version>2.1.0version>
????dependency>
????<dependency>
????????<groupId>com.alibabagroupId>
????????<artifactId>druidartifactId>
????????<version>1.1.10version>
????dependency>
????<dependency>
????????<groupId>org.springframework.bootgroupId>
????????<artifactId>spring-boot-configuration-processorartifactId>
????????<optional>trueoptional>
????dependency>
dependencies>
1234567891011121314151617181920212223242526272829303132333435
編寫(xiě)產(chǎn)品服務(wù)配置文件
切記這里只能有公鑰地址!
server:
??port:?9002
spring:
??datasource:
????driver-class-name:?com.mysql.jdbc.Driver
????url:?jdbc:mysql://localhost:3306/srm
????username:?root
????password:?123456
????type:?com.alibaba.druid.pool.DruidDataSource
mybatis:
??type-aliases-package:?com.dpb.domain
??mapper-locations:?classpath:mapper/*.xml
logging:
??level:
????com.dpb:?debug
rsa:
??key:
????pubKeyFile:?c:\tools\auth_key\id_key_rsa.pub
123456789101112131415161718
編寫(xiě)讀取公鑰的配置類(lèi)
package?com.dpb.config;
import?com.dpb.utils.RsaUtils;
import?lombok.Data;
import?org.springframework.boot.context.properties.ConfigurationProperties;
import?javax.annotation.PostConstruct;
import?java.security.PrivateKey;
import?java.security.PublicKey;
/**
?*?@program:?springboot-54-security-jwt-demo
?*?@description:
?*?@author:?波波烤鴨
?*?@create:?2019-12-03?11:25
?*/
@Data
@ConfigurationProperties(prefix?=?"rsa.key")
public?class?RsaKeyProperties?{
????private?String?pubKeyFile;
????private?PublicKey?publicKey;
????/**
?????*?系統(tǒng)啟動(dòng)的時(shí)候觸發(fā)
?????*?@throws?Exception
?????*/
????@PostConstruct
????public?void?createRsaKey()?throws?Exception?{
????????publicKey?=?RsaUtils.getPublicKey(pubKeyFile);
????}
}
12345678910111213141516171819202122232425262728293031323334
編寫(xiě)啟動(dòng)類(lèi)
package?com.dpb;
import?com.dpb.config.RsaKeyProperties;
import?org.mybatis.spring.annotation.MapperScan;
import?org.springframework.boot.SpringApplication;
import?org.springframework.boot.autoconfigure.SpringBootApplication;
import?org.springframework.boot.context.properties.EnableConfigurationProperties;
/**
?*?@program:?springboot-54-security-jwt-demo
?*?@description:
?*?@author:?波波烤鴨
?*?@create:?2019-12-03?17:23
?*/
@SpringBootApplication
@MapperScan("com.dpb.mapper")
@EnableConfigurationProperties(RsaKeyProperties.class)
public?class?App?{
????public?static?void?main(String[]?args)?{
????????SpringApplication.run(App.class,args);
????}
}
1234567891011121314151617181920212223
復(fù)制認(rèn)證服務(wù)中,用戶(hù)對(duì)象,角色對(duì)象和校驗(yàn)認(rèn)證的接口
復(fù)制認(rèn)證服務(wù)中的相關(guān)內(nèi)容即可
復(fù)制認(rèn)證服務(wù)中SpringSecurity配置類(lèi)做修改
package?com.dpb.config;
import?com.dpb.filter.TokenVerifyFilter;
import?com.dpb.service.UserService;
import?org.springframework.beans.factory.annotation.Autowired;
import?org.springframework.context.annotation.Bean;
import?org.springframework.context.annotation.Configuration;
import?org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import?org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import?org.springframework.security.config.annotation.web.builders.HttpSecurity;
import?org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import?org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import?org.springframework.security.config.http.SessionCreationPolicy;
import?org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
/**
?*?@program:?springboot-54-security-jwt-demo
?*?@description:
?*?@author:?波波烤鴨
?*?@create:?2019-12-03?12:41
?*/
@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("/user/query").hasAnyRole("USER")
????????????????.anyRequest()
????????????????.authenticated()
????????????????.and()
????????????????.addFilter(new?TokenVerifyFilter(super.authenticationManager(),?prop))
????????????????//?禁用掉session
????????????????.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
????}
}
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
去掉“增加自定義認(rèn)證過(guò)濾器”即可!
編寫(xiě)產(chǎn)品處理器
package?com.dpb.controller;
import?org.springframework.security.access.annotation.Secured;
import?org.springframework.web.bind.annotation.RequestMapping;
import?org.springframework.web.bind.annotation.RestController;
/**
?*?@program:?springboot-54-security-jwt-demo
?*?@description:
?*?@author:?波波烤鴨
?*?@create:?2019-12-03?11:55
?*/
@RestController
@RequestMapping("/user")
public?class?UserController?{
????@RequestMapping("/query")
????public?String?query(){
????????return?"success";
????}
????@RequestMapping("/update")
????public?String?update(){
????????return?"update";
????}
}
1234567891011121314151617181920212223242526
測(cè)試
搞定~
-END- 如果你能看到這里,那么下面這套教程,你一定要領(lǐng)取!最近有讀者想要分布式的項(xiàng)目,還有想要商城的,還有想要springboot,springcloud,k8s等等,這次直接分享幾乎涵蓋了我們java程序員的大部分技術(shù)桟,可以說(shuō)真的非常全面了。強(qiáng)烈建議大家都上手做一做,而且以后肯定用的上。資料包含高清視頻+課件+源碼……
掃以下二維碼并回復(fù)“99”即可獲取
掃描上方二維碼,關(guān)注并回復(fù)【99】馬上獲取







