我有一个使用Angular(5)+ Spring Boot(1.5.11)开发的UI应用程序,它正在调用使用Spring boot开发的Rest服务。
在UI应用程序中,我在application.properties中添加了 security.enable-csrf = false ,并在Rest服务中添加了以下代码以禁用CSRF
package com.dell.it.eis.email.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.codec.Base64;
@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Value("${api.security.username:}")
private String username;
@Value("${api.security.password:}")
private String password;
@Autowired
private Environment environment;
private static final String SECURITY_SKIP_PROFILE = "test";
@Override
protected void configure(HttpSecurity http) throws Exception {
if (!SECURITY_SKIP_PROFILE.equals(environment.getActiveProfiles()[0])) {
http.csrf().disable().authorizeRequests()
.regexMatchers("/application.wadl", "/swagger-ui.html")
.permitAll().anyRequest().authenticated().and().httpBasic();
}
}
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
if (!SECURITY_SKIP_PROFILE.equals(environment.getActiveProfiles()[0])) {
auth.inMemoryAuthentication().withUser(username)
.password(new String(Base64.decode(password.getBytes())))
.roles("USER");
}
}
}
对Rest服务的GET调用按预期工作,但POST / PUT调用引发以下错误。
{
"timestamp": 1533327330280,
"status": 403,
"error": "Forbidden",
"message": "Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.",
"path": "/restService/postCall"
}
深入了解该错误将非常有帮助。