如何通过cookie退出登录(使用cookie实现自动登录功能)
如何通过cookie退出登录(使用cookie实现自动登录功能)译文:在追寻真理方面,前方的道路还很漫长,但我将百折不挠,不遗余力地去追求和探索。@PostMapping("/logout") public RequestResult logout(HttpServletRequest request HttpServletResponse response) { CookieHelper.delete(request response); return RequestResult.success(); }路漫漫其修远兮,吾将上下而求索CookieHelper.javapublic class cookieHelper { public static void set(StaffDTO dto HttpServletResponse response) { String loginName
一、自动登录流程
二、代码实现
1、操作cookie的工具类
这里用户名和密码使用的是Base64加密,这种方式是不安全的,可以解码。
CookieHelper.java
public class cookieHelper {
public static void set(StaffDTO dto HttpServletResponse response) {
String loginName = Base64.getEncoder().encodeToString(dto.getLoginName().getBytes());
String loginPassword = Base64.getEncoder().encodeToString(dto.getLoginPassword().getBytes());
Cookie cookie = new Cookie("login_staff" loginName "#" loginPassword);
cookie.setMaxAge(60*60*24*365);
response.addCookie(cookie);
}
public static Map<String String> get(HttpServletRequest request) {
Map<String String> map = new HashMap<>();
Cookie[] cookies = request.getCookies();
if (cookies == null)
return null;
for (Cookie cookie: cookies) {
if ("login_staff".equals(cookie.getName()))
map = getLoginparams(cookie);
}
return map;
}
public static void delete(HttpServletRequest request HttpServletResponse response) {
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies) {
cookie.setMaxAge(0);
response.addCookie(cookie);
}
}
private static Map<String String> getLoginParams(Cookie cookie) {
Map<String String> map = new HashMap<>();
String[] params = cookie.getValue().split("#");
String loginName = new String(Base64.getdecoder().decode(params[0]) StandardCharsets.UTF_8);
String loginPassword = new String(Base64.getDecoder().decode(params[1]) StandardCharsets.UTF_8);
map.put("loginName" loginName);
map.put("loginPassword" loginPassword);
return map;
}
2、控制器中的登录方法
@PostMapping("/login")
public RequestResult login(@RequestParam Map<String String> map HttpServletResponse response) {
StaffDTO staff = staffService.getByAccount(map.get("loginName") map.get("loginPassword"));
if (staff == null)
return RequestResult.fail();
else if (staff.getEnabled() == 0)
return RequestResult.fail("当前账户已被禁用");
if (Boolean.parseBoolean(map.get("autoLogin")))
CookieHelper.set(staff response);
return RequestResult.success(staff);
}
3、控制器中的登出方法
@PostMapping("/logout")
public RequestResult logout(HttpServletRequest request HttpServletResponse response) {
CookieHelper.delete(request response);
return RequestResult.success();
}
路漫漫其修远兮,吾将上下而求索
译文:在追寻真理方面,前方的道路还很漫长,但我将百折不挠,不遗余力地去追求和探索。
如果您有什么好的想法与方法,欢迎在评论区留言,我们一起讨论~