完成乐优商城前台授权中心

完成授权中心微服务,解决分布式单点登陆问题。
无状态登录原理
什么是有状态?
有状态服务,即服务端需要记录每次会话的客户端信息,从而识别客户端身份,根据用户身份进行请求的处理,典型的设计如tomcat中的session。
例如登录:用户登录后,我们把登录者的信息保存在服务端session中,并且给用户一个cookie值,记录对应的session。然后下次请求,用户携带cookie值来,我们就能识别到对应session,从而找到用户的信息。
缺点是什么?
- 服务端保存大量数据,增加服务端压力
- 服务端保存用户状态,无法进行水平扩展
- 客户端请求依赖服务端,多次请求必须访问同一台服务器
什么是无状态
微服务集群中的每个服务,对外提供的都是Rest风格的接口。而Rest风格的一个最重要的规范就是:服务的无状态性,即:
- 服务端不保存任何客户端请求者信息
- 客户端的每次请求必须具备自描述信息,通过这些信息识别客户端身份
带来的好处是什么呢?
- 客户端请求不依赖服务端的信息,任何多次请求不需要必须访问到同一台服务
- 服务端的集群和状态对客户端透明
- 服务端可以任意的迁移和伸缩
- 减小服务端存储压力
如何实现无状态
无状态登录的流程:
- 当客户端第一次请求服务时,服务端对用户进行信息认证(登录)
- 认证通过,将用户信息进行加密形成token,返回给客户端,作为登录凭证
- 以后每次请求,客户端都携带认证的token
- 服务端对token进行解密,判断是否有效。
流程图:

整个登录过程中,最关键的点是什么?
token的安全性
token是识别客户端身份的唯一标示,如果加密不够严密,被人伪造那就完蛋了。
采用何种方式加密才是安全可靠的呢?
我们将采用JWT + RSA非对称加密
JWT
简介
JWT,全称是Json Web Token, 是JSON风格轻量级的授权和身份认证规范,可实现无状态、分布式的Web应用授权;官网:https://jwt.io

GitHub上jwt的java客户端:https://github.com/jwtk/jjwt
数据格式
JWT包含三部分数据:
Header:头部,通常头部有两部分信息:
我们会对头部进行base64加密(可解密),得到第一部分数据
Payload:载荷,就是有效数据,一般包含下面信息:
- 用户身份信息(注意,这里因为采用base64加密,可解密,因此不要存放敏感信息)
- 注册声明:如token的签发时间,过期时间,签发人等
这部分也会采用base64加密,得到第二部分数据
Signature:签名,是整个数据的认证信息。一般根据前两步的数据,再加上服务的的密钥(secret)(不要泄漏,最好周期性更换),通过加密算法生成。用于验证整个数据完整和可靠性
生成的数据格式:

可以看到分为3段,每段就是上面的一部分数据
JWT交互流程
流程图:

