一、token与cookie相比较的优势
1、支持跨域访问,将token置于请求头中,而cookie是不支持跨域访问的;
2、无状态化,服务端无需存储token,只需要验证token信息是否正确即可,而session需要在服务端存储,一般是通过cookie中的sessionID在服务端查找对应的session;
3、无需绑定到一个特殊的身份验证方案(传统的用户名密码登陆),只需要生成的token是符合我们预期设定的即可;
4、更适用于移动端(Android,iOS,小程序等等),像这种原生平台不支持cookie,比如说微信小程序,每一次请求都是一次会话,当然我们可以每次去手动为他添加cookie,详情请查看博主另一篇博客;
5、避免CSRF跨站伪造攻击,还是因为不依赖cookie;
二、基于JWT的token认证实现
JWT:JSON Web Token,其实token就是一段字符串,由三部分组成:Header,Payload,Signature
1.引入依赖
<!--JWT-->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.8.2</version>
</dependency>
2.设置秘钥与生存时间
//设置过期时间
private static final long EXPIRE_DATE = 30 * 60 * 100000;
//token秘钥
private static final String TOKEN_SECRET = "SmTicket";
3.加密Token代码
/**
* 加密Token
*
* @Author: RZH
* @Date: 2020/4/6 9:25
*/
public static String token(Integer userId) {
String token;
try {
//过期时间
Date date = new Date(System.currentTimeMillis() + EXPIRE_DATE);
//秘钥及加密算法
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
//设置头部信息
Map<String, Object> header = new HashMap<>();
header.put("typ", "JWT");
header.put("alg", "HS256");
//携带UserId信息,生成签名
token = JWT.create()
.withHeader(header)
.withClaim("userId", userId)
.withExpiresAt(date)
.sign(algorithm);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return token;
}
4.解密Token
/**
* JWT解密
*
* @Author: RZH
* @Date: 2020/4/6 9:30
*/
public static Integer decodeToken(final String token) {
Integer userId = null;
try {
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET))
.build();
DecodedJWT jwt = verifier.verify(token);
if (jwt != null) {
userId = Integer.valueOf(jwt.getClaim("userId").asInt());
}
} catch (JWTVerificationException exception) {
exception.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
return userId;
}
5.验证Token
/**
* 验证Token
*
* @Author: RZH
* @Date: 2020/4/5 19:35
*/
public static boolean verify(String token) {
try {
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
JWTVerifier verifier = JWT.require(algorithm).build();
verifier.verify(token);
return true;
} catch (Exception e) {
return false;
}
}
完事over