java 如何在 Spring Security 中启用 POST、PUT 和 DELETE 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38108357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 03:07:40  来源:igfitidea点击:

How to enable POST, PUT AND DELETE methods in spring security

javarestspring-mvcspring-securityspring-boot

提问by Rajan

I developed an application with spring boot, which was working fine. There is a restful controller. I tried to add spring security to some of the pages. The rest controller's endpoint is

我用 spring boot 开发了一个应用程序,运行良好。有一个宁静的控制器。我试图为某些页面添加弹簧安全性。其余控制器的端点是

/api/greetings

/api/greetings

I configured the security settings in the class below.

我在下面的课程中配置了安全设置。

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/home","/api/greetings").permitAll()
                //.antMatchers("/api/greetings","").permitAll()//can't do this
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

Now, when I tried accessing the Rest endpoint, from a Rest-client(Postman), only the GET method is accessible and i am getting 403 Forbidden response if I try to POST, PUT or DELETE.

现在,当我尝试从 Rest 客户端(邮递员)访问 Rest 端点时,只有 GET 方法可以访问,如果我尝试 POST、PUT 或 DELETE,我会收到 403 Forbidden 响应。

{
    "timestamp": 1467223888525,
    "status": 403,
    "error": "Forbidden",
    "message": "Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.",
    "path": "/api/greetings/2"
}

How do i solve this issue. I am new to Spring Security things.

我如何解决这个问题。我是 Spring Security 的新手。

采纳答案by MGR

UPDATE Answer

更新答案

If you're using Spring security 4, you can disable specific routes easily

如果您使用的是 Spring security 4,则可以轻松禁用特定路由

http.csrf().ignoringAntMatchers("/nocsrf","/ignore/startswith/**")

If not, you can enable/disable CSRF on specific routes using requireCsrfProtectionMatcher

如果没有,您可以使用在特定路由上启用/禁用 CSRF requireCsrfProtectionMatcher

http.csrf().requireCsrfProtectionMatcher(new RequestMatcher() {
    private Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");
    private RegexRequestMatcher apiMatcher = new RegexRequestMatcher("/v[0-9]*/.*", null);

    @Override
    public boolean matches(HttpServletRequest request) {
        // No CSRF due to allowedMethod
        if(allowedMethods.matcher(request.getMethod()).matches())
            return false;

        // No CSRF due to api call
        if(apiMatcher.matches(request))
            return false;

        // CSRF for everything else that is not an API call or an allowedMethod
        return true;
    }
});

ORIGINAL Answer

原始答案

You got an error because CSRF handling is 'on' by default with Spring Security.

您收到错误消息,因为 Spring Security 的 CSRF 处理默认为“开启”。

You can disabled it by adding http.csrf().disable();.

您可以通过添加禁用它http.csrf().disable();

But really, would you leave your application unsecured? I invite you to read this articleto protect your application against CSRF, even if your application is based on REST service and not form submission.

但真的,你会让你的应用程序不安全吗?我邀请您阅读 本文以保护您的应用程序免受 CSRF 的侵害,即使您的应用程序基于 REST 服务而不是表单提交。