步骤翻译:
- 1、用户登录
- 2、服务的认证,通过后根据secret生成token
- 3、将生成的token返回给浏览器
- 4、用户每次请求携带token
- 5、服务端利用公钥解读jwt签名,判断签名有效后,从Payload中获取用户信息
- 6、处理请求,返回响应结果
因为JWT签发的token中已经包含了用户的身份信息,并且每次请求都会携带,这样服务的就无需保存用户信息,甚至无需去数据库查询,完全符合了Rest的无状态规范。
非对称加密
加密技术是对信息进行编码和解码的技术,编码是把原来可读信息(又称明文)译成代码形式(又称密文),其逆过程就是解码(解密),加密技术的要点是加密算法,加密算法可以分为三类:
- 对称加密,如AES
- 基本原理:将明文分成N个组,然后使用密钥对各个组进行加密,形成各自的密文,最后把所有的分组密文进行合并,形成最终的密文。
- 优势:算法公开、计算量小、加密速度快、加密效率高
- 缺陷:双方都使用同样密钥,安全性得不到保证
- 非对称加密,如RSA
- 基本原理:同时生成两把密钥:私钥和公钥,私钥隐秘保存,公钥可以下发给信任客户端
- 私钥加密,持有私钥或公钥才可以解密
- 公钥加密,持有私钥才可解密
- 优点:安全,难以破解
- 缺点:算法比较耗时
- 不可逆加密,如MD5,SHA
- 基本原理:加密过程中不需要使用密钥,输入明文后由系统直接经过加密算法处理成密文,这种加密后的数据是无法被解密的,无法根据密文推算出明文。
RSA算法历史:
1977年,三位数学家Rivest、Shamir 和 Adleman 设计了一种算法,可以实现非对称加密。这种算法用他们三个人的名字缩写:RSA
结合Zuul的鉴权流程
我们逐步演进系统架构设计。需要注意的是:secret是签名的关键,因此一定要保密,我们放到鉴权中心保存,其它任何服务中都不能获取secret。
没有RSA加密时
在微服务架构中,我们可以把服务的鉴权操作放到网关中,将未通过鉴权的请求直接拦截,如图:

- 1、用户请求登录
- 2、Zuul将请求转发到授权中心,请求授权
- 3、授权中心校验完成,颁发JWT凭证
- 4、客户端请求其它功能,携带JWT
- 5、Zuul将jwt交给授权中心校验,通过后放行
- 6、用户请求到达微服务
- 7、微服务将jwt交给鉴权中心,鉴权同时解析用户信息
- 8、鉴权中心返回用户数据给微服务
- 9、微服务处理请求,返回响应
发现什么问题了?
每次鉴权都需要访问鉴权中心,系统间的网络请求频率过高,效率略差,鉴权中心的压力较大。
结合RSA的鉴权
直接看图:

