【发布时间】:2015-08-17 19:29:50
【问题描述】:
我们的堆栈使用 Backbone 作为客户端应用,使用 Spring Boot 作为 RESTful API。
我们正在尝试使用 OAuth2 进行基本身份验证,用户提供用户名和密码。
我们使用 Spring Security 进行身份验证,使用 jQuery $.ajax 方法发出请求。然而,我们得到的响应是预检 OPTIONS 请求的 401(未授权)状态,然后我们甚至可以发布带有我们授权的秘密的标头。 但是,我们可以毫无问题地 POST 或 GET 任何其他资源。 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
}
[...]
}
【问题讨论】:
标签: spring-security oauth-2.0 cors single-page-application restful-authentication