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

我用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();

}

现在,当我尝试从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"

}

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

回答:

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

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

如果没有,您可以使用以下命令在特定路由上启用/禁用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;

}

});

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

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

但是,实际上,您会将应用程序置于不安全状态吗?我邀请您阅读

本文以保护您的应用程序免受CSRF的侵害,即使您的应用程序基于REST服务而不是表单提交也是如此。

以上是 如何在Spring Security中启用POST,PUT和DELETE方法 的全部内容, 来源链接: utcz.com/qa/425702.html

回到顶部