- 我们首先利用RSA生成公钥和私钥。私钥保存在授权中心,公钥保存在Zuul和各个微服务
- 用户请求登录
- 授权中心校验,通过后用私钥对JWT进行签名加密
- 返回jwt给用户
- 用户携带JWT访问
- Zuul直接通过公钥解密JWT,进行验证,验证通过则放行
- 请求到达微服务,微服务直接用公钥解析JWT,获取用户信息,无需访问授权中心
授权中心
授权中心的主要职责:
- 用户鉴权:
- 接收用户的登录请求,通过用户中心的接口进行校验,通过后生成JWT
- 使用私钥生成JWT并返回
- 服务鉴权:微服务间的调用不经过Zuul,会有风险,需要鉴权中心进行认证
- 原理与用户鉴权类似,但逻辑稍微复杂一些(此处我们不做实现)
因为生成jwt,解析jwt这样的行为以后在其它微服务中也会用到,因此我们会抽取成工具。我们把鉴权中心进行聚合,一个工具module,一个提供服务的module。
微服务搭建
父工程
- GroupId:
com.leyou.auth
- ArtifactId:
ly-auth
ly-auth-common
- GroupId:
com.leyou.auth
- ArtifactId:
ly-auth-common
ly-auth-service
- GroupId:
com.leyou.auth
- ArtifactId:
ly-auth-service
pom.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| <?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>ly-auth</artifactId> <groupId>com.leyou.auth</groupId> <version>1.0.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion>
<groupId>com.leyou.auth</groupId> <artifactId>ly-auth-service</artifactId>
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.leyou.auth</groupId> <artifactId>ly-auth-common</artifactId> <version>${leyou.latest.version}</version> </dependency> <dependency> <groupId>com.leyou.common</groupId> <artifactId>ly-common</artifactId> <version>${leyou.latest.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> </dependencies>
</project>
|
启动类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| package com.leyou;
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication @EnableDiscoveryClient @EnableFeignClients public class AuthApplication { public static void main(String[] args) { SpringApplication.run(AuthApplication.class, args); } }
|
application.yml
1 2 3 4 5 6 7 8 9
| server: port: 8007 spring: application: name: auth-service eureka: client: service-url: defaultZone: http://127.0.0.1:9999/eureka
|
需要在网关微服务中配置auth-service
访问路径:auth-service: /auth/**
JWT工具类
依赖
在ly-auth-common
中引入依赖。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <dependencies> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.0</version> </dependency> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> </dependency> </dependencies>
|
entity.UserInfo
1 2 3 4 5 6 7 8 9 10 11 12 13
| package com.leyou.auth.entity;
import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor;
@Data @NoArgsConstructor @AllArgsConstructor public class UserInfo { private Long id; private String username; }
|
utils
RasUtils
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
| package com.leyou.auth.utils;
import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.security.*; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec;
public class RsaUtils {
public static PublicKey getPublicKey(String fileName) throws Exception { byte[] bytes = readFile(fileName); return getPublicKey(bytes); }
public static PrivateKey getPrivateKey(String fileName) throws Exception{ byte[] bytes = readFile(fileName); return getPrivateKey(bytes); }
public static PublicKey getPublicKey(byte[] bytes) throws Exception { X509EncodedKeySpec spec = new X509EncodedKeySpec(bytes); KeyFactory factory = KeyFactory.getInstance("RSA"); return factory.generatePublic(spec); }
public static PrivateKey getPrivateKey(byte[] bytes) throws Exception { PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytes); KeyFactory factory = KeyFactory.getInstance("RSA"); return factory.generatePrivate(spec); }
public static byte[] readFile(String fileName) throws IOException { return Files.readAllBytes(new File(fileName).toPath());
}
public static void generateKey(String publicKeyFilename, String privateKeyFilename, String secret) throws Exception { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); SecureRandom secureRandom = new SecureRandom(secret.getBytes()); keyPairGenerator.initialize(1024, secureRandom); KeyPair keyPair = keyPairGenerator.genKeyPair(); byte[] publicKeyBytes = keyPair.getPublic().getEncoded(); writeFile(publicKeyFilename, publicKeyBytes); byte[] privateKeyBytes = keyPair.getPrivate().getEncoded(); writeFile(privateKeyFilename, privateKeyBytes); }
public static void writeFile(String destPath, byte[] bytes) throws IOException { File dest = new File(destPath); if (!dest.exists()) { dest.createNewFile(); } Files.write(dest.toPath(), bytes); } }
|
ObjectUtils
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| package com.leyou.auth.utils;
import org.apache.commons.lang3.StringUtils;
public class ObjectUtils {
public static String toString(Object obj) { if (obj == null) { return null; } return obj.toString(); }
public static Long toLong(Object obj) { if (obj == null) { return 0L; } if (obj instanceof Double || obj instanceof Float) { return Long.valueOf(StringUtils.substringBefore(obj.toString(), ".")); } if (obj instanceof Number) { return Long.valueOf(obj.toString()); } if (obj instanceof String) { return Long.valueOf(obj.toString()); } else { return 0L; } }
public static Integer toInt(Object obj) { return toLong(obj).intValue(); } }
|
JwtUtils
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
| package com.leyou.auth.utils;
import com.leyou.auth.entity.UserInfo; 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;
public class JwtUtils {
public static String generateToken(UserInfo userInfo, PrivateKey privateKey, int expireMinutes) { return Jwts.builder() .claim(JwtConstants.JWT_KEY_ID, userInfo.getId()) .claim(JwtConstants.JWT_KEY_USER_NAME, userInfo.getUsername()) .setExpiration(DateTime.now().plusMinutes(expireMinutes).toDate()) .signWith(SignatureAlgorithm.RS256, privateKey) .compact(); }
public static String generateToken(UserInfo userInfo, byte[] privateKey, int expireMinutes) throws Exception { return Jwts.builder() .claim(JwtConstants.JWT_KEY_ID, userInfo.getId()) .claim(JwtConstants.JWT_KEY_USER_NAME, userInfo.getUsername()) .setExpiration(DateTime.now().plus(expireMinutes).toDate()) .signWith(SignatureAlgorithm.ES256, RsaUtils.getPrivateKey(privateKey)) .compact(); }
public static Jws<Claims> parseToken(PublicKey publicKey, String token) { return Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token); }
public static Jws<Claims> parseToken(byte[] publicKey, String token) throws Exception { return Jwts.parser().setSigningKey(RsaUtils.getPublicKey(publicKey)).parseClaimsJws(token); }
public static UserInfo getUserInfo(PublicKey publicKey, String token) { Jws<Claims> claimsJws = parseToken(publicKey, token); Claims body = claimsJws.getBody(); return new UserInfo( ObjectUtils.toLong(body.get(JwtConstants.JWT_KEY_ID)), ObjectUtils.toString(body.get(JwtConstants.JWT_KEY_USER_NAME)) ); }
public static UserInfo getUserInfo(byte[] publicKey, String token) throws Exception { Jws<Claims> claimsJws = parseToken(publicKey, token); Claims body = claimsJws.getBody(); return new UserInfo( ObjectUtils.toLong(body.get(JwtConstants.JWT_KEY_ID)), ObjectUtils.toString(body.get(JwtConstants.JWT_KEY_USER_NAME)) ); } }
|
JwtConstants
1 2 3 4 5 6 7 8 9
| package com.leyou.auth.utils;
public class JwtConstants { public static final String JWT_KEY_ID = "id"; public static final String JWT_KEY_USER_NAME = "username"; }
|
JWT工具类测试
准备工作
生成公钥和私钥
1 2 3 4 5 6 7 8 9
| /** * 生成公钥和私钥 * * @throws Exception */ @Test public void testRsa() throws Exception { RsaUtils.generateKey(pubKeyPath, priKeyPath, "imxushuai"); }
|
生成的公私钥如下:

生成token
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| private PublicKey publicKey; private PrivateKey privateKey;
@Before public void testGetRsa() throws Exception { publicKey = RsaUtils.getPublicKey(pubKeyPath); privateKey = RsaUtils.getPrivateKey(priKeyPath); }
@Test public void testGenerateToken() throws Exception { String token = JwtUtils.generateToken(new UserInfo(20L, "xushuai"), privateKey, 5); System.out.println("token = " + token); }
|
生成的token如下:
1
| eyJhbGciOiJSUzI1NiJ9.eyJpZCI6MjAsInVzZXJuYW1lIjoieHVzaHVhaSIsImV4cCI6MTU1ODk2NTMwOX0.RTOt2PrhteC4DOdaB2TGVBroHI5ZRg9YxyqRradjP6wak5vWvDXQPJOA9WtfqQAj6oIkG0CwKvmFt74d4LW8fETWTDKEBBik3_HF0vDX5vAZk4LTGM91nE0nOepRSBawTs_zwn0O_UKQwcw3ufLgeV3_Q4uoZDfqWsR4IsLrgDw
|
解析token
1 2 3 4 5 6 7 8 9 10 11 12
|
@Test public void testParseToken() { String token = "eyJhbGciOiJSUzI1NiJ9.eyJpZCI6MjAsInVzZXJuYW1lIjoieHVzaHVhaSIsImV4cCI6MTU1ODk2NTMwOX0.RTOt2PrhteC4DOdaB2TGVBroHI5ZRg9YxyqRradjP6wak5vWvDXQPJOA9WtfqQAj6oIkG0CwKvmFt74d4LW8fETWTDKEBBik3_HF0vDX5vAZk4LTGM91nE0nOepRSBawTs_zwn0O_UKQwcw3ufLgeV3_Q4uoZDfqWsR4IsLrgDw";
UserInfo user = JwtUtils.getUserInfo(publicKey, token); System.out.println("id: " + user.getId()); System.out.println("userName: " + user.getUsername()); }
|
方法中的token即是刚才生成的token,打印输出如下:

初始化公钥私钥
ly-auth-service新增配置
1 2 3 4 5 6
| ly: jwt: secret: https://www.imxushuai.com pubKeyPath: C:\\key\\rsa.pub priKeyPath: C:\\key\\rsa.pri expire: 30
|
JwtProperties
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| package com.leyou.auth.config;
import com.leyou.auth.utils.RsaUtils; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.context.properties.ConfigurationProperties;
import javax.annotation.PostConstruct; import java.nio.file.Paths; import java.security.PrivateKey; import java.security.PublicKey;
@Data @Slf4j @ConfigurationProperties("ly.jwt") public class JwtProperties {
private String secret; private String pubKeyPath; private String priKeyPath; private int expire;
private PublicKey publicKey; private PrivateKey privateKey;
@PostConstruct public void init() { try { checkPubAndPri(); publicKey = RsaUtils.getPublicKey(pubKeyPath); privateKey = RsaUtils.getPrivateKey(priKeyPath); } catch (Exception e) { log.error("初始化公钥私钥失败", e); throw new RuntimeException(); } }
private void checkPubAndPri() throws Exception { if (!Paths.get(pubKeyPath).toFile().exists() || !Paths.get(priKeyPath).toFile().exists()) { RsaUtils.generateKey(pubKeyPath, priKeyPath, secret); } }
}
|
授权API
准备工作
user-service开发api
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| package com.leyou.api;
import com.leyou.pojo.User; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam;
public interface UserApi {
@GetMapping("/query") User queryUserByUsernameAndPassword(@RequestParam("username") String username, @RequestParam("password") String password);
}
|
auth-service引入依赖
1 2 3 4 5
| <dependency> <groupId>com.leyou.service</groupId> <artifactId>ly-user-interface</artifactId> <version>${leyou.latest.version}</version> </dependency>
|
UserClient
1 2 3 4 5 6 7 8 9
| package com.leyou.auth.client;
import com.leyou.api.UserApi; import com.leyou.common.util.LeyouConstants; import org.springframework.cloud.openfeign.FeignClient;
@FeignClient(LeyouConstants.SERVICE_USER) public interface UserClient extends UserApi { }
|
准备工作完成,开始正式编写授权API。
AuthController
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| package com.leyou.auth.controller;
import com.leyou.auth.service.AuthService; import com.leyou.common.util.CookieUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
@RestController public class AuthController {
@Value("${ly.jwt.cookieName}") private String cookieName;
@Autowired private AuthService authService;
@PostMapping("login") public ResponseEntity<Void> login(@RequestParam("username") String username, @RequestParam("password") String password, HttpServletRequest request, HttpServletResponse response) { String token = authService.login(username, password); CookieUtils.setCookie(request, response, cookieName, token); return ResponseEntity.status(HttpStatus.OK).build(); } }
|
在application.yml
中新增配置:ly.jwt.cookieName=LY_TOKEN
。
AuthService
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| package com.leyou.auth.service;
import com.leyou.auth.client.UserClient; import com.leyou.auth.config.JwtProperties; import com.leyou.auth.entity.UserInfo; import com.leyou.auth.utils.JwtUtils; import com.leyou.common.enums.LyExceptionEnum; import com.leyou.common.exception.LyException; import com.leyou.pojo.User; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.stereotype.Service;
@Slf4j @Service @EnableConfigurationProperties(JwtProperties.class) public class AuthService {
@Autowired private JwtProperties properties;
@Autowired private UserClient userClient;
public String login(String username, String password) { User user; try { user = userClient.queryUserByUsernameAndPassword(username, password); } catch (Exception e) { log.info("[授权中心] 调用UserClient失败, 用户名=[{}]", username, e); throw new LyException(LyExceptionEnum.INVALID_USERNAME_OR_PASSWORD); } return JwtUtils.generateToken(new UserInfo(user.getId(), user.getUsername()), properties.getPrivateKey(), properties.getExpire()); } }
|
测试授权API

token写入cookie成功。
Cookie写入问题
解决host地址变化问题
这里的server name其实就是请求时的主机名:Host,之所以改变,有两个原因:
- 我们使用了
nginx
反向代理,当监听到api.leyou.com
的时候,会自动将请求转发至127.0.0.1:10001
,即ly-gateway
。
- 而后请求到达我们的网关Zuul,Zuul就会根据路径匹配,我们的请求是
/api/auth
,根据规则被转发到了 127.0.0.1:8087
,即我们的授权中心。
我们首先去更改nginx
配置,让它不要修改我们的host:proxy_set_header Host $host;

修改完毕后,重启nginx
。
修改ly-gateway
保留请求携带的header信息
1
| zuul.add-host-header=true
|
允许写入cookie
Zuul内部有默认的过滤器,会对请求和响应头信息进行重组,过滤掉敏感的头信息。通过一个属性为SensitiveHeaders
的属性,来获取敏感头列表,然后添加到IgnoredHeaders
中,这些头信息就会被忽略。IgnoredHeaders
的默认值如下:
1
| ["Cookie", "Set-Cookie", "Authorization"]
|
所以我们需要修改SensitiveHeaders
的值,通过配置该属性的值为空(null)即可,配置如下:
测试
使用页面进行登录,查看Cookie
:

写入Cookie成功。
校验用户已登录
我们在leyou-auth-service
中定义用户的校验接口,通过cookie获取token,然后校验通过返回用户信息。
- 请求方式:GET
- 请求路径:/verify
- 请求参数:无,不过我们需要从cookie中获取token信息
- 返回结果:UserInfo,校验成功返回用户信息;校验失败,则返回401
Controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
@GetMapping("verify") public ResponseEntity<UserInfo> login(@CookieValue("LY_TOKEN") String token) { if (StringUtils.isBlank(token)) { throw new LyException(LyExceptionEnum.UNAUTHORIZED); } try { UserInfo userInfo = JwtUtils.getUserInfo(properties.getPublicKey(), token); return ResponseEntity.ok(userInfo); } catch (Exception e) { throw new LyException(LyExceptionEnum.UNAUTHORIZED); } }
|
测试

登录成功,前台也拿到了用户信息。
token刷新
每当用户来查询其个人信息,就证明他正在浏览网页,此时刷新cookie是比较合适的时机。因此我们可以对刚刚的校验用户登录状态的接口进行改进,加入刷新token的逻辑。修改后如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
@GetMapping("verify") public ResponseEntity<UserInfo> login(@CookieValue("LY_TOKEN") String token, HttpServletRequest request, HttpServletResponse response) { if (StringUtils.isBlank(token)) { throw new LyException(LyExceptionEnum.UNAUTHORIZED); } try { UserInfo userInfo = JwtUtils.getUserInfo(properties.getPublicKey(), token);
token = JwtUtils.generateToken(userInfo, this.properties.getPrivateKey(), this.properties.getExpire()); CookieUtils.setCookie(request, response, cookieName, token);
return ResponseEntity.ok(userInfo); } catch (Exception e) { throw new LyException(LyExceptionEnum.UNAUTHORIZED); } }
|
网关登录拦截器
Zuul编写拦截器,对用户的token进行校验,如果发现未登录,则进行拦截。
准备工作(ly-gateway)
引入依赖
1 2 3 4 5 6 7 8 9 10
| <dependency> <groupId>com.leyou.common</groupId> <artifactId>ly-common</artifactId> <version>${leyou.latest.version}</version> </dependency> <dependency> <groupId>com.leyou.auth</groupId> <artifactId>ly-auth-common</artifactId> <version>${leyou.latest.version}</version> </dependency>
|
application.yml
1 2 3 4
| leyou: jwt: pubKeyPath: C:\\key\\rsa.pub cookieName: LY_TOKEN
|
JwtProperties
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| package com.leyou.config;
import com.leyou.auth.utils.RsaUtils; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.context.properties.ConfigurationProperties;
import javax.annotation.PostConstruct; import java.security.PublicKey;
@Data @Slf4j @ConfigurationProperties(prefix = "ly.jwt") public class JwtProperties {
private String pubKeyPath;
private PublicKey publicKey;
private String cookieName;
@PostConstruct public void init(){ try { this.publicKey = RsaUtils.getPublicKey(pubKeyPath); } catch (Exception e) { log.error("初始化公钥失败!", e); throw new RuntimeException(); } }
}
|
过滤器:LoginFilter
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| package com.leyou.filter;
import com.leyou.auth.utils.JwtUtils; import com.leyou.common.util.CookieUtils; import com.leyou.config.JwtProperties; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
@Component @EnableConfigurationProperties(JwtProperties.class) public class LoginFilter extends ZuulFilter {
@Autowired private JwtProperties properties;
@Override public String filterType() { return "pre"; }
@Override public int filterOrder() { return 5; }
@Override public boolean shouldFilter() { return true; }
@Override public Object run() { RequestContext context = RequestContext.getCurrentContext(); HttpServletRequest request = context.getRequest(); String token = CookieUtils.getCookieValue(request, properties.getCookieName()); try { JwtUtils.getUserInfo(properties.getPublicKey(), token); } catch (Exception e) { context.setSendZuulResponse(false); context.setResponseStatusCode(HttpStatus.FORBIDDEN.value()); } return null; } }
|
请求白名单
要注意,并不是所有的路径我们都需要拦截,例如:
- 登录校验接口:
/auth/**
- 注册接口:
/user/register
- 数据校验接口:
/user/check/**
- 发送验证码接口:
/user/code
- 搜索接口:
/search/**
另外,跟后台管理相关的接口,因为我们没有做登录和权限,因此暂时都放行,但是生产环境中要做登录校验:
所以,我们需要在拦截时,配置一个白名单,如果在名单内,则不进行拦截。
在application.yaml
中添加规则
1 2 3 4 5 6 7 8 9
| ly: filter: allowPaths: - /api/auth - /api/search - /api/user/register - /api/user/check - /api/user/code - /api/item
|
FilterProperties
1 2 3 4 5 6 7 8 9 10 11 12
| package com.leyou.config;
import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.List;
@Data @ConfigurationProperties(prefix = "ly.filter") public class FilterProperties { private List<String> allowPaths; }
|
重写LoginFilter#shouldFilter
方法,修改后的LoginFilter
如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| package com.leyou.filter;
import com.leyou.auth.utils.JwtUtils; import com.leyou.common.util.CookieUtils; import com.leyou.config.FilterProperties; import com.leyou.config.JwtProperties; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
@Component @EnableConfigurationProperties({JwtProperties.class, FilterProperties.class}) public class LoginFilter extends ZuulFilter {
@Autowired private JwtProperties jwtProperties;
@Autowired private FilterProperties filterProperties;
@Override public String filterType() { return "pre"; }
@Override public int filterOrder() { return 5; }
@Override public boolean shouldFilter() { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest req = ctx.getRequest(); String requestURI = req.getRequestURI(); return !isAllowPath(requestURI); }
private boolean isAllowPath(String requestURI) { boolean flag = false; for (String path : filterProperties.getAllowPaths()) { if(requestURI.startsWith(path)){ flag = true; break; } } return flag; }
@Override public Object run() { RequestContext context = RequestContext.getCurrentContext(); HttpServletRequest request = context.getRequest(); String token = CookieUtils.getCookieValue(request, jwtProperties.getCookieName()); try { JwtUtils.getUserInfo(jwtProperties.getPublicKey(), token); } catch (Exception e) { context.setSendZuulResponse(false); context.setResponseStatusCode(HttpStatus.FORBIDDEN.value()); } return null; } }
|
关于自定义Filter我的另一篇文章中有详细介绍:
文章链接:Spring Cloud Zuul自定义Filter