系列十一、Spring Security登录接口兼容JSON格式登录

news2025/4/24 4:01:22

一、Spring Security登录接口兼容JSON格式登录

1.1、概述

        前后端分离中,前端和后端的数据交互通常是JSON格式,而Spring Security的登录接口默认支持的是form-data或者x-www-form-urlencoded的,如下所示:

那么如何让Spring Security的登录接口也支持JSON格式登录呢?请看下文分析 

1.2、自定义过滤器

/**
 * @Author : 一叶浮萍归大海
 * @Date: 2024/1/13 9:30
 * @Description:
 */
public class MyUsernamePasswordAuthenticationFilter7007 extends UsernamePasswordAuthenticationFilter {

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!HttpMethod.POST.name().equals(request.getMethod())) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        String sessionCode = (String) request.getSession().getAttribute("code");
        if (MediaType.APPLICATION_JSON_VALUE.equals(request.getContentType()) || MediaType.APPLICATION_JSON_UTF8_VALUE.equals(request.getContentType())) {
            Map<String, String> loginData = new HashMap<>(16);
            try {
                loginData = new ObjectMapper().readValue(request.getInputStream(), Map.class);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                String paramCode = loginData.get("code");
                try {
                    checkCode(response,paramCode,sessionCode);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
            String username = loginData.get(getUsernameParameter());
            String password = loginData.get(getPasswordParameter());
            if (username == null) {
                username = "";
            }
            if (password == null) {
                password = "";
            }
            username = username.trim();
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
            setDetails(request,authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        } else {
            try {
                checkCode(response,request.getParameter("code"),sessionCode);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return super.attemptAuthentication(request, response);
        }
    }

    /**
     * 检查验证码
     * @param response
     * @param paramCode
     * @param sessionCode
     */
    private void checkCode(HttpServletResponse response, String paramCode, String sessionCode) throws Exception {
        if (StringUtils.isBlank(paramCode)) {
            R r = R.error(ResponseEnum.VERIFY_CODE_IS_NULL.getCode(), ResponseEnum.VERIFY_CODE_IS_NULL.getMessage());
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.write(new ObjectMapper().writeValueAsString(r));
            out.flush();
            out.close();
            return;
        }
        if (StringUtils.isBlank(sessionCode)) {
            R r = R.error(ResponseEnum.VERIFY_CODE_IS_EXPIRED.getCode(), ResponseEnum.VERIFY_CODE_IS_EXPIRED.getMessage());
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.write(new ObjectMapper().writeValueAsString(r));
            out.flush();
            out.close();
            return;
        }
        if (!StringUtils.equals(paramCode.toLowerCase(), sessionCode.toLowerCase())) {
            R r = R.error(ResponseEnum.VERIFY_CODE_IS_NOT_MATCH.getCode(), ResponseEnum.VERIFY_CODE_IS_NOT_MATCH.getMessage());
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.write(new ObjectMapper().writeValueAsString(r));
            out.flush();
            out.close();
            return;
        }
    }
}

1.3、配置类

/**
 * @Author : 一叶浮萍归大海
 * @Date: 2024/1/11 21:50
 * @Description: Spring Security配置类
 */
@Configuration
public class MyWebSecurityConfigurerAdapter7007 extends WebSecurityConfigurerAdapter {

    @Resource
    private MyAuthenticationSuccessHandler7007 successHandler;
    @Resource
    private MyAuthenticationFailureHandler7007 failureHandler;
    @Resource
    private MyLogoutSuccessHandler7007 logoutSuccessHandler;
    @Resource
    private MyAuthenticationEntryPoint7007 authenticationEntryPoint;
    @Resource
    private MyAccessDeniedHandler7007 accessDeniedHandler;
    @Resource
    private UserDetailsService userDetailsServiceImpl;

    /**
     * 密码加密器
     *
     * @return
     */
    @Bean
    PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

    /**
     * 定义基于MyBatis-Plus的用户
     *
     * @return
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsServiceImpl);
    }

    /**
     * 角色继承
     *
     * @return
     */
    @Bean
    protected RoleHierarchy roleHierarchy() {
        RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
        roleHierarchy.setHierarchy("ROLE_admin > ROLE_dba");

        return roleHierarchy;
    }

    @Bean
    public MyUsernamePasswordAuthenticationFilter7007 usernamePasswordAuthenticationFilter() throws Exception {
        MyUsernamePasswordAuthenticationFilter7007 usernamePasswordAuthenticationFilter = new MyUsernamePasswordAuthenticationFilter7007();
        usernamePasswordAuthenticationFilter.setFilterProcessesUrl("/login");
        usernamePasswordAuthenticationFilter.setAuthenticationManager(authenticationManager());
        // 登录成功回调
        usernamePasswordAuthenticationFilter.setAuthenticationSuccessHandler(successHandler);
        // 登录失败回调
        usernamePasswordAuthenticationFilter.setAuthenticationFailureHandler(failureHandler);
        return usernamePasswordAuthenticationFilter;

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/dba/**").hasRole("dba")
                .antMatchers("/admin/**").hasRole("admin")
                .antMatchers("/helloWorld", "/verifyCode/getVerifyCode")
                .permitAll()
                .anyRequest()
                .authenticated()

                .and()

                /**
                 * 注销登录回调
                 */
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler(logoutSuccessHandler)
                .permitAll()

                .and()

                .csrf()
                .disable()

                /**
                 * 未认证 & 权限不足回调
                 */
                .exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint)
                .accessDeniedHandler(accessDeniedHandler);
        http.addFilterAfter(usernamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

}

1.4、测试

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1382433.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

计算机三级(网络技术)——应用题

第一题 61.输出端口S0 &#xff08;直接连接&#xff09; RG的输出端口S0与RE的S1接口直接相连构成一个互联网段 对172.0.147.194和172.0.147.193 进行聚合 前三段相同&#xff0c;将第四段分别转换成二进制 11000001 11000010 前6位相同&#xff0c;加上前面三段 共30…

【数据库】聊聊MySQL事务隔离级别与锁机制

概述 针对事务来说&#xff0c;其实主要解决的就是数据的一致性&#xff0c;对于任何的存储中间件来说&#xff0c;都会存在并发访问数据的问题&#xff0c;编程语言层面 juc、go等机制 使用编程上的方式&#xff0c;加锁、无锁编程等。而数据库也存在多个连接访问修改同一个数…

KEI5许可证没到期,编译却出现Error: C9555E: Failed to check out a license.问题解决

一、编译出现如下报错 二、检查一下许可证 三、许可证在许可日期内&#xff0c;故应该不是许可证的问题 四、检查一下编译器&#xff0c;我用的是这个&#xff0c;这几个编译器的区别其实我不太明白&#xff0c;但我把问题解决是选的这个 五、找到编译器的路径&#xff0c;去复…

metrics安装异常原因【doesn‘t contain any IP SANs】

1、问题背景 安装好k8s后&#xff0c;安装metrics-server后发现对应的pod一直无法启动。 apiVersion: v1 kind: ServiceAccount metadata:labels:k8s-app: metrics-servername: metrics-servernamespace: kube-system --- apiVersion: rbac.authorization.k8s.io/v1 kind: Cl…

windows下如何搭建Yapi环境

今天使用YApi时发现原网址无法访问。这下只能本地部署了&#xff08;官方文档&#xff09;。 第一步&#xff1a;安装node.js 获取资源 nodejs: https://nodejs.org/en/downloadLinux安装yum install -y nodejs查看node版本node -v查看npm版本npm -v第二步&#xff1a;安装mo…

Redis命令 - Hashes命令组常用命令

1、HSET key field value 设置 key 指定的哈希集中指定字段的值。 HSET key field value 返回值&#xff1a;1代表field是一个新的字段。0代表field已存在 如果 key 指定的哈希集不存在&#xff0c;会创建一个新的哈希集并与 key 关联。如果字段在哈希集中存在&#xff0c;它将…

【算法】最佳牛围栏(二分,前缀和,双指针)

题目 农夫约翰的农场由 N 块田地组成&#xff0c;每块地里都有一定数量的牛&#xff0c;其数量不会少于 1 头&#xff0c;也不会超过 2000 头。 约翰希望用围栏将一部分连续的田地围起来&#xff0c;并使得围起来的区域内每块地包含的牛的数量的平均值达到最大。 围起区域内…

9. 乐观锁

当程序中出现并发访问时&#xff0c;就需要保证数据的一致性。以商品系统为例&#xff0c;现在有两个管理员均想对同一件售价为 100 元的商品进行修改&#xff0c;A 管理员正准备将商品售价改为 150 元&#xff0c;但此时出现了网络问题&#xff0c;导致 A 管理员的操作陷入了等…

大括号内两行公式中,如何左对齐公式的条件

1. 先建立一个大括号&#xff0c;中间设置一个二维矩阵如下&#xff1a; 2. 选中整个矩阵&#xff0c;不要选外面的括号&#xff0c;进行如下操作 3. 选择左侧对齐 即可。

浅析Linux进程地址空间

前言 现代处理器基本都支持虚拟内存管理&#xff0c;在开启虚存管理时&#xff0c;程序只能访问到虚拟地址&#xff0c;处理器的内存管理单元&#xff08;MMU&#xff09;会自动完成虚拟地址到物理地址的转换。基于虚拟内存机制&#xff0c;操作系统可以为每个运行中的进程创建…

YOLOv8原理与源码解析

课程链接&#xff1a;https://edu.csdn.net/course/detail/39251 【为什么要学习这门课】 Linux创始人Linus Torvalds有一句名言&#xff1a;Talk is cheap. Show me the code. 冗谈不够&#xff0c;放码过来&#xff01;代码阅读是从基础到提高的必由之路。 YOLOv8 基于先前…

linux多进程基础(3):waitpid()函数

前文已经讲解了wait函数,这一篇要讲的是waitpid()函数. waitpid()函数与wait()函数目的一致:回收子进程资源,但它比 wait() 更灵活&#xff0c;其可以指定要等待的子进程的 PID&#xff08;进程ID),并且可以设置函数是阻塞还是非阻塞的,当设置为非阻塞的,主函数将不再等待子函…

Dobbo---分布式系统通信方式

通信方式 分布式系统通信方式1. RMIRMI 通信实现案例2. RPC常用RPC框架 分布式系统通信方式 1. RMI RMI ( Remote Method Invocation 远程方法调用) 图1.1 客户端-服务端通信方式 客户端将要调用的方法及参数&#xff0c;打包为辅助对象&#xff0c;通过网络socket&#xff…

【CAN】CANoe添加模拟节点报错解决方法

文章目录 1. 问题现象2. 问题解决方法 >>返回总目录<< 1. 问题现象 通过CANoe添加模拟节点时&#xff0c;提示无法加载动态链接库CANOEILNLSPA.DLL。 2. 问题解决方法 右键模拟节点&#xff0c;选择Configuration选项&#xff0c;弹出Node Configuration界面&am…

Vue.observable详解(细到原码)

文章目录 一、Observable 是什么二、使用场景三、原理分析参考文献 一、Observable 是什么 Observable 翻译过来我们可以理解成可观察的 我们先来看一下其在Vue中的定义 Vue.observable&#xff0c;让一个对象变成响应式数据。Vue 内部会用它来处理 data 函数返回的对象 返回…

JS数组函数 reduce() 的用法—包含基础、进阶、高阶用法

目录 一、语法剖析 二、实例讲解 1. 求数组项之和 2. 求数组项最大值 3. 数组去重 三、其他相关方法 1. reduceRight() 2. forEach()、map()、every()、some()和filter() 四、重点总结 先看w3c语法 ✔ 常见用法 数组求和 数组最大值 ✔ 进阶用法 数组对象中的用…

【Maven】007-Maven 工程的继承和聚合关系

【Maven】007-Maven 工程的继承和聚合关系 文章目录 【Maven】007-Maven 工程的继承和聚合关系一、Maven 工程的继承关系1、继承的概念2、继承的作用3、继承的语法4、父工程统一管理依赖版本父工程声明依赖版本子工程继承以来版本 二、Maven 工程的聚合关系1、聚合的概念2、聚合…

exec函数簇和守护进程

目录 一、exec函数族 二、守护进程 三、GDB调试多进程程序 一、exec函数族 exec函数使得进程当前内容被指定的程序替换。 示例&#xff1a; 运行结果&#xff1a; 代码就相当于执行命令&#xff1a;ls -a -l ./ 二、守护进程 举例&#xff1a; 运行结果&#xff1a; 举例…

计算机网络——第三层:网络层

1. IP数据报 1.1 IPV4数据报 1.1.1 IPv4数据报的结构 如图按照RFC 791规范显示了一个IPv4数据包头部的不同字段 IPv4头部通常包括以下部分&#xff1a; 1.1.1.1 版本&#xff08;Version&#xff09; 指明了IP协议的版本&#xff0c;IPv4表示为4。 1.1.1.2 头部长度&#x…

AR HUD全面「上新」

AR HUD赛道正在迎来新的时代。 上周&#xff0c;蔚来ET9正式发布亮相&#xff0c;新车定位为D级行政旗舰轿车&#xff0c;其中&#xff0c;在智能座舱交互层面&#xff0c;继理想L系列、长安深蓝S7之后&#xff0c;也首次取消仪表盘&#xff0c;取而代之的是业内首个全焦段AR H…