SpringSecirity(四)——用户退出

因为JWT是无状态的,去中心化的,在服务器端无法清除,服务器一旦进行颁发,就只能等待自动过期 才会失效,所以需要redis配合才能完成登录状态的记录。

实现思路: 登录后在redis中添加一个白名单,把认证成功的用户的JWT添加到redis中。

在退出的时候,服务清空springsecurit保存认证通过的Authentication对象,其次在redis中进行删除。

(1)改造登录接口

保存至redis时,加上截止时间。

(2)退出后台代码实现

java 复制代码
    /**
     * 用户退出
     */
    @PostMapping("/logout")
    public R logout(HttpServletRequest request, HttpServletResponse response) {
        //获取token
        String token = request.getParameter("Authorization");
        //如果没有从头部获取token,那么从参数里面获取
        if (ObjectUtils.isEmpty(token)) {
            token = request.getHeader("Authorization");
        }
        //获取用户相关信息
        Authentication authentication
                = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            //清空用户信息
            new SecurityContextLogoutHandler().logout(request, response,authentication);
            //清空redis里面的token
            String key = "token_" + token;
            stringRedisTemplate.delete(key);
        }
        return R.ok().message("用户退出成功");
    }
相关推荐
凌奕22 分钟前
我读了六个 Coding Agent 的上下文压缩源码,发现网上流传的数据一半是错的
github·agent·claude
一次旅行4 小时前
act本地预跑GitHub Actions:Python项目完整CI/CD流水线实战
python·ci/cd·github
敢敢是只喵i4 小时前
Agent 为什么需要 guidance,但不能把 guidance 当成安全策略?
github·aigc
不简说5 小时前
JS 代码技巧 vol.9 — 20 个设计模式在真实项目里的应用
前端·javascript·github
逛逛GitHub6 小时前
很多神级开源 Agent 从它演化而来:77K Star 的 Pi 太强了。
github
今夕资源网7 小时前
SayIt语音输入+AI 润色 Typeless 替代品 GitHub开源语音输入法,可本地部署LLM亦可接入deepseek 或者其他大模型。
人工智能·开源·github·输入法·开源输入法·语音输入法
chaors20 小时前
DeepResearchSystem 0x03:HITL
llm·github·ai编程
OpenTiny社区20 小时前
Loop Engineering:让 AI Agent 自己跑起来的工程方法
前端·github
木心术121 小时前
GitHub Actions自动化运维实战:从CI/CD到全链路DevOps
运维·自动化·github
炸膛坦客1 天前
Git 和 GitHub:(七)将本地新建仓库与 GitHub 远程仓库关联起来(SSH)
git·ssh·github