网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

springsecurity如何使用application/json接收数据

这篇文章将为大家详细讲解有关springsecurity如何使用application/json接收数据,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

创新互联公司专注为客户提供全方位的互联网综合服务,包含不限于网站设计、成都网站制作、山南网络推广、成都小程序开发、山南网络营销、山南企业策划、山南品牌公关、搜索引擎seo、人物专访、企业宣传片、企业代运营等,从售前售中售后,我们都将竭诚为您服务,您的肯定,是我们最大的嘉奖;创新互联公司为所有大学生创业者提供山南建站搭建服务,24小时服务热线:13518219792,官方网址:www.cdcxhl.com

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> threadLocal = new ThreadLocal<>();

        @Override
        protected 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);
        }

        @Override
        protected 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 getBodyParams(HttpServletRequest request){
                Map 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 {

        @Autowired
        UserDetailServiceImpl userDetailService;
        @Autowired
        LoginSuccessHandler loginSuccessHandler;

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
                //自定义用户验证和加密方式
                auth.userDetailsService(userDetailService).passwordEncoder(new BCryptPasswordEncoder());
        }

        @Override
        protected 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 {
        @Override
        public 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
         */
        @Override
        public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
                Collection 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
都可以获取到传入的参数

关于“springsecurity如何使用application/json接收数据”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。


网站栏目:springsecurity如何使用application/json接收数据
文章路径:http://bjjierui.cn/article/pccghc.html

其他资讯