1、首先引入jjwt的依赖
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
2、编写生成token的工具类
package com.jjw.result.util;
import com.jjw.result.constants.SystemConstants;
import io.jsonwebtoken.*;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.*;
public class AppJwtUtil {
// TOKEN的有效期一天(S)
private static final int TOKEN_TIME_OUT = 3600;
// 加密KEY
private static final String TOKEN_ENCRY_KEY = "MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY";
// 最小刷新间隔(S)
private static final int REFRESH_TIME = 300;
// 生产ID
public static String createToken(Long id) {
Map<String, Object> claimMaps = new HashMap<>();
claimMaps.put("id", id);
long currentTime = System.currentTimeMillis();
return Jwts.builder()
.setId(UUID.randomUUID().toString())
.setIssuedAt(new Date(currentTime)) //签发时间
.setSubject("system") //说明
.setIssuer("jjw") //签发者信息
.setAudience("app") //接收用户
.compressWith(CompressionCodecs.GZIP) //数据压缩方式
.signWith(SignatureAlgorithm.HS512, generalKey()) //加密方式
//过期一个小时
.setExpiration(new Date(currentTime + TOKEN_TIME_OUT * 1000)) //过期时间戳
.addClaims(claimMaps) //cla信息
.compact();
}
/**
* 获取token中的claims信息
*
* @param token
* @return
*/
private static Jws<Claims> getJws(String token) {
return Jwts.parser()
.setSigningKey(generalKey())
.parseClaimsJws(token);
}
/**
* 获取payload body信息
*
* @param token
* @return
*/
public static Claims getClaimsBody(String token) {
try {
return getJws(token).getBody();
} catch (ExpiredJwtException e) {
return null;
}
}
/**
* 获取hearder body信息
*
* @param token
* @return
*/
public static JwsHeader getHeaderBody(String token) {
return getJws(token).getHeader();
}
/**
* 是否过期
*
* @param token
* @return 1 有效 0 无效 2 已过期
*/
public static Integer verifyToken(String token) {
try {
Claims claims = AppJwtUtil.getClaimsBody(token);
if (claims == null) {
return SystemConstants.JWT_FAIL;
}
return SystemConstants.JWT_OK;
} catch (ExpiredJwtException ex) {
return SystemConstants.JWT_EXPIRE;
} catch (Exception e) {
return SystemConstants.JWT_FAIL;
}
}
/**
* 由字符串生成加密key
*
* @return
*/
public static SecretKey generalKey() {
byte[] encodedKey = Base64.getEncoder().encode(TOKEN_ENCRY_KEY.getBytes());
SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
return key;
}
public static void main(String[] args) {
/* Map map = new HashMap();
map.put("id","11");*/
String token = AppJwtUtil.createToken(1102L);
System.out.println(token);
Claims claims = AppJwtUtil.getClaimsBody(token);
//Integer integer = AppJwtUtil.verifyToken("dsafafsa");
Integer integer = AppJwtUtil.verifyToken("eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAAC2LywrDIBAA_2XP8aCrZs3frI-CQkFYQ1tK_z0b6G2GYb4wVocDMNuMXMhQfKDxJQXDuEcTk68tuFooBNig84LDRiJHO2HaQM6st3xktefdRVTHeCnzWZV5TuX2nv8vWX9_XZv7Xf0W2Rt-AAAA.srh9GIXr4ZqpXNfFb6vGIUxT12ve6Tu6xQ2KmdySsziP6AeCgP1h2GBhhx1g4rNbdsLozNI_WA-2FKsoR6-yPg");
System.out.println(integer);
System.out.println(claims);
}
}
3、使用到的常量类:
package com.jjw.result.constants;
public class SystemConstants {
//JWT TOKEN已过期
public static final Integer JWT_EXPIRE = 2;
//JWT TOKEN有效
public static final Integer JWT_OK = 1;
//JWT TOKEN无效
public static final Integer JWT_FAIL = 0;
public static final String USER_HEADER_NAME = "userId";
public static final Integer TYPE_USER = 1; // 用户
public static final Integer TYPE_E = 0; // 设备
}
4、在service的实现类中调用,生成token返回给前端
//4.生成令牌返回给前端
String token = AppJwtUtil.createToken(Long.valueOf(adUserFromDb.getId()));
Map<String, Object> info = new HashMap<>();
info.put("token",token);
5、在网关上进行校验,因此需要搭建网关服务。首先引人依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>com.jjw</groupId>
<artifactId>result-content</artifactId>
<version>1.0-SNAPSHOT</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</exclusion>
<!--要排除spring-boot-starter-web这个依赖,但是result-content中包含的swagger-content这个
依赖又依赖于spring-boot-starter-web,而我只需要result-content中的内容,所以将这两个依赖都排除了-->
<exclusion>
<groupId>com.jjw</groupId>
<artifactId>swagger-content</artifactId>
</exclusion>
</exclusions>
</dependency>
6、启动类代码如下:
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayAdminApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayAdminApplication.class,args);
}
}
7、配置application.yml文件
spring:
profiles:
active: dev
---
server:
port: 6001
spring:
application:
name: leadnews-admin-gateway
profiles: dev
cloud:
nacos:
server-addr: 192.168.211.136:8848
discovery:
server-addr: ${spring.cloud.nacos.server-addr}
gateway:
globalcors:
add-to-simple-url-handler-mapping: true #增加
cors-configurations:
'[/**]': # 匹配所有请求
allowedOrigins: "*" #跨域处理 允许所有的域
allowedHeaders: "*"
allowedMethods: # 支持的方法
- GET
- POST
- PUT
- DELETE
allowCredentials: true # 是否允许携带cookie
maxAge: 360000 # 这次跨域检测的有效期
routes:
# 平台管理
- id: admin
uri: lb://leadnews-admin
predicates:
- Path=/admin/**
filters:
- StripPrefix= 1
8、添加网关模块、结构如下:
9、编写校验token的AuthorizeFilter类(全局过滤器),其内容如下:
package com.jjw.gatewayadmin.filter;
import com.jjw.result.constants.SystemConstants;
import com.jjw.result.util.AppJwtUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//+ 1.先获取请求和响应对象
ServerHttpRequest request = exchange.getRequest();
ServerHttpResponse response = exchange.getResponse();
// /get /a post /a
//+ 2.判断当前的请求 是否 是登录的请求 如果是 ,则放行
String path = request.getURI().getPath();
if(path.equals("/admin/admin/login")){
return chain.filter(exchange);
}
//+ 3.获取页面传递过来的请求头中的令牌数据 如果获取不到 返回错误(401)
String token = request.getHeaders().getFirst("token");
if(StringUtils.isEmpty(token)){
response.setStatusCode(HttpStatus.UNAUTHORIZED);
return response.setComplete();//完成响应 返回 后面就不执行了
}
//+ 4.校验令牌 校验失败 返回错误401
//通过jwt 来校验
if(SystemConstants.JWT_OK!= AppJwtUtil.verifyToken(token)){
response.setStatusCode(HttpStatus.UNAUTHORIZED);
return response.setComplete();//完成响应 返回 后面就不执行了
}
//+ 5.校验成功 放行
return chain.filter(exchange);
}
//过滤器的执行的优先级的设置 值越低 优先级越高
@Override
public int getOrder() {
return 0;
}
}