gpt4 book ai didi

spring-security - OAuth2 - 检索 token 时选项请求的状态 401

转载 作者:行者123 更新时间:2023-12-04 07:19:54 26 4
gpt4 key购买 nike

我们的堆栈使用 Backbone 作为我们的客户端应用程序,使用 Spring Boot 作为 RESTful API。

我们正在尝试使用 OAuth2 进行基本身份验证,用户提供用户名和密码。

我们使用 Spring Security 进行身份验证,使用 jQuery $.ajax 方法进行请求。然而,我们在预检 OPTIONS 请求中得到的响应是 401(未授权)状态,然后我们甚至可以使用我们的 secret 来授权 POST header 。然而,我们可以毫无问题地发布或获取任何其他资源。 OPTIONS 请求的服务器响应是 200(ok),然后是 POST 请求。

那么,为什么来自/oauth/token 的 OPTIONS 请求会以 401 状态响应,即使它不应该响应?它不会让我们授权自己,因为它卡在我们无法添加授权 header 的 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
}

[...]
}

最佳答案

我只能从理论上回答你的问题:

So why is that an OPTIONS request from /oauth/token responses with 401 status even when it shouldn't? It won't let us authorize ourselves because it get's stuck at OPTIONS request in which we can't add authorization header.

这是因为 default configuration of the AuthServer是只允许在 token 端点进行完全身份验证的请求。

在您的资源服务器中,您允许所有请求在没有身份验证的情况下发生:http.authorizeRequests().anyRequest().permitAll();

我试图像提到的那样解决这种情况 here ,但我无法让它为我工作。

为了完整起见,我还在这里提到,你必须添加一个 CorsFilter将正确的 header 添加到 OPTIONS 预检请求中。

I also asked a very similar question ,所以也许如果我的答案得到解答,您也可以使用这些信息解决您的问题。

关于spring-security - OAuth2 - 检索 token 时选项请求的状态 401,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30622624/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com