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

这篇具有很好参考价值的文章主要介绍了系列十一、Spring Security登录接口兼容JSON格式登录。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

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

1.1、概述

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

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

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

那么如何让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、测试

系列十一、Spring Security登录接口兼容JSON格式登录,Spring Security OAuth2.0系列,Spring Security,OAuth2文章来源地址https://www.toymoban.com/news/detail-808309.html

到了这里,关于系列十一、Spring Security登录接口兼容JSON格式登录的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Spring Security 6.0系列【8】认证篇之注销登录

    有道无术,术尚可求,有术无道,止于术。 本系列Spring Boot 版本 3.0.4 本系列Spring Security 版本 6.0.2 源码地址:https://gitee.com/pearl-organization/study-spring-security-demo

    2023年04月08日
    浏览(29)
  • Spring Security 6.0系列【14】认证篇之添加登录验证码功能

    有道无术,术尚可求,有术无道,止于术。 本系列Spring Boot 版本 3.0.4 本系列Spring Security 版本 6.0.2 源码地址:https://gitee.com/pearl-organization/study-spring-security-demo 验证码 ( CAPTCHA )是“ Completely Automated Public Turing test to tell Computers and Humans Apart ”(全自动区分计算机和人类的图灵

    2023年04月09日
    浏览(31)
  • spring boot中常用的安全框架 Security框架 利用Security框架实现用户登录验证token和用户授权(接口权限控制)

    spring boot中常用的安全框架 Security 和 Shiro 框架 Security 两大核心功能 认证 和 授权 重量级 Shiro 轻量级框架 不限于web 开发 在不使用安全框架的时候 一般我们利用过滤器和 aop自己实现 权限验证 用户登录 Security 实现逻辑 输入用户名和密码 提交 把提交用户名和密码封装对象

    2024年02月06日
    浏览(39)
  • Spring Security 6.0系列【15】认证篇之实现短信验证码登录功能

    有道无术,术尚可求,有术无道,止于术。 本系列Spring Boot 版本 3.0.4 本系列Spring Security 版本 6.0.2 源码地址:https://gitee.com/pearl-organization/study-spring-security-demo 目前大部分网站都支持使用 手机号+短信验证码 登录,比

    2023年04月24日
    浏览(45)
  • Spring Security 6.x 系列【15】认证篇之实现短信验证码登录功能

    有道无术,术尚可求,有术无道,止于术。 本系列Spring Boot 版本 3.0.4 本系列Spring Security 版本 6.0.2 源码地址:https://gitee.com/pearl-organization/study-spring-security-demo 目前大部分网站都支持使用 手机号+短信验证码 登录,比

    2024年02月05日
    浏览(37)
  • 手把手教你学会接口自动化系列十一-将用例写在json中,持久化管理起来下

    上一篇我写了登录,我们发现json还是没有什么大问题,还蛮好用的,但是我们再写下一个,比如线索新建接口的时候,我们写着写着会发现问题: 我们写获取url的没有问题,代码如下: # 读取JSON文件 url = baseUrl[\\\'host\\\']+read_json_file(jsonpath)[\\\'url\\\'] print(url) 下一个我们要获取的是

    2024年01月18日
    浏览(30)
  • Java json 格式化小工具兼容转义 json 串

    封装了一个格式化 json 小工具,支持标准的 json 格式 和 经过后端编程语言如 java 转义后的 字符串 json 格式的格式化输出,代码如下: 我们看下两种 json 数据: 注意第一种使用 JSON 工具处理时,并不能正常解析,需要先转义才行,注意: 在 IDEA中 测试时不能直接将上面的内

    2024年02月07日
    浏览(40)
  • Spring Security--自动登录

    也就是remember me 在配置链上加一个  然后发送请求时加上:remember-me字段 value值可以为,ture,1,on 我们记住登录后,关掉浏览器再打开,访问一下接口,可以访问,说明记住登录成功了。    因为有的接口可以支持rememberMe认证,有的接口不支持,用上图的方式做区别。 //禁止

    2024年02月08日
    浏览(27)
  • 【深入浅出 Spring Security(十一)】授权原理分析和持久化URL权限管理

    在 【深入浅出Spring Security(一)】Spring Security的整体架构 中小编解释过授权所用的三大组件,在此再解释说明一下(三大组件具体指:ConfigAttribute、AccessDecisionManager(决策管理器)、AccessDecisionVoter(决策投票器)) ConfigAttribute 在 Spring Security 中,用户请求一个资源(通常是

    2024年02月10日
    浏览(36)
  • Spring Security多登录页面示例

    在 Web 应用程序开发中,有两个单独的模块是很常见的 - 一个用于管理员用户,一个用于普通用户。每个模块都有一个单独的登录页面,并且可以与相同或不同的身份验证源相关联。换句话说,应用程序为不同类型的用户提供了多个登录页面:管理员和用户,或管理员和客户

    2023年04月23日
    浏览(23)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包