如何在spring安全性中启用POST,PUT和DELETE方法

Raj*_*jan 5 java rest spring-mvc spring-security spring-boot

我用弹簧靴开发了一个应用程序,工作正常.有一个安静的控制器.我试图在某些页面添加spring security.其余控制器的端点是

/api/greetings

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

@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();
    }
Run Code Online (Sandbox Code Playgroud)

现在,当我尝试从Rest-client(Postman)访问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"
}
Run Code Online (Sandbox Code Playgroud)

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

MGR*_*MGR 5

更新答案

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

http.csrf().ignoringAntMatchers("/nocsrf","/ignore/startswith/**")
Run Code Online (Sandbox Code Playgroud)

如果没有,您可以使用以下命令在特定路由上启用/禁用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;
    }
});
Run Code Online (Sandbox Code Playgroud)

原始答案

您收到错误消息是因为Spring Security默认将CSRF处理设置为“开”。

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

但是,实际上,您会将应用程序置于不安全状态吗?我邀请您阅读 本文以保护您的应用程序免受CSRF的侵害,即使您的应用程序基于REST服务而不是表单提交也是如此。