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();
    }
}

  

 

posted @ 2020-11-12 17:01  穆晟铭  阅读(1633)  评论(0编辑  收藏  举报