spring security 使用 application/json 接收数据
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 接收数据相关推荐
- Spring Security + Session Redis——JSON序列化错误[The class xxx and name of xxx is not whitelisted. ]解决方案
前置 Spring Security + Spring Session + Redis--[SecurityContext]和[AuthenticationToken]JSON反序列化问题解决方案 问 ...
- 关于Js(四)------ jquery ajax 中json接收数据注意事项
json获取的数据为数值型时,会四舍五入,最好要求后端传入的为字符串. 转载于:https://www.cnblogs.com/huangqiao/p/9224330.html
- Spring Security——集成Spring Session、Redis和JSON序列化解决方案
官方文档 https://docs.spring.io/spring-session/docs/2.4.2/reference/html5/#spring-security Maven 主要 < ...
- Spring Security框架
Spring Security框架 关于用户身份认证与授权 Spring Security是用于解决认证与授权的框架. 添加依赖 <!-- Spring Boot Security:处理认证与授 ...
- 【客户下单】后台提供webservice服务接收数据
[客户下单]后台提供webservice服务接收数据 在bos_fore系统中,添加OrderAction封装订单数据. 接下来调用webservice,将数据传递给bos_management系统. ...
- 使用JWT和Spring Security保护REST API
通常情况下,把API直接暴露出去是风险很大的,不说别的,直接被机器攻击就喝一壶的.那么一般来说,对API要划分出一定的权限级别,然后做一个用户的鉴权,依据鉴权结果给予用户开放对应的API.目前,比较主 ...
- Angular 6集成Spring Boot 2,Spring Security,JWT和CORS
主要内容:Spring Boot 2的基础应用.CORS配置.Actuator监控:Spring Boot集成springfox-swagger,利用Swagger生成JSON API文档,利用Swa ...
- Java开发 - 单点登录初体验(Spring Security + JWT)
目录 前言 为什么要登录 登录的种类 Cookie-Session Cookie-Session-local storage JWT令牌 几种登陆总结 用户身份认证与授权 创建工程 添加 ...
- 请求头Content-Type:application/json,java后端如何接收数据
Content-Type的类型 1.application/x-www-form-urlencoded 常用@RequestParam("参数名称")也可以不写使用spring ...
- 前台传递JSON数据,后台spring mvc如何接收数据
如何传递JSON数据到后台? 方式一, 使用post请求,请求类型为:application/x-www-form-urlencoded; charset=UTF-8 $.ajax({url : ur ...
最新文章
- MIMO系统ML检测(最大似然检测)
- Apache rewrite
- 04.Java网络编程(转载)
- 【科普】从HTTP到HTTP/3的发展简史
- MFC列表控件ListControl和树控件TreeControl
- Chapter 5 Blood Type——24
- Spring Boot 之 elasticsearch
- 官宣预热iQOO 7强悍配置:“性能铁三角”加持 给你强悍全感
- iOS - 常用本机URL跳转设置
- 绿色版DNF(地下城勇士)全键盘连发工具,支持DNF双开
- 为何最近我们日子会很难过 之 第一篇
- 从腾讯云迁移到腾讯云,开心消消乐的云端迁移战事
- requests关于Exceeded 30 redirects
- iOS16.0:屏幕旋转
- angular 获取上一个路由地址 获取当前页地址 地址裁切
- 关于以太网IO模块如何选型
- 教你如何拥有好看的CMD界面 如何美化Windows Terminal
- 令人截图上瘾的录屏神器FSCapture
- 实战 - 学成在线项目
- java一个式子开根号语句_[基础篇]-基础知识整理-03-JAVA中的运算符