cookie中添加token消除cookie被修改的安全隐患
1) 用户登陆成功后,向response中 添加三个Cookie, 分别是userId,time,token, 其中token是 由前两个字段通过md5加 密得到的。
用户登陆成功后需要向response中 写cookie, 具体代码如下:
public void login(String userId, HttpServletResponse response) {
String _time = String.valueOf(System.currentTimeMillis());
Cookie userId= new Cookie("userId", userId);
Cookie time = new Cookie("cookieTime", String.valueOf(_time));
Cookie token = new Cookie("cookieToken", token(userId, _time));
userId.setPath("/");
time.setPath("/");
token.setPath("/");
userId.setMaxAge(timeout);
time.setMaxAge(timeout);
token.setMaxAge(timeout);
response.addCookie(userId);
response.addCookie(time);
response.addCookie(token);
}
private String token(String id, String time) {
return Hashing.md5().hashString(id + "_" + time, Charsets.UTF_8).toString();
}
2) 验证时只需要取 出userId, time, token三 者对应的cookie, 判断前两者通过相同的md5加 密后和token是 否相等,如果相等证明验证通过,如果不等,验证不通过。代码如下:
public boolean isLogin(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if (cookies == null) {
return false;
}
String userId= null;
String time = null;
String token = null;
for (Cookie cookie : cookies) {
String name = cookie.getName();
if (cookieId.equals(name)) {
id = cookie.getValue();
} else if (cookieTime.equals(name)) {
time = cookie.getValue();
} else if (cookieToken.equals(name)) {
token = cookie.getValue();
}
}
if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(time) || StringUtils.isEmpty(token)) {
return false;
}
return token.equals(token(userId, time));
}
- 上一篇: HTTP客户端识别与Cookie机制
- 下一篇: 使用Cookie并使用MD5算法实现用户永久登录