
1、支持跨域访问,将token置于请求头中,而cookie是不支持跨域访问的;
2、无状态化,服务端无需存储token,只需要验证token信息是否正确即可,而session需要在服务端存储,一般是通过cookie中的sessionID在服务端查找对应的session;
3、无需绑定到一个特殊的身份验证方案(传统的用户名密码登陆),只需要生成的token是符合我们预期设定的即可;
4、更适用于移动端(Android,iOS,小程序等等),像这种原生平台不支持cookie,比如说微信小程序,每一次请求都是一次会话,当然我们可以每次去手动为他添加cookie,详情请查看博主另一篇博客;
二、基于JWT的token认证实现5、避免CSRF跨站伪造攻击,还是因为不依赖cookie;
1.引入依赖JWT:JSON Web Token,其实token就是一段字符串,由三部分组成:Header,Payload,Signature
com.auth0
java-jwt
3.8.2
2.设置秘钥与生存时间
//设置过期时间 private static final long EXPIRE_DATE = 30 * 60 * 100000; //token秘钥 private static final String TOKEN_SECRET = "SmTicket";3.加密Token代码
public static String token(Integer userId) {
String token;
try {
//过期时间
Date date = new Date(System.currentTimeMillis() + EXPIRE_DATE);
//秘钥及加密算法
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
//设置头部信息
Map 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
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
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
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)