在《Spring Boot基于SpringSecurity设置swagger2访问权限》一文中我们集成了SpringSecurity,但是在使用的过程中发现一个问题,就是get请求可以正常访问,而post的请求却无法访问。

再三检查了对url路径权限的匹配,都没有问题。上篇文章中对应的SecurityConfig配置如下:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/api/**").permitAll() 
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .permitAll();
    }
}

api的post请求返回结果信息如下:

{
  "timestamp": "2020-03-24T12:44:12.782+0000",
  "status": 403,
  "error": "Forbidden",
  "message": "Forbidden",
  "path": "/api/check"
}

也就是说由于权限问题导致请求失败,返回403错误。

针对这个问题,最主要的原因是:SpringSecrity默认开启CSRF保护。

CSRF(Cross Site Request Forgery, 跨站域请求伪造)是一种网络的攻击方式。

可以这么理解CSRF攻击:攻击者盗用了你的身份,以你的名义发送恶意请求。CSRF能够做的事情包括:以你名义发送邮件,发消息,盗取你的账号,甚至于购买商品,虚拟货币转账……造成的问题包括:个人隐私泄露以及财产安全。

那么如何解决呢?方案有两种:

方案一:简单直接,禁用CSRF。修改之后的代码如下:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests()
                .antMatchers("/api/**").permitAll() 
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .permitAll();
    }
}

也就是添加了一行http.csrf().disable();。

方案二:重写CSRF保护策略。示例代码如下:

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;

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

经过以上两种方案解决之后,错误也就消失了。

精品SpringBoot 2.x视频教程

《Spring Boot 2.x 视频教程全家桶》,精品Spring Boot 2.x视频教程,打造一套最全的Spring Boot 2.x视频教程。



Spring Boot使用Spring Security POST无法访问解决方案插图

关注公众号:程序新视界,一个让你软实力、硬技术同步提升的平台

除非注明,否则均为程序新视界原创文章,转载必须以链接形式标明本文链接

本文链接:http://www.choupangxia.com/2020/03/24/spring-security-post-403/