我们的堆栈使用Backbone作为客户端应用程序,Spring Boot作为RESTful API使用 .
我们正在尝试使用OAuth2进行基本身份验证,用户提供用户名和密码 .
我们使用Spring Security进行身份验证,使用jQuery $ .ajax方法进行请求 . 然而,我们得到的响应是在预检OPTIONS请求上的401(未授权)状态,然后我们甚至可以使用我们的秘密来授权POST头 . 但是我们可以毫无问题地发布或获取任何其他资源 . OPTIONS请求的服务器响应是200(ok),然后它跟进POST请求 .
那么,为什么来自/ oauth / token响应的OPTIONS请求具有401状态,即使它不应该?它不会让我们自己授权,因为它会停留在我们无法添加授权标头的OPTIONS请求中 .
这是我们处理前端请求的方式:
$.ajax({
url: "http://localhost:8080/oauth/token",
type: "POST",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic Y2xpZW50YXBwOjEyMzQ1Ng==");
},
data: {
password: "qwerty",
username: "jkowalski",
grant_type: "password"
}
});
这是我们的OAuth2配置:
@Configuration
public class OAuth2ServerConfiguration {
private static final String RESOURCE_ID = "restservice";
@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends
ResourceServerConfigurerAdapter {
[...]
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http
.authorizeRequests()
.anyRequest().permitAll();
}
}
[...]
@Configuration
@EnableAuthorizationServer
protected static class OAuth2AuthorizationConfig extends
AuthorizationServerConfigurerAdapter {
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// @formatter:off
clients
.inMemory()
.withClient("clientapp")
.authorizedGrantTypes("password", "refresh_token")
.authorities("USER","ADMIN")
.scopes("read", "write")
.resourceIds(RESOURCE_ID)
.secret("123456");
// @formatter:on
}
[...]
}
1 回答
我可以在理论上回答你的问题:
这是因为default configuration of the AuthServer仅允许在令牌 endpoints 处进行完全认证的请求 .
在您的资源服务器中,您允许所有请求在未经身份验证的情况下发生:
http.authorizeRequests().anyRequest().permitAll();
我试图像提到的那样解决这种情况here,但我不能让我这样做 .
为了完整起见,我在这里也提到,你必须添加一个CorsFilter来为OPTIONS预检请求添加正确的 Headers .
I also asked a very similar question,所以如果我的答案得到解答,你也可以用这些信息来解决你的问题 .