我刚刚在我的项目中实现了 Spring Security。 我启用了 CSRF。 问题是 - 我认为所有对 REST API(Spring) 的 POST 请求现在都被 Spring Security 阻止了。
这是我的Spring Security配置
<context:annotation-config/>
<!-- enable use-expressions -->
<http auto-config="true" use-expressions="true">
<headers>
<cache-control />
</headers>
<intercept-url pattern="/maps/api/admin**" access="hasRole('ROLE_ADMIN')"/>
<intercept-url pattern="/user**" access="hasRole('ROLE_USER')"/>
<!-- access denied page -->
<access-denied-handler error-page="/403"/>
<form-login
login-processing-url="/login/processing"
login-page="/user-login"
default-target-url="/"
authentication-failure-url="/user-login"
username-parameter="username"
password-parameter="password"
authentication-success-handler-ref="successHandler"
authentication-failure-handler-ref="failureHandler"/>
<logout logout-success-url="/maps/api/user-login?logout" delete-cookies="JSESSIONID"/>
<!-- enable csrf protection -->
<csrf/>
</http>
我有一个自定义的身份验证成功处理程序,并且用于身份验证的 POST 效果很好。
这就是我发送 POST 进行身份验证的方式(在 Angular 中)
var req = {
method: 'POST',
url: '/login/processing',
headers: {
'Content-Type': "application/x-www-form-urlencoded",
'Upgrade-Insecure-Requests': "1",
'X-CSRF-TOKEN': $('input[name="_csrf"]').val()
},
data: $(obj.target).serialize()
}
$http(req)
.success(function(data, status, headers, config){
blab bla bla
})
.error(function(data){
alert( "Exception details: " + JSON.stringify({data: data}));
});
这是我发送以从 Spring REST API Controller 检索数据的其他 POST 请求的示例:
var formData = {
"username" : $scope.registerUser.email,
"password" : $scope.registerUser.password
};
var req = {
method: 'POST',
url: '/maps/api/user/register',
headers: {
'X-CSRF-TOKEN': $('input[name="_csrf"]').val(),
//'Content-Type': "application/x-www-form-urlencoded"
'Content-Type': 'application/json'
},
data: formData
}
$http(req)
.success(function(data, status, headers, config){
blaaaaaaaa
})
.error(function(data, status, headers, config){
alert( "Exception details: " + JSON.stringify({data: data}));
});
并收到此错误:
The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers.
但实际上我得到了'Content-Type': 'application/json'
作为“接受” header , Controller 还返回一个 JSON 对象。
有人可以帮忙吗?
最佳答案
您的 Spring 版本是什么(如果是 4.1.* )。将以下 jar 添加到您的 pom.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.1.1</version>
</dependency>
或者 添加
headers = "Accept=*/*", produces = "application/json"
到您的 Controller 映射
关于java - Spring Security + AngularJS Ajax 帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32114045/