1. 为什么需要SSO
分布式中有很多微服务,某些服务需要用户登录完成才能进行操作,但是每个微服务独立,这样就会访问每个微服务都需要重新登录一次,SSO只要在SSO微服务登录,就可以一次登录,处处使用!
2. 传统单体项目实现登录
使用session实现登录和认证,springsecurity也是使用session
发一次请求就是一次会话,服务端会在开启一份独有的空间(也就是session,里面是使用map结构),并产生唯一的标识JessionId(uuid)与session内存空间进行绑定,根据JessionId就能访问这片空间,通过cookie回写jessionId,从而使得浏览器cookies保留的jessionId(就好像服务端给浏览器生成的钥匙一样),下次cookies自动携带jessionId到服务端,就知道你操作的是哪片内存空间。
浏览器的cookies存放对应你对应的domain:port里面,每个域的cookies都会隔离
3. 分布式项目实现登陆
传统单体cookies+session不适合分布式系统,有以下原因
- 前后端分离(前端与后台各为独立的工程),那么前端只能访问前端的cookies,后台只能访问后台的cookies,回写的到浏览器中是后台的cookies,这样导致前端cookies中没有这个钥匙;而在分布式系统中,后台的微服务各自独立,更无法共享。
- 后台集群的搭建,就会使用nginx进行反向代理与负载均衡,那么集群中的每个session数据不同步,集群之后session共享是一个很大的问题(解决:单点来存session)。
- 一个有很多子系统(门户,商铺,管理)每个都要实现登录功能,这种方式不可取的。
最终的方案采用:SSO来完成登录与认证!!!
4. SSO登录的两种方案
4.1 基于redis
登录成功后生成uuid(Token),用户信息存入redis中(k:v =uuid:用户信息),将uuid回写给前端,前端使用sessionStorage来存储uuid。用户请求微服务是在请求头中携带token,就去使用网关去校验token
每次验证都访问redis,有压力
4.2 基于JWT
把用户信息都写入客户浏览器中,涉及到安全问题,解决加密
只要加密用的salt与解密用的salt是一对的一定能打开
这种方式少了一个网络请求,效率更高
5. JWT令牌
对称和非对称加密作为JWT算法
JWT (JSON Web Token) 出色的分布式身份校验方案,由以下三部分构成
‘
6. salt泄露问题
利用生成token与校验token校验的salt是不一样的;
私钥用于生成token,公钥用于校验token;
RSA的数学原理
关于对称与非对称的结合使用
7. 使用
7.1 RSA公钥私钥的生成方法
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
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 getPublicKey(String filename) throws Exception {
byte[] bytes = readFile(filename);
return getPublicKey(bytes);
}
/**
* 从文件中读取密钥
*
* @param filename 私钥保存路径,相对于classpath
* @return 私钥对象
* @throws Exception
*/
public static PrivateKey getPrivateKey(String filename) throws Exception {
byte[] bytes = readFile(filename);
return getPrivateKey(bytes);
}
/**
* 获取公钥
* @param bytes 公钥的字节形式
* @return
* @throws Exception
*/
public 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
*/
public 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);
}
public static void main(String[] args)throws Exception {
String privateFilePath = "E:\\key\\rsa";
String publicFilePath = "E:\\key\\rsa.pub";
RsaUtils.generateKey(publicFilePath,privateFilePath,"portal",2048);
}
}
7.2 使用公钥与私钥生成与解析JWT
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.*;
/**
* 生成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) {
//计算过期时间
Calendar c = Calendar.getInstance();
c.add(Calendar.MINUTE,expire);
return Jwts.builder()
.claim(JWT_PAYLOAD_USER_KEY, JsonUtils.toString(userInfo))//将用户信息放入payload
.setId(new String(Base64.getEncoder().encode(UUID.randomUUID().toString().getBytes())))
.setExpiration(c.getTime())
.signWith(privateKey, SignatureAlgorithm.RS256)
.compact();
}
/**
* 私钥加密token
* @param userInfo 载荷中的数据
* @param privateKey 私钥
* @param expire 过期时间,单位秒
* @return JWT
*/
public static String generateTokenExpireInSeconds(Object userInfo, PrivateKey privateKey, int expire) {
//计算过期时间
Calendar c = Calendar.getInstance();
c.add(Calendar.SECOND,expire);
return Jwts.builder()
.claim(JWT_PAYLOAD_USER_KEY, JsonUtils.toString(userInfo))
.setId(new String(Base64.getEncoder().encode(UUID.randomUUID().toString().getBytes())))
.setExpiration(c.getTime())
.signWith(privateKey, SignatureAlgorithm.RS256)
.compact();
}
/**
* 获取token中的用户信息
* 解析令牌的方法
*
* @param token 用户请求中的令牌
* @param publicKey 公钥
* @return 用户信息
*/
public static Object getInfoFromToken(String token, PublicKey publicKey, Class userType) {
//解析token
Jws<Claims> claimsJws = Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
Claims body = claimsJws.getBody();//获取payload
String userInfoJson = body.get(JWT_PAYLOAD_USER_KEY).toString();
return JsonUtils.toBean(userInfoJson, userType);
}
}
7.3 使用的JsonUtils
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.List;
import java.util.Map;
public class JsonUtils {
public static final ObjectMapper mapper = new ObjectMapper();
/**
* 将对象转换成json串
* @param obj
* @return
*/
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) {
return null;
}
}
/**
* 将json串转换成对象
* @param json
* @param tClass
* @param <T>
* @return
*/
public static <T> T toBean(String json, Class<T> tClass) {
try {
return mapper.readValue(json, tClass);
} catch (IOException e) {
return null;
}
}
}
8. 后台使用
传到SSO先校验用户是否存在于对应密码是否正确,之后获取私钥来颁发令牌
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.djh.entity.user.WxbMember;
import org.djh.entity.vo.Result;
import org.djh.user.mapper.WxbMemberMapper;
import org.djh.user.service.IWxbMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.djh.utils.JwtUtils;
import org.djh.utils.RsaUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import java.security.PrivateKey;
/**
* @since 2021-05-25
*/
@Service
public class WxbMemberServiceImpl extends ServiceImpl<WxbMemberMapper, WxbMember> implements IWxbMemberService {
@Autowired
private WxbMemberMapper wxbMemberMapper;
@Override
public Result login(WxbMember member) {
//根据username获取user信息
//根据username获取user信息
QueryWrapper<WxbMember> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("account",member.getAccount());
WxbMember wxbMember =wxbMemberMapper.selectOne(queryWrapper);
if (wxbMember == null) {
return new Result(false,"用户名或者密码错误");
}
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
if(!encoder.matches(member.getPassword(),wxbMember.getPassword())){
return new Result(false,"用户名或者密码错误");
}
//获取私钥
PrivateKey privateKey = null;
try {
privateKey = RsaUtils.getPrivateKey(ResourceUtils.getFile("classpath:rsa").getPath());
} catch (Exception e) {
e.printStackTrace();
}
//颁发令牌 密码生日脱敏
wxbMember.setPassword(null);
String token = JwtUtils.generateTokenExpireInMinutes(wxbMember, privateKey, 30);
return new Result(true,"success",token);
}
}
gateway中 全局共享:
- 判断是否有token
- 获取公钥解析token,需要捕获具体异常(过期令牌,非法令牌,其他异常),解析没有报异常就将解析的用户信息(用于之后的服务操作)包装成一个新的request,之后放行
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import org.djh.entity.user.WxbMember;
import org.djh.entity.vo.Result;
import org.djh.utils.JsonUtils;
import org.djh.utils.JwtUtils;
import org.djh.utils.RsaUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.net.URI;
import java.security.PublicKey;
/**
* @Date:2021/5/25-05-25-14:31
* @version:1.0
**/
@Component
public class GlobalAuthFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpResponse response = exchange.getResponse();
ServerHttpRequest request = exchange.getRequest();
//放行资源
URI uri = request.getURI();
String[] whiteList = {"/user/member/login","/search/search","/search/init",
"/index/findContetByCid","/index/hot/goodsList","/pay/notify"};
System.out.println(uri.getPath());
for (String w : whiteList) {
if(uri.getPath().equals(w)){
return chain.filter(exchange);//放行
}
}
//判断请求头里面是否有token
String token = request.getHeaders().getFirst("token");
if (token == null) {
//不能放行,直接响应客户端
return response(response,new Result(false,"请登录","invalid token"));
}
//校验令牌
//加载公钥
PublicKey publicKey = null;
try {
publicKey = RsaUtils.getPublicKey( ResourceUtils.getFile("classpath:rsa.pub").getPath());
} catch (Exception e) {
e.printStackTrace();
}
//校验令牌
try {
WxbMember infoFromToken = (WxbMember) JwtUtils.getInfoFromToken(token, publicKey, WxbMember.class);
//传递用户信息【请求头】
ServerHttpRequest newRequest = request.mutate().header("token", JsonUtils.toString(infoFromToken)).build();
ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
//放行
return chain.filter(newExchange);
} catch (MalformedJwtException e) {
e.printStackTrace();
return response(response,new Result(false,"非法令牌","invalid token"));
}catch (ExpiredJwtException e){
return response(response,new Result(false,"令牌过期","invalid token"));
}catch (Exception e){
return response(response,new Result(false,"其他异常","invalid token"));
}
}
@Override
public int getOrder() {
return 0;
}
private Mono<Void> response(ServerHttpResponse response, Result res){
//不能放行,直接返回,返回json信息
response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
ObjectMapper objectMapper = new ObjectMapper();
String jsonStr = null;
try {
jsonStr = objectMapper.writeValueAsString(res);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
DataBuffer dataBuffer = response.bufferFactory().wrap(jsonStr.getBytes());
return response.writeWith(Flux.just(dataBuffer));//响应json数据
}
}