学于黑马和传智播客联合做的教学项目 感谢
微信搜索"艺术行者",关注并回复关键词"乐优商城"获取视频和教程资料!
1.无状态登陆
在服务器端保存session
无状态不需要session,把登陆状态保存在cookie中
2.jwt+rsa
token:登陆时,jwt oath2
jwt:头信息(jwt) 载荷(用户信息,签发人 签发时间 有效时间) 签名(头信息+载荷:通过加密算法生成。作用:校验前两部分内容的合法性)
3.zuul网关访问的流程
4.搭建授权中心
聚合工程:leyou-auth-common(jwt相关的工具类) leyou-auth-service(微服务)
5.jwtUtils
根据载荷还有私钥生成jwt类型的token
根据公钥解析jwt类型的token,获取载荷信息(userInfo)
rsaUtils(生成公钥和私钥文件,并且读取公钥和私钥文件返回公钥和私钥对象)
6.登陆功能
1.调用user-service中的queryUser接口,验证用户是否正确
2.判断返回的用户信息是否为空
3.生成jwt类型的token
4.token信息设置到cookie中
7.首页用户名回显
1.获取Cookie中jwt类型的token @CookieValue("LY_TOKEN")
2.jwtUtils解析jwt,获取用户信息
判断用户是否为空
3.刷新jwt时间 cookie时间
4.响应用户信息
8.在zuul网关添加过滤器
获取zuul的上下文对象
获取request
通过cookieutils获取token
解析token
白名单;
有状态服务,即服务端需要记录每次会话的客户端信息,从而识别客户端身份,根据用户身份进行请求的处理,典型的设计如tomcat中的session。
例如登录:用户登录后,我们把登录者的信息保存在服务端session中,并且给用户一个cookie值,记录对应的session。然后下次请求,用户携带cookie值来,我们就能识别到对应session,从而找到用户的信息。
缺点是什么?
微服务集群中的每个服务,对外提供的都是Rest风格的接口。而Rest风格的一个最重要的规范就是:服务的无状态性,即:
带来的好处是什么呢?
无状态登录的流程:
流程图:
整个登录过程中,最关键的点是什么?
token的安全性
token是识别客户端身份的唯一标示,如果加密不够严密,被人伪造那就完蛋了。
采用何种方式加密才是安全可靠的呢?
我们将采用JWT + RSA非对称加密
JWT,全称是Json Web Token, 是JSON风格轻量级的授权和身份认证规范,可实现无状态、分布式的Web应用授权;官网:https://jwt.io
GitHub上jwt的java客户端:https://github.com/jwtk/jjwt
JWT包含三部分数据:
Header:头部,通常头部有两部分信息:
我们会对头部进行base64编码,得到第一部分数据
Payload:载荷,就是有效数据,一般包含下面信息:
这部分也会采用base64编码,得到第二部分数据
Signature:签名,是整个数据的认证信息。一般根据前两步的数据,再加上服务的的密钥(secret)(不要泄漏,最好周期性更换),通过加密算法生成。用于验证整个数据完整和可靠性
可以看到分为3段,每段就是上面的一部分数据
流程图:
步骤翻译:
因为JWT签发的token中已经包含了用户的身份信息,并且每次请求都会携带,这样服务的就无需保存用户信息,甚至无需去数据库查询,完全符合了Rest的无状态规范。
加密技术是对信息进行编码和解码的技术,编码是把原来可读信息(又称明文)译成代码形式(又称密文),其逆过程就是解码(解密),加密技术的要点是加密算法,加密算法可以分为三类:
对称加密,如AES
非对称加密,如RSA
基本原理:同时生成两把密钥:私钥和公钥,私钥隐秘保存,公钥可以下发给信任客户端
优点:安全,难以破解
缺点:算法比较耗时
不可逆加密,如MD5,SHA
RSA算法历史:
1977年,三位数学家Rivest、Shamir 和 Adleman 设计了一种算法,可以实现非对称加密。这种算法用他们三个人的名字缩写:RSA
我们逐步演进系统架构设计。需要注意的是:secret是签名的关键,因此一定要保密,我们放到鉴权中心保存,其它任何服务中都不能获取secret。
在微服务架构中,我们可以把服务的鉴权操作放到网关中,将未通过鉴权的请求直接拦截,如图:
发现什么问题了?
每次鉴权都需要访问鉴权中心,系统间的网络请求频率过高,效率略差,鉴权中心的压力较大。
直接看图:
授权中心的主要职责:
用户鉴权:
服务鉴权:微服务间的调用不经过Zuul,会有风险,需要鉴权中心进行认证
因为生成jwt,解析jwt这样的行为以后在其它微服务中也会用到,因此我们会抽取成工具。我们把鉴权中心进行聚合,一个是工具module,另一个是提供服务的module。
我们先创建父module,名称为:leyou-auth
将pom打包方式改为pom:
<?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>leyou</artifactId>
<groupId>com.leyou.parent</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.leyou.auth</groupId>
<artifactId>leyou-auth</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>pom</packaging>
</project>
然后是授权服务的通用模块:leyou-auth-common:
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>leyou-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>leyou-auth-common</artifactId>
<version>1.0.0-SNAPSHOT</version>
</project>
结构:
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>leyou-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>leyou-auth-service</artifactId>
<version>1.0.0-SNAPSHOT</version>
<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>leyou-auth-common</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.leyou.common</groupId>
<artifactId>leyou-common</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
</project>
引导类:
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class LeyouAuthApplication {
public static void main(String[] args) {
SpringApplication.run(LeyouAuthApplication.class, args);
}
}
application.yml
server:
port: 8087
spring:
application:
name: auth-service
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
registry-fetch-interval-seconds: 10
instance:
lease-renewal-interval-in-seconds: 5 # 每隔5秒发送一次心跳
lease-expiration-duration-in-seconds: 10 # 10秒不发送就过期
结构:
在leyou-gateway工程的application.yml中,修改路由:
zuul:
prefix: /api # 路由路径前缀
routes:
item-service: /item/** # 商品微服务的映射路径
search-service: /search/** # 搜索微服务
user-service: /user/** # 用户微服务
auth-service: /auth/** # 授权中心微服务
创建实体类UserInfo:
public class UserInfo {
private Long id;
private String username;
public UserInfo() {
}
public UserInfo(Long id, String username) {
this.id = id;
this.username = username;
}
//getter/setter
}
我们在leyou-auth-common
中导入课前资料中的工具类:
需要在leyou-auth-common
中引入JWT依赖:
<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>
我们在leyou-auth-common
中编写测试类:
public class JwtTest {
private static final String pubKeyPath = "C:\\tmp\\rsa\\rsa.pub";
private static final String priKeyPath = "C:\\tmp\\rsa\\rsa.pri";
private PublicKey publicKey;
private PrivateKey privateKey;
@Test
public void testRsa() throws Exception {
RsaUtils.generateKey(pubKeyPath, priKeyPath, "234");
}
@Before
public void testGetRsa() throws Exception {
this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
this.privateKey = RsaUtils.getPrivateKey(priKeyPath);
}
@Test
public void testGenerateToken() throws Exception {
// 生成token
String token = JwtUtils.generateToken(new UserInfo(20L, "jack"), privateKey, 5);
System.out.println("token = " + token);
}
@Test
public void testParseToken() throws Exception {
String token = "eyJhbGciOiJSUzI1NiJ9.eyJpZCI6MjAsInVzZXJuYW1lIjoiamFjayIsImV4cCI6MTUzMzI4MjQ3N30.EPo35Vyg1IwZAtXvAx2TCWuOPnRwPclRNAM4ody5CHk8RF55wdfKKJxjeGh4H3zgruRed9mEOQzWy79iF1nGAnvbkraGlD6iM-9zDW8M1G9if4MX579Mv1x57lFewzEo-zKnPdFJgGlAPtNWDPv4iKvbKOk1-U7NUtRmMsF1Wcg";
// 解析token
UserInfo user = JwtUtils.getInfoFromToken(token, publicKey);
System.out.println("id: " + user.getId());
System.out.println("userName: " + user.getUsername());
}
}
测试生成公钥和私钥,我们运行这段代码:注意需要把@Before方法注释掉
运行之后,查看目标目录:
公钥和私钥已经生成了!
测试生成token,把@Before的注释去掉的:
测试解析token:
正常情况:
任意改动token,发现报错了:
接下来,我们需要在leyou-auth-servcice
编写一个接口,对外提供登录授权服务。基本流程如下:
我们需要在授权中心生成真正的公钥和私钥。我们必须有一个生成公钥和私钥的secret,这个可以配置到application.yml
中:
leyou:
jwt:
secret: leyou@Login(Auth}*^31)&heiMa% # 登录校验的密钥
pubKeyPath: C:\\tmp\\rsa\\rsa.pub # 公钥地址
priKeyPath: C:\\tmp\\rsa\\rsa.pri # 私钥地址
expire: 30 # 过期时间,单位分钟
然后编写属性类,加载这些数据:
@ConfigurationProperties(prefix = "leyou.jwt")
public class JwtProperties {
private String secret; // 密钥
private String pubKeyPath;// 公钥
private String priKeyPath;// 私钥
private int expire;// token过期时间
private PublicKey publicKey; // 公钥
private PrivateKey privateKey; // 私钥
private static final Logger logger = LoggerFactory.getLogger(JwtProperties.class);
/**
* @PostContruct:在构造方法执行之后执行该方法
*/
@PostConstruct
public void init(){
try {
File pubKey = new File(pubKeyPath);
File priKey = new File(priKeyPath);
if (!pubKey.exists() || !priKey.exists()) {
// 生成公钥和私钥
RsaUtils.generateKey(pubKeyPath, priKeyPath, secret);
}
// 获取公钥和私钥
this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
this.privateKey = RsaUtils.getPrivateKey(priKeyPath);
} catch (Exception e) {
logger.error("初始化公钥和私钥失败!", e);
throw new RuntimeException();
}
}
// getter setter ...
}
编写授权接口,我们接收用户名和密码,校验成功后,写入cookie中。
代码:
@RestController
@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {
@Autowired
private AuthService authService;
@Autowired
private JwtProperties prop;
/**
* 登录授权
*
* @param username
* @param password
* @return
*/
@PostMapping("accredit")
public ResponseEntity<Void> authentication(
@RequestParam("username") String username,
@RequestParam("password") String password,
HttpServletRequest request,
HttpServletResponse response) {
// 登录校验
String token = this.authService.authentication(username, password);
if (StringUtils.isBlank(token)) {
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
// 将token写入cookie,并指定httpOnly为true,防止通过JS获取和修改
CookieUtils.setCookie(request, response, prop.getCookieName(),
token, prop.getCookieMaxAge(), null, true);
return ResponseEntity.ok().build();
}
}
这里的cookie的name和生存时间,我们配置到属性文件:application.yml:
然后在JwtProperties
中添加属性:
要注意,这里我们使用了一个工具类,CookieUtils,可以在课前资料中找到,我们把它添加到leyou-common
中,然后引入servlet相关依赖即可:
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
</dependency>
代码:略
接下来我们肯定要对用户密码进行校验,所以我们需要通过FeignClient去访问 user-service微服务:
在leyou-auth中引入user-service-interface依赖:
<dependency>
<groupId>com.leyou.user</groupId>
<artifactId>leyou-user-interface</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
参照leyou-search或者leyou-goods-web,在leyou-auth-service中编写FeignClient:
@FeignClient(value = "user-service")
public interface UserClient extends UserApi {
}
在leyou-user-interface工程中添加api接口:
内容:
public interface UserApi {
@GetMapping("query")
public User queryUser(
@RequestParam("username") String username,
@RequestParam("password") String password);
}
这个接口上边原来有@RequestMapping("user")注解,但是user模块的controller并没有这个注解,要加都加,要不加都不加,因为controller还有很多方法是不带这个user路径的,所以去掉这个路径,以后要注意哦!
在leyou-auth-service:
@Service
public class AuthService {
@Autowired
private UserClient userClient;
@Autowired
private JwtProperties properties;
public String authentication(String username, String password) {
try {
// 调用微服务,执行查询
User user = this.userClient.queryUser(username, password);
// 如果查询结果为null,则直接返回null
if (user == null) {
return null;
}
// 如果有查询结果,则生成token
String token = JwtUtils.generateToken(new UserInfo(user.getId(), user.getUsername()),
properties.getPrivateKey(), properties.getExpire());
return token;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
接下来,我们看看登录页面,是否能够正确的发出请求。
我们在页面输入登录信息,然后点击登录:
查看控制台:
发现请求的路径不对,我们的认证接口是:
/api/auth/accredit
我们打开login.html,修改路径信息:
页面ajax请求:
然后再次测试,成功跳转到了首页:
接下来我们查看首页cookie:
什么都没有,为什么?
我们在之前测试时,清晰的看到了响应头中,有Set-Cookie属性,为什么在这里却什么都没有?
我们之前在讲cors跨域时,讲到过跨域请求cookie生效的条件:
看看我们的服务端cors配置:
没有任何问题。
再看客户端浏览器的ajax配置,我们在js/common.js
中对axios进行了统一配置:
一切OK。
那说明,问题一定出在响应的set-cookie头中。我们再次仔细看看刚才的响应头:
我们发现cookie的 domain
属性似乎不太对。
cookie也是有域
的限制,一个网页,只能操作当前域名下的cookie,但是现在我们看到的地址是0.0.1,而页面是www.leyou.com,域名不匹配,cookie设置肯定失败了!
我们去Debug跟踪CookieUtils,看看到底是怎么回事:
我们发现内部有一个方法,用来获取Domain:
它获取domain是通过服务器的host来计算的,然而我们的地址竟然是:127.0.0.1:8087,因此后续的运算,最终得到的domain就变成了:
问题找到了:我们请求时的serverName明明是:api.leyou.com,现在却被变成了:127.0.0.1,因此计算domain是错误的,从而导致cookie设置失败!
那么问题来了:为什么我们这里的请求serverName变成了:127.0.0.1:8087呢?
这里的server name其实就是请求的时的主机名:Host,之所以改变,有两个原因:
我们首先去更改nginx配置,让它不要修改我们的host:proxy_set_header Host $host;
把nginx进行reload:
nginx -s reload
这样就解决了nginx这里的问题。但是Zuul还会有一次转发,所以要去修改网关的配置(leyou-gateway工程):
重启后,我们再次测试。
最后计算得到的domain:
完美!
我们再次登录,发现依然没有cookie!!
怎么回事呢?
我们通过RestClient访问下看看:
发现,响应头中还是没有set-cookie
。
这是怎么回事??
Zuul内部有默认的过滤器,会对请求和响应头信息进行重组,过滤掉敏感的头信息:
会发现,这里会通过一个属性为SensitiveHeaders
的属性,来获取敏感头列表,然后添加到IgnoredHeaders
中,这些头信息就会被忽略。
而这个SensitiveHeaders
的默认值就包含了set-cookie
:
解决方案有两种:
全局设置:
zuul.sensitive-headers=
指定路由设置:
zuul.routes.<routeName>.sensitive-headers=
zuul.routes.<routeName>.custom-sensitive-headers=true
思路都是把敏感头设置为null
再次重启后测试:
虽然cookie已经成功写入,但是我们首页的顶部,登录状态依然没能判断出用户信息:
这里需要向后台发起请求,获取根据cookie获取当前用户的信息。
我们先看页面实现
页面的顶部已经被我们封装为一个独立的Vue组件,在/js/pages/shortcut.js
中
打开js,发现里面已经定义好了Vue组件,并且在created函数中,查询用户信息:
查看网络控制台,发现发起了请求:
因为token在cookie中,因此本次请求肯定会携带token信息在头中。
我们在leyou-auth-service
中定义用户的校验接口,通过cookie获取token,然后校验通过返回用户信息。
代码:
/**
* 验证用户信息
* @param token
* @return
*/
@GetMapping("verify")
public ResponseEntity<UserInfo> verifyUser(@CookieValue("LY_TOKEN")String token){
try {
// 从token中解析token信息
UserInfo userInfo = JwtUtils.getInfoFromToken(token, this.prop.getPublicKey());
// 解析成功返回用户信息
return ResponseEntity.ok(userInfo);
} catch (Exception e) {
e.printStackTrace();
}
// 出现异常则,响应500
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
页面效果:
每当用户在页面进行新的操作,都应该刷新token的过期时间,否则30分钟后用户的登录信息就无效了。而刷新其实就是重新生成一份token,然后写入cookie即可。
那么问题来了:我们怎么知道用户有操作呢?
事实上,每当用户来查询其个人信息,就证明他正在浏览网页,此时刷新cookie是比较合适的时机。因此我们可以对刚刚的校验用户登录状态的接口进行改进,加入刷新token的逻辑。
/**
* 验证用户信息
* @param token
* @return
*/
@GetMapping("verify")
public ResponseEntity<UserInfo> verifyUser(@CookieValue("LY_TOKEN")String token, HttpServletRequest request, HttpServletResponse response){
try {
// 从token中解析token信息
UserInfo userInfo = JwtUtils.getInfoFromToken(token, this.prop.getPublicKey());
// 解析成功要重新刷新token
token = JwtUtils.generateToken(userInfo, this.prop.getPrivateKey(), this.prop.getExpire());
// 更新cookie中的token
CookieUtils.setCookie(request, response, this.prop.getCookieName(), token, this.prop.getCookieMaxAge()*60);
// 解析成功返回用户信息
return ResponseEntity.ok(userInfo);
} catch (Exception e) {
e.printStackTrace();
}
// 出现异常则,响应500
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
接下来,我们在Zuul编写拦截器,对用户的token进行校验,如果发现未登录,则进行拦截。
既然是登录拦截,一定是前置拦截器,我们在leyou-gateway
中定义。
首先在pom.xml中,引入所需要的依赖:
<dependency>
<groupId>com.leyou.common</groupId>
<artifactId>leyou-common</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.leyou.auth</groupId>
<artifactId>leyou-auth-common</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
然后编写application.yml属性文件,添加如下内容:
leyou:
jwt:
pubKeyPath: C:\\tmp\\rsa\\rsa.pub # 公钥地址
cookieName: LY_TOKEN # cookie的名称
编写属性类,读取公钥:
@ConfigurationProperties(prefix = "leyou.jwt")
public class JwtProperties {
private String pubKeyPath;// 公钥
private PublicKey publicKey; // 公钥
private String cookieName;
private static final Logger logger = LoggerFactory.getLogger(JwtProperties.class);
@PostConstruct
public void init(){
try {
// 获取公钥和私钥
this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
} catch (Exception e) {
logger.error("初始化公钥失败!", e);
throw new RuntimeException();
}
}
public String getPubKeyPath() {
return pubKeyPath;
}
public void setPubKeyPath(String pubKeyPath) {
this.pubKeyPath = pubKeyPath;
}
public PublicKey getPublicKey() {
return publicKey;
}
public void setPublicKey(PublicKey publicKey) {
this.publicKey = publicKey;
}
public String getCookieName() {
return cookieName;
}
public void setCookieName(String cookieName) {
this.cookieName = cookieName;
}
}
基本逻辑:
@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() throws ZuulException {
// 获取上下文
RequestContext context = RequestContext.getCurrentContext();
// 获取request
HttpServletRequest request = context.getRequest();
// 获取token
String token = CookieUtils.getCookieValue(request, this.properties.getCookieName());
// 校验
try {
// 校验通过什么都不做,即放行
JwtUtils.getInfoFromToken(token, this.properties.getPublicKey());
} catch (Exception e) {
// 校验出现异常,返回403
context.setSendZuulResponse(false);
context.setResponseStatusCode(HttpStatus.FORBIDDEN.value());
}
return null;
}
}
重启,刷新页面,发现请求校验的接口也被拦截了:
证明我们的拦截器生效了,但是,似乎有什么不对的。这个路径似乎不应该被拦截啊!
要注意,并不是所有的路径我们都需要拦截,例如:
/auth/**
/user/register
/user/check/**
/user/code
/search/**
另外,跟后台管理相关的接口,因为我们没有做登录和权限,因此暂时都放行,但是生产环境中要做登录校验:
/item/**
所以,我们需要在拦截时,配置一个白名单,如果在名单内,则不进行拦截。
在application.yaml
中添加规则:
leyou:
filter:
allowPaths:
- /api/auth
- /api/search
- /api/user/register
- /api/user/check
- /api/user/code
- /api/item
然后读取这些属性:
内容:
@ConfigurationProperties(prefix = "leyou.filter")
public class FilterProperties {
private List<String> allowPaths;
public List<String> getAllowPaths() {
return allowPaths;
}
public void setAllowPaths(List<String> allowPaths) {
this.allowPaths = allowPaths;
}
}
在过滤器中的shouldFilter
方法中添加判断逻辑
代码:
@Component
@EnableConfigurationProperties({JwtProperties.class, FilterProperties.class})
public class LoginFilter extends ZuulFilter {
@Autowired
private JwtProperties jwtProp;
@Autowired
private FilterProperties filterProp;
private static final Logger logger = LoggerFactory.getLogger(LoginFilter.class);
@Override
public String filterType() {
return "pre";
}
@Override
public int filterOrder() {
return 5;
}
@Override
public boolean shouldFilter() {
// 获取上下文
RequestContext ctx = RequestContext.getCurrentContext();
// 获取request
HttpServletRequest req = ctx.getRequest();
// 获取路径
String requestURI = req.getRequestURI();
// 判断白名单
// 遍历允许访问的路径
for (String path : this.filterProp.getAllowPaths()) {
// 然后判断是否是符合
if(requestURI.startsWith(path)){
return false;
}
}
return true;
}
@Override
public Object run() throws ZuulException {
// 获取上下文
RequestContext ctx = RequestContext.getCurrentContext();
// 获取request
HttpServletRequest request = ctx.getRequest();
// 获取token
String token = CookieUtils.getCookieValue(request, jwtProp.getCookieName());
// 校验
try {
// 校验通过什么都不做,即放行
JwtUtils.getInfoFromToken(token, jwtProp.getPublicKey());
} catch (Exception e) {
// 校验出现异常,返回403
ctx.setSendZuulResponse(false);
ctx.setResponseStatusCode(403);
logger.error("非法访问,未登录,地址:{}", request.getRemoteHost(), e );
}
return null;
}
}
再次测试:
手机扫一扫
移动阅读更方便
你可能感兴趣的文章