cookie中添加token消除cookie被修改的安全隐患

本文介绍了一种基于MD5加密的用户登录验证机制,通过在用户登录成功后设置包含userId、时间戳及加密后的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));

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值