• 使用 Spring Security 手动验证用户


    1。概述

    在这篇快速文章中,我们将重点介绍如何在 Spring Security 和 Spring MVC 中手动验证用户的身份。

    2。Spring Security

    简单地说,Spring Security 将每个经过身份验证的用户的主体信息保存在 ThreadLocal 中——表示为 Authentication 对象。

    为了构造和设置这个 Authentication 对象——我们需要使用 Spring Security 通常用来在标准身份验证上构建对象的相同方法。

    为此,让我们手动触发身份验证,然后将生成的 Authentication 对象设置为框架用来保存当前登录用户的当前 SecurityContext

    UsernamePasswordAuthenticationToken authReq = new UsernamePasswordAuthenticationToken(user, pass);
    Authentication auth = authManager.authenticate(authReq);
    SecurityContext sc = SecurityContextHolder.getContext();
    sc.setAuthentication(auth);
    

    在上下文中设置 Authentication 后,我们现在可以使用 securityContext.getAuthentication().isAuthenticated() 检查当前用户是否已通过身份验证。

    3。Spring MVC

    默认情况下,Spring Security 在 Spring Security 过滤器链中添加了一个额外的过滤器——它能够持久化安全上下文(SecurityContextPersistenceFilter 类)。

    反过来,它将安全上下文的持久性委托给 SecurityContextRepository 的实例,默认为 HttpSessionSecurityContextRepository 类。

    因此,为了对请求设置身份验证并因此使其可用于来自客户端的所有后续请求,我们需要在 HTTP 会话中手动设置包含 AuthenticationSecurityContext

    public void login(HttpServletRequest req, String user, String pass) { 
        UsernamePasswordAuthenticationToken authReq = new UsernamePasswordAuthenticationToken(user, pass);
        Authentication auth = authManager.authenticate(authReq);
        
        SecurityContext sc = SecurityContextHolder.getContext();
        sc.setAuthentication(auth);
        HttpSession session = req.getSession(true);
        session.setAttribute(SPRING_SECURITY_CONTEXT_KEY, sc);
    }
    

    SPRING_SECURITY_CONTEXT_KEY 是静态导入的 HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY

    需要注意的是,我们不能直接使用 HttpSessionSecurityContextRepository -- 因为它与 SecurityContextPersistenceFilter. 一起工作

    这是因为我们使用的返回值是被 Wrapper 包装过后的对象,而 HttpSessionSecurityContextRepository 只能处理被 Wrapper 包装前的对象。

    4。结论

    在这个快速教程中,我们讨论了如何在 Spring Security 上下文中手动设置用户 Authentication 以及如何使其可用于 Spring MVC 目的,重点介绍了说明实现它的最简单方法的代码示例。

    与往常一样,可以在 GitHub 上 找到代码示例。

  • 相关阅读:
    正则表达式符号含义
    Java系列之:如何取出嵌套JSON中的数据值
    Spring复习之——IoC和AOP
    《痞子衡嵌入式半月刊》 第 66 期
    基于JAVA仁爱公益网站计算机毕业设计源码+系统+mysql数据库+lw文档+部署
    已经2023年了,你还不会手撕轮播图?
    人才资源开发杂志人才资源开发杂志社人才资源开发编辑部2022年第21期目录
    vue框架之插槽,组件的自定义,网络代理配置,网络公共路径配置
    网络安全(黑客)自学笔记
    【LeetCode】LeetCode 106.从中序与后序遍历序列构造二叉树
  • 原文地址:https://www.cnblogs.com/hunterzhang/p/16771018.html