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

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM