使用cookie实现自动登录功能

1、自动登录流程:
在这里插入图片描述

2、代码实现
这里用户名和密码使用的是Base64加密,这种方式是不安全的,可以解码。
① 操作cookie的工具类 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;
    }

② 控制器中的登录方法

@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);
}

③ 控制器中登出方法

@PostMapping("/logout")
public RequestResult logout(HttpServletRequest request, HttpServletResponse response) {
    CookieHelper.delete(request, response);
    return RequestResult.success();
}
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值