spring security 使用 application/json 接收数据


不了解 security 的请看 security 的简单使用

https://blog.51cto.com/5013162/2404946


在使用 spring security 登录用户的时候 发现使用 application/josn 后台不能获取到数据
看 UsernamePasswordAuthenticationFilter 源码发现

    //获取密码protected String obtainPassword(HttpServletRequest request) {return request.getParameter(passwordParameter);}//获取用户名protected String obtainUsername(HttpServletRequest request) {return request.getParameter(usernameParameter);}

是直接从request 获取的 不是从 requestBody 中获取的

那我们就只需要重写这两个方法从 requestBody 中获取参数

重写 UsernamePasswordAuthenticationFilter 类

    public class UserAuthenticationFilter extends UsernamePasswordAuthenticationFilter {private ThreadLocal<Map<String,String>> threadLocal = new ThreadLocal<>();@Overrideprotected String obtainPassword(HttpServletRequest request) {String password = this.getBodyParams(request).get(super.SPRING_SECURITY_FORM_PASSWORD_KEY);if(!StringUtils.isEmpty(password)){return password;}return super.obtainPassword(request);}@Overrideprotected String obtainUsername(HttpServletRequest request) {String username = this.getBodyParams(request).get(super.SPRING_SECURITY_FORM_USERNAME_KEY);if(!StringUtils.isEmpty(username)){return username;}return super.obtainUsername(request);}/*** 获取body参数  body中的参数只能获取一次 * @param request* @return*/private Map<String,String> getBodyParams(HttpServletRequest request){Map<String,String> bodyParams =  threadLocal.get();if(bodyParams==null) {ObjectMapper objectMapper = new ObjectMapper();try (InputStream is = request.getInputStream()) {bodyParams = objectMapper.readValue(is, Map.class);} catch (IOException e) {}if(bodyParams==null) bodyParams = new HashMap<>();threadLocal.set(bodyParams);}return bodyParams;}
}自定义 SecurityConfig 类@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {@AutowiredUserDetailServiceImpl userDetailService;@AutowiredLoginSuccessHandler loginSuccessHandler;@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {//自定义用户验证和加密方式auth.userDetailsService(userDetailService).passwordEncoder(new BCryptPasswordEncoder());}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.formLogin()                    //  定义当需要用户登录时候,转到的登录页面。//          .loginPage("/login.html") //自定义登录页面
//                .loginProcessingUrl("/login") //自定义登录接口地址
//                .successHandler(loginSuccessHandler).and()// 定义哪些URL需要被保护、哪些不需要被保护.authorizeRequests().antMatchers("/login").permitAll() //不需要保护的URL.anyRequest()               // 任何请求,登录后可以访问.authenticated().and().logout().logoutSuccessUrl("/login").permitAll() // 登出.and().csrf().disable();//配置自定义过滤器 增加post json 支持http.addFilterAt(UserAuthenticationFilterBean(), UsernamePasswordAuthenticationFilter.class);}private UserAuthenticationFilter UserAuthenticationFilterBean() throws Exception {UserAuthenticationFilter userAuthenticationFilter = new UserAuthenticationFilter();userAuthenticationFilter.setAuthenticationManager(super.authenticationManager());userAuthenticationFilter.setAuthenticationSuccessHandler(loginSuccessHandler);return userAuthenticationFilter;}
}

登录成功处理类
LoginSuccessHandler.class

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {@Overridepublic void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {httpServletResponse.setContentType("application/json;charset=UTF-8");httpServletResponse.getWriter().write(authentication.getName());}
}

用户校验处理类

@Component
public class UserDetailServiceImpl implements UserDetailsService {/*** 用户校验* @param s* @return* @throws UsernameNotFoundException*/@Overridepublic UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {Collection<GrantedAuthority> collection = new ArrayList<>();//权限集合String password = new BCryptPasswordEncoder().encode("123456");User user = new User(s,password,collection);return user;}}

改造完成 支持 post application/json 同时也支持 post form-data/x-www-form-urlencoded
都可以获取到传入的参数

转载于:https://blog.51cto.com/5013162/2408405

spring security 使用 application/json 接收数据相关推荐

  1. Spring Security + Session Redis——JSON序列化错误[The class xxx and name of xxx is not whitelisted. ]解决方案

    前置 Spring Security + Spring Session + Redis--[SecurityContext]和[AuthenticationToken]JSON反序列化问题解决方案 问 ...

  2. 关于Js(四)------ jquery ajax 中json接收数据注意事项

    json获取的数据为数值型时,会四舍五入,最好要求后端传入的为字符串. 转载于:https://www.cnblogs.com/huangqiao/p/9224330.html

  3. Spring Security——集成Spring Session、Redis和JSON序列化解决方案

    官方文档 https://docs.spring.io/spring-session/docs/2.4.2/reference/html5/#spring-security Maven 主要 < ...

  4. Spring Security框架

    Spring Security框架 关于用户身份认证与授权 Spring Security是用于解决认证与授权的框架. 添加依赖 <!-- Spring Boot Security:处理认证与授 ...

  5. 【客户下单】后台提供webservice服务接收数据

    [客户下单]后台提供webservice服务接收数据 在bos_fore系统中,添加OrderAction封装订单数据. 接下来调用webservice,将数据传递给bos_management系统. ...

  6. 使用JWT和Spring Security保护REST API

    通常情况下,把API直接暴露出去是风险很大的,不说别的,直接被机器攻击就喝一壶的.那么一般来说,对API要划分出一定的权限级别,然后做一个用户的鉴权,依据鉴权结果给予用户开放对应的API.目前,比较主 ...

  7. Angular 6集成Spring Boot 2,Spring Security,JWT和CORS

    主要内容:Spring Boot 2的基础应用.CORS配置.Actuator监控:Spring Boot集成springfox-swagger,利用Swagger生成JSON API文档,利用Swa ...

  8. Java开发 - 单点登录初体验(Spring Security + JWT)

    目录​​​​​​​ 前言 为什么要登录 登录的种类 Cookie-Session Cookie-Session-local storage JWT令牌 几种登陆总结 用户身份认证与授权 创建工程 添加 ...

  9. 请求头Content-Type:application/json,java后端如何接收数据

    Content-Type的类型 1.application/x-www-form-urlencoded ​ 常用@RequestParam("参数名称")也可以不写使用spring ...

  10. 前台传递JSON数据,后台spring mvc如何接收数据

    如何传递JSON数据到后台? 方式一, 使用post请求,请求类型为:application/x-www-form-urlencoded; charset=UTF-8 $.ajax({url : ur ...

最新文章

  1. MIMO系统ML检测(最大似然检测)
  2. Apache rewrite
  3. 04.Java网络编程(转载)
  4. 【科普】从HTTP到HTTP/3的发展简史
  5. MFC列表控件ListControl和树控件TreeControl
  6. Chapter 5 Blood Type——24
  7. Spring Boot 之 elasticsearch
  8. 官宣预热iQOO 7强悍配置:“性能铁三角”加持 给你强悍全感
  9. iOS - 常用本机URL跳转设置
  10. 绿色版DNF(地下城勇士)全键盘连发工具,支持DNF双开
  11. 为何最近我们日子会很难过 之 第一篇
  12. 从腾讯云迁移到腾讯云,开心消消乐的云端迁移战事
  13. requests关于Exceeded 30 redirects
  14. iOS16.0:屏幕旋转
  15. angular 获取上一个路由地址 获取当前页地址 地址裁切
  16. 关于以太网IO模块如何选型
  17. 教你如何拥有好看的CMD界面 如何美化Windows Terminal
  18. 令人截图上瘾的录屏神器FSCapture
  19. 实战 - 学成在线项目
  20. java一个式子开根号语句_[基础篇]-基础知识整理-03-JAVA中的运算符

热门文章

  1. Python urllib爬取百度首页
  2. win10 打开注册表
  3. jQuery封装的选项卡方法
  4. 关于setTimeout的面试题
  5. 每一句都值得品味的话
  6. HTML sublime :Please wait a bit while PyV8 binary is being downloaded 及代码和注释颜色 ,大小调节
  7. 谁偷偷删了你的微信?别慌!一篇Python学习教程帮你都揪出来
  8. 前端响应式のmedia文件分离
  9. 你家的APS系统有这些功能吗?排程系统功能盘点
  10. mysql的体系架构和存储引擎