• springboot,springSecurity中POST请求404


    解决方案:

    方式一.服务后台配置

           1.直接禁用csrf保护。在configure(HttpSecurity http)方法中添加   http.csrf().disable();

           2.重写csrf保护策略。

            在configure(HttpSecurity http)方法中添加   http.csrf().requireCsrfProtectionMatcher(requestMatcher());

            新增处理类

    package com.levenx.config.security;
     
    import org.springframework.security.web.util.matcher.RequestMatcher;
     
    import javax.servlet.http.HttpServletRequest;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.regex.Pattern;
     
    /**
     * Created by 乐闻 on 2018/9/11.
     */
    public class CsrfSecurityRequestMatcher implements RequestMatcher {
     
        private Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");
     
        @Override
        public boolean matches(HttpServletRequest request) {
            List<String> unExecludeUrls = new ArrayList<>();
            //unExecludeUrls.add("/api/test");//(不允许post请求的url路径)此处根据自己的需求做相应的逻辑处理
     
            if (unExecludeUrls != null && unExecludeUrls.size() > 0) {
                String servletPath = request.getServletPath();
                request.getParameter("");
                for (String url : unExecludeUrls) {
                    if (servletPath.contains(url)) {
                        return true;
                    }
                }
            }
            return allowedMethods.matcher(request.getMethod()).matches();
        }
    }
    

      

    或者允许通过:

    RequestMatcher requestMatcher = new CsrfSecurityRequestMatcher();
    http.csrf().requireCsrfProtectionMatcher(requestMatcher);
    

      

    其中CsrfSecurityRequestMatcher自己实现RequestMatcher

    public class CsrfSecurityRequestMatcher implements RequestMatcher {
         
         private Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");
         
        @Override
        public boolean matches(HttpServletRequest request) {
            List<String> execludeUrls = new ArrayList<>();
            execludeUrls.add("sys/getSecCode.do");//允许post请求的url路径,这只是简单测试,具体要怎么设计这个csrf处理,看个人爱好
             
             if (execludeUrls != null && execludeUrls.size() > 0) {
                    String servletPath = request.getServletPath();
                    request.getParameter("");
                    for (String url : execludeUrls) {
                        if (servletPath.contains(url)) {
                            return false;
                        }
                    }
                }
             return !allowedMethods.matcher(request.getMethod()).matches();
        }
    }
    

      

  • 相关阅读:
    Herny
    机器学习No.4
    机器学习No.3
    机器学习No.2
    机器学习No.1
    算法第五章上机实践报告
    算法第五章作业
    算法第四章实践报告
    算法第四章作业
    算法第三章作业
  • 原文地址:https://www.cnblogs.com/achengmu/p/13964874.html
Copyright © 2020-2023  润新知