1、分布式认证介绍
1.1 概念
分布式认证,即我们常说的单点登录,简称SSO,指的是在多应用系统的项目中,用户只需要登录一次,就可以访
问所有互相信任的应用系统。
1.2 分布式认证流程
首先,我们要明确,在分布式项目中,每台服务器都有各自独立的session,而这些session之间是无法直接共享资源的,所以,session通常不能被作为单点登录的技术方案。
最合理的单点登录方案流程如下图所示:
总结一下,单点登录的实现分两大环节:
- 用户认证:这一环节主要是用户向认证服务器发起认证请求,认证服务器给用户返回一个成功的令牌token,
主要在认证服务器中完成,即图中的A系统,注意A系统只能有一个。
- 身份校验:这一环节是用户携带token去访问其他服务器时,在其他服务器中要对token的真伪进行检验,主
要在资源服务器中完成,即图中的B系统,这里B系统可以有很多个。
2、JWT介绍
2.1 概念
从分布式认证流程中,我们不难发现,这中间起最关键作用的就是token,token的安全与否,直接关系到系统的
健壮性,这里我们选择使用JWT来实现token的生成和校验。
JWT,全称JSON Web Token,官网地址https://jwt.io,是一款出色的分布式身份校验方案。可以生成token,也可以解析检验token。
JWT生成的token由三部分组成:
-
头部:主要设置一些规范信息,签名部分的编码格式就在头部中声明。
-
载荷:token中存放有效信息的部分,比如用户名,用户角色,过期时间等,但是不要放密码,会泄露!
-
签名:将头部与载荷分别采用base64编码后,用“.”相连,再加入盐,最后使用头部声明的编码类型进行编码,就得到了签名。
2.2 JWT生成token的安全性分析
从JWT生成的token组成上来看,要想避免token被伪造,主要就得看签名部分了,而签名部分又有三部分组成,其中头部和载荷的base64编码,几乎是透明的,毫无安全性可言,那么最终守护token安全的重担就落在了加入的盐上面了!
试想:如果生成token所用的盐与解析token时加入的盐是一样的。岂不是类似于中国人民银行把人民币防伪技术公开了?大家可以用这个盐来解析token,就能用来伪造token。
所以,我们就需要对盐采用非对称加密的方式进行加密,以达到生成token与校验token方所用的盐不一致的安全效果!
3、非对称加密RSA介绍
基本原理:同时生成两把密钥:私钥和公钥,私钥隐秘保存,公钥可以下发给信任客户端;
-
私钥加密,持有私钥或公钥才可以解密
-
公钥加密,持有私钥才可解密
优点:安全,难以破解;
缺点:算法比较耗时,为了安全,可以接受;
历史:三位数学家Rivest、Shamir 和 Adleman 设计了一种算法,可以实现非对称加密。这种算法用他们三
个人的名字缩写:RSA。
一般采取的方式是:认证服务器使用私钥进行加密,其他客户端使用公钥进行解密,然后验证token是否正确。
为什么不采取公钥加密呢?
我们可以假设采用公钥加密,那么其他客户端保存的就是私钥信息,如果这个客户端有伪造token的请求,它就会使用自己的私钥进行加密,那么其他客户端的私钥也就能解密这个token,那么伪造token就成功了。这是不安全的。所以我们必须让认证服务器可以进行加密,其中如果有一个客户端伪造token,进行私钥,会导致其他客户端无法解密,这样伪造token的目的就达不到了。而私钥加密,公钥解密正好可以满足。
4、分布式认证
4.1 创建父模块springboot_security_jwt_rsa_parent
pom.xml中加入下面的依赖:
<?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>
<artifactId>springboot_security_jwt_rsa_parent</artifactId>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/>
</parent>
</project>
4.2 创建公共模块security_common
在4.1创建的模块下新增一个子模块securit_common:在里面创建我们需要的一些工具类,方便其他模块去调用
4.2.1 pom.xml
<?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>org.springframework.boot</groupId>
<version>2.1.3.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.zdwhong</groupId>
<artifactId>security_common</artifactId>
<version>1.0-SNAPSHOT</version>
<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>
4.2.2 工具类JsonUtils
package com.zdwhong.util;
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;
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;
}
}
}
4.2.3 工具类JwtUtils
package com.zdwhong.util;
import com.zdwhong.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;
/**
* 生成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;
}
}
4.2.4 工具类RsaUtils
package com.zdwhong.util;
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;
public class RsaUtils {
private static final int DEFAULT_KEY_SIZE = 2048;
/**
* 从文件中读取公钥
*
* @param filename 公钥保存路径,相对于classpath
* @return 公钥对象
* @throws Exception
*/
public static PublicKey getPublicKeyFromClasspath(String filename) throws Exception {
String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
byte[] bytes = readFile(basePath+filename);
return getPublicKey(bytes);
}
/**
* 从文件中读取公钥
*
* @param filename 公钥保存路径,相对于文件夹路径
* @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 getPrivateKeyFromClasspath(String filename) throws Exception {
String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
byte[] bytes = readFile(basePath+filename);
return getPrivateKey(bytes);
}
/**
* 从文件中读取密钥
*
* @param filename 私钥保存路径,相对于文件夹路径
* @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);
}
}
4.2.5 token的载荷对象PayLoad
package com.zdwhong.domain;
import lombok.Data;
import java.util.Date;
/**
* @author ZDW
* @create 2020-07-19 21:39
* 为了方便后期获取token中的用户信息,将token中载荷部分单独封装成一个对象
*/
@Data
public class Payload<T> {
private String id;
//用户信息
private T userInfo;
//过期时间
private Date expiration;
}
4.2.6 编写测试类生成rsa公钥和私钥
package com.zdwhong.test;
import com.zdwhong.util.RsaUtils;
import org.junit.Test;
/**
* @author ZDW
* @create 2020-07-19 21:50
*/
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, "zdwhong", 2048);
}
}
一定要注意保存这两个密钥,可以把这公钥放到客户端的resources下面,把私钥放到认证服务的resources下面;
4.3 SpringSecurity+JWT+RSA分布式认证思路分析
SpringSecurity主要是通过过滤器来实现功能的!我们要找到SpringSecurity实现认证和校验身份的过滤器!
4.3.1 回顾集中式认证流程
-
用户认证:(jsp页面使用是form表单提交)使用UsernamePasswordAuthenticationFilter过滤器中attemptAuthentication方法实现认证功能,该过滤器父类中successfulAuthentication方法实现认证成功后的操作。
-
身份校验:使用BasicAuthenticationFilter过滤器中doFilterInternal方法验证是否登录,以决定能否进入后续过滤器。
4.3.2 分析分布式认证流程
-
用户认证:
由于分布式项目,多数是前后端分离的架构设计,我们要满足可以接受异步post的认证请求参数,需要修改UsernamePasswordAuthenticationFilter过滤器中attemptAuthentication方法,让其能够接收请求体。另外,默认successfulAuthentication方法在认证通过后,是把用户信息直接放入session就完事了,现在我们需要修改这个方法,在认证通过后生成token并返回给用户。
-
身份校验:
原来BasicAuthenticationFilter过滤器中doFilterInternal方法校验用户是否登录,就是看session中是否有用户信息,我们要修改为,验证用户携带的token是否合法,并解析出用户信息,交给SpringSecurity,以便于后续的授权功能可以正常使用。
4.4 创建认证服务模块
4.4.1 pom.xml加入依赖
<?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>org.springframework.boot</groupId>
<version>2.1.3.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.zdwhong</groupId>
<artifactId>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.zdwhong</groupId>
<artifactId>security_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>
4.4.2 配置文件application.yml
server:
port: 9001
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.56.102/spring_security?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&useSSL=false
username: root
password: 123456
mybatis:
type-aliases-package: com.zdwhong.domain
configuration:
map-underscore-to-camel-case: true
logging:
level:
com.itheima: debug
rsa:
key:
pubKeyPath: rsakey/rsa_key.pub
priKeyPath: rsakey/rsa_key
4.4.3 提供解析公钥和私钥的配置类
package com.zdwhong.config;
import com.zdwhong.util.RsaUtils;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import javax.annotation.PostConstruct;
import java.security.PrivateKey;
import java.security.PublicKey;
/**
* @author ZDW
* @create 2020-07-19 22:05
*/
@Data
@ConfigurationProperties(prefix = "rsa.key")
public class RsaKeyProperties {
//公钥的路经
private String pubKeyPath;
//私钥路径
private String priKeyPath;
//公钥对象
private PublicKey publicKey;
//私钥对象
private PrivateKey privateKey;
//这个注解标注的方法会在这个类初始化之后执行,然后对公钥和私钥对象初始化
@PostConstruct
public void loadKey() throws Exception {
publicKey = RsaUtils.getPublicKeyFromClasspath(pubKeyPath);
privateKey = RsaUtils.getPrivateKeyFromClasspath(priKeyPath);
}
}
4.4.4 创建认证服务启动类
package com.zdwhong;
import com.zdwhong.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;
/**
* @author ZDW
* @create 2020-07-19 22:27
*/
@SpringBootApplication
@MapperScan("com.zdwhong.mapper")
//RsaKeyProperties使该文件生效
@EnableConfigurationProperties(RsaKeyProperties.class)
public class AuthServerApplication {
public static void main(String[] args) {
SpringApplication.run(AuthServerApplication.class,args);
}
}
4.4.5 将之前代码controlelr,service,mapper等复制过来
注意这里要去掉mapper中继承的通用mapper接口
处理器类上换成**@RestController**,这里前后端绝对分离,不能再跳转页面了,要返回数据。
4.4.6 编写认证过滤器
自定义过滤器JwtLoginFilter,继承UsernamePasswordAuthenticationFilter,重写认证方法和认证成功之后执行的方法
package com.zdwhong.filter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zdwhong.config.RsaKeyProperties;
import com.zdwhong.domain.SysRole;
import com.zdwhong.domain.SysUser;
import com.zdwhong.util.JwtUtils;
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.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.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author ZDW
* @create 2020-07-27 21:39
*/
public class JwtLoginFilter extends UsernamePasswordAuthenticationFilter {
private AuthenticationManager authenticationManager;
private RsaKeyProperties rsaKeyProperties;
public JwtLoginFilter(AuthenticationManager authenticationManager, RsaKeyProperties rsaKeyProperties) {
this.authenticationManager = authenticationManager;
this.rsaKeyProperties = rsaKeyProperties;
}
/**
* 重写认证的方法
* @param request
* @param response
* @return
* @throws AuthenticationException
*/
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
try {
//从请求体中获取用户信息,将json格式的请求体转成用户对象,所以前台传的是json格式的信息
SysUser sysUser = new ObjectMapper().readValue(request.getInputStream(), SysUser.class);
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(sysUser.getUsername(),sysUser.getPassword());
return authenticationManager.authenticate(authRequest);
}catch (Exception e) {
//认证失败,定义json格式的数据返回给客户端
response.setContentType("application/json;charset=utf-8");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
try {
PrintWriter writer = response.getWriter();
Map<String,Object> map = new HashMap<>();
map.put("code",HttpServletResponse.SC_UNAUTHORIZED);
map.put("msg","用户名或密码错误");
writer.write(new ObjectMapper().writeValueAsString(map));
writer.flush();
writer.close();
}catch (Exception ex) {
ex.printStackTrace();
}
throw new RuntimeException();
}
}
/**
* 重写认证成功之后的方法,目的是给客户端返回一个token
* @param request
* @param response
* @param chain
* @param authResult
* @throws IOException
* @throws ServletException
*/
@Override
public void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
FilterChain chain, Authentication authResult) throws IOException, ServletException {
//获取当前认证的对象
SysUser sysUser = new SysUser();
sysUser.setUsername(authResult.getName());
sysUser.setId(((SysUser)authResult.getPrincipal()).getId());
sysUser.setRoles((List<SysRole>) authResult.getAuthorities());
//获取生成token的私钥
PrivateKey privateKey = rsaKeyProperties.getPrivateKey();
//定义token过期时间为一天
int expireTime = 24 * 60;
//生成token
String token = JwtUtils.generateTokenExpireInMinutes(sysUser, privateKey, expireTime);
//把token添加到响应头中,返回给客户端
response.setHeader("Authorization","Bearer "+token);
try {
response.setContentType("application/json;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter writer = response.getWriter();
Map<String,Object> map = new HashMap<>();
map.put("code",HttpServletResponse.SC_OK);
map.put("msg","认证成功");
writer.write(new ObjectMapper().writeValueAsString(map));
writer.flush();
writer.close();
}catch (Exception ex) {
ex.printStackTrace();
}
}
}
4.4.7 编写token的验证过滤器
原来的验证逻辑是BasicAuthenticationFilter来实现的,现在我们自定义过滤器,继承它,重写它过滤请求的方法:
package com.zdwhong.filter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zdwhong.config.RsaKeyProperties;
import com.zdwhong.domain.Payload;
import com.zdwhong.domain.SysUser;
import com.zdwhong.util.JwtUtils;
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;
/**
* 验证登录的filter
* @author ZDW
* @create 2020-07-27 21:58
*/
public class JwtVerifyFilter extends BasicAuthenticationFilter {
private RsaKeyProperties rsaKeyProperties;
public JwtVerifyFilter(AuthenticationManager authenticationManager,RsaKeyProperties rsaKeyProperties) {
super(authenticationManager);
this.rsaKeyProperties = rsaKeyProperties;
}
//过滤请求
@Override
public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
//从请求头中取出Authorization
String header = request.getHeader("Authorization");
response.setContentType("application/json;charset=utf-8");
//如果没有认证或者token错误,提示用户登录
if(header == null || !header.startsWith("Bearer ")) {
chain.doFilter(request,response);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
PrintWriter writer = response.getWriter();
Map<String,Object> map = new HashMap<>();
map.put("code",HttpServletResponse.SC_UNAUTHORIZED);
map.put("msg","请登录");
writer.write(new ObjectMapper().writeValueAsString(map));
writer.flush();
writer.close();
}else {
//如果token格式正确,就验证token
Payload<SysUser> payload = JwtUtils.getInfoFromToken(header.replace("Bearer ", ""), rsaKeyProperties.getPublicKey(), SysUser.class);
SysUser sysUser = payload.getUserInfo();
if(sysUser != null) {
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(sysUser.getUsername(),null,sysUser.getAuthorities());
//把Authentication写入SecurityContextHolder中,供后续使用
SecurityContextHolder.getContext().setAuthentication(authRequest);
chain.doFilter(request,response);
}else {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
PrintWriter writer = response.getWriter();
Map<String,Object> map = new HashMap<>();
map.put("code",HttpServletResponse.SC_UNAUTHORIZED);
map.put("msg","验证失败");
writer.write(new ObjectMapper().writeValueAsString(map));
writer.flush();
writer.close();
}
}
}
}
4.4.8 编写Security配置类
package com.zdwhong.config;
import com.zdwhong.filter.JwtLoginFilter;
import com.zdwhong.filter.JwtVerifyFilter;
import com.zdwhong.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.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;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
@Autowired
private RsaKeyProperties rsaKeyProperties;
/**
* 把加密对象放入IOC容器中
*/
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
/*** 使用数据库中的用户 */
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//配置自定义的用户信息
auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
}
//SpringSecurity配置信息
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf()
.disable()
.authorizeRequests()
//表示/product需要USER角色
.antMatchers("/product").hasAnyRole("USER")
//表示其他的任意请求都是需要先登录才能访问
.anyRequest().authenticated()
.and()
//添加认证过滤器
.addFilter(new JwtLoginFilter(super.authenticationManager(),rsaKeyProperties))
//添加验证过滤器
.addFilter(new JwtVerifyFilter(super.authenticationManager(),rsaKeyProperties))
//禁用session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
;
}
}
4.4.9 测试
执行启动类,使用postman测试:
登录测试:
可以查看响应头中的Authorization头:
访问资源测试:现在访问资源的时候,请求头中要有Authorization
其中肯定还有不完善的地方,需要优化,用到的时候需要多次测试和优化。
4.5 资源服务
说明:资源服务可以有很多个,这里只拿产品服务为例,记住,资源服务中只能通过公钥验证认证。不能签发token!
4.5.1 创建产品服务并导入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>org.springframework.boot</groupId>
<version>2.1.3.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>product_source</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.zdwhong</groupId>
<artifactId>security_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>
4.5.2 编写产品服务配置文件application.yml
切记这里只能有公钥地址!
server:
port: 9002
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.56.102/spring_security?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&useSSL=false
username: root
password: 123456
mybatis:
type-aliases-package: com.zdwhong.domain
configuration:
map-underscore-to-camel-case: true
logging:
level:
com.itheima: debug
rsa:
key:
pubKeyPath: rsakey/rsa_key.pub
4.5.3 编写读取公钥的配置类
package com.zdwhong.config;
import com.zdwhong.util.RsaUtils;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import javax.annotation.PostConstruct;
import java.security.PrivateKey;
import java.security.PublicKey;
/**
* @author ZDW
* @create 2020-07-19 22:05
*/
@Data
@ConfigurationProperties(prefix = "rsa.key")
public class RsaKeyProperties {
//公钥的路经
private String pubKeyPath;
//公钥对象
private PublicKey publicKey;
//这个注解标注的方法会在这个类初始化之后执行,然后对公钥和私钥对象初始化
@PostConstruct
public void loadKey() throws Exception {
publicKey = RsaUtils.getPublicKeyFromClasspath(pubKeyPath);
}
}
4.5.4 编写启动类
启动类上要开启支持权限注解:@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true, jsr250Enabled = true)
package com.zdwhong;
import com.zdwhong.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;
/**
* @author ZDW
* @create 2020-07-28 8:34
*/
@SpringBootApplication
@MapperScan("com.zdwhong.mapper")
@EnableConfigurationProperties(RsaKeyProperties.class)
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true, jsr250Enabled = true)
public class ProduceSourceApplication {
public static void main(String[] args) {
SpringApplication.run(ProduceSourceApplication.class,args);
}
}
4.5.5 复制认证服务中,用户对象,角色对象和校验认证的接口
复制:SysUser,SysRole和JwtVerifyFilter
4.5.6 复制认证服务中SpringSecurity配置类做修改
去掉“增加自定义认证过滤器”即可!
package com.zdwhong.config;
import com.zdwhong.filter.JwtVerifyFilter;
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.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;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private RsaKeyProperties rsaKeyProperties;
/**
* 把加密对象放入IOC容器中
*/
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
//SpringSecurity配置信息
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf()
.disable()
.authorizeRequests()
//表示/product需要USER角色
.antMatchers("/product").hasAnyRole("USER")
//表示其他的任意请求都是需要先登录才能访问
.anyRequest().authenticated()
.and()
//添加验证过滤器
.addFilter(new JwtVerifyFilter(super.authenticationManager(),rsaKeyProperties))
//禁用session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
;
}
}
4.5.7 编写资源controller
package com.zdwhong.controller;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author ZDW
* @create 2020-07-18 21:30
*/
@RestController
@RequestMapping("product")
public class ProductController {
@Secured("ROLE_PRODUCT")
@RequestMapping("/findAll")
public String findAll() {
return "产品列表查询成功";
}
}
添加了注解:@Secured(“ROLE_PRODUCT”) 表示需要有ROLE_PRODUCT权限才能访问,否则会报403错误。
4.5.8 测试
以 xiaoma/123456 访问认证服务,然后用返回的token访问资源服务,会报403错误,因为我们之前数据库配置中,xiaoma没有ROLE_PRODUCT权限;
以 xiaoming/123456 访问认证服务后,写到返回的token访问资源服务,可以正常访问。因为它有ROLE_PRODUCT权限。
USER角色
.antMatchers("/product").hasAnyRole(“USER”)
//表示其他的任意请求都是需要先登录才能访问
.anyRequest().authenticated()
.and()
//添加验证过滤器
.addFilter(new JwtVerifyFilter(super.authenticationManager(),rsaKeyProperties))
//禁用session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
;
}
}
### 4.5.7 编写资源controller
```java
package com.zdwhong.controller;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author ZDW
* @create 2020-07-18 21:30
*/
@RestController
@RequestMapping("product")
public class ProductController {
@Secured("ROLE_PRODUCT")
@RequestMapping("/findAll")
public String findAll() {
return "产品列表查询成功";
}
}
添加了注解:@Secured(“ROLE_PRODUCT”) 表示需要有ROLE_PRODUCT权限才能访问,否则会报403错误。
4.5.8 测试
以 xiaoma/123456 访问认证服务,然后用返回的token访问资源服务,会报403错误,因为我们之前数据库配置中,xiaoma没有ROLE_PRODUCT权限;
以 xiaoming/123456 访问认证服务后,写到返回的token访问资源服务,可以正常访问。因为它有ROLE_PRODUCT权限。