SpringBoot+Vue前后端分离集成JWT
源代码:https://github.com/AlanLee97/code-demos/tree/master/jwt
一、搭建SpringBoot项目
-
添加jwt依赖
<!-- ======BEGIN jwt ====== --> <dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>3.10.3</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> <!-- ======END jwt ====== -->
-
编码
目录结构
JwtConfigProperties.java
package top.alanlee.template.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 配置属性类
*/
@Component
@ConfigurationProperties(prefix = "jwt")
public class JwtConfigProperties{
private long expire;
private String secret;
public JwtConfigProperties() {
}
public JwtConfigProperties(long expire, String secret) {
this.expire = expire;
this.secret = secret;
}
public long getExpire() {
return expire;
}
public void setExpire(long expire) {
this.expire = expire;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
@Override
public String toString() {
return "JwtConfigProperties{" +
"expire=" + expire +
", secret='" + secret + '\'' +
'}';
}
}
JwtConfigProperties是自定义的配置类,创建了这个类之后就可以在application.yml添加配置了
# 自定义的jwt配置
jwt:
# 过期时间:2小时
expire: 7200000
# 密钥
secret: 6Dx8SIuaHXJYnpsG18SSpjPs50lZcT52
JWTUtil.java
package top.alanlee.template.util;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import top.alanlee.template.config.JwtConfigProperties;
import java.util.Date;
public class JWTUtil {
/**
* 校验token是否正确
* @param token 密钥
* @return 是否正确
*/
public static boolean verify(String token, JwtConfigProperties jwtConfigProperties) throws Exception {
try {
Algorithm algorithm = Algorithm.HMAC256(jwtConfigProperties.getSecret());
JWTVerifier verifier = JWT.require(algorithm).build();
DecodedJWT jwt = verifier.verify(token);
System.out.println(jwt);
return true;
}