gpt4 book ai didi

asp.net - OWIN token 身份验证 400 来自浏览器的 OPTIONS 的错误请求

转载 作者:行者123 更新时间:2023-12-04 01:30:19 25 4
gpt4 key购买 nike

我根据这篇文章对小项目使用 token 认证:http://bitoftech.net/2014/06/09/angularjs-token-authentication-using-asp-net-web-api-2-owin-asp-net-identity/

除了一件事之外,一切似乎都很好:基于 OWIN 的 token 身份验证不允许在/token 端点上进行 OPTIONS 请求。 Web API 返回 400 Bad Request,整个浏览器应用程序停止发送 POST 请求以获取 token 。

我在示例项目中在应用程序中启用了所有 CORS。下面是一些可能相关的代码:

public class Startup
{
public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; private set; }

public void Configuration(IAppBuilder app)
{
AreaRegistration.RegisterAllAreas();
UnityConfig.RegisterComponents();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);

HttpConfiguration config = new HttpConfiguration();

app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

ConfigureOAuth(app);

WebApiConfig.Register(config);

app.UseWebApi(config);

Database.SetInitializer(new ApplicationContext.Initializer());
}

public void ConfigureOAuth(IAppBuilder app)
{
//use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseExternalSignInCookie(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie);
OAuthBearerOptions = new OAuthBearerAuthenticationOptions();

OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),
Provider = new SimpleAuthorizationServerProvider(),
RefreshTokenProvider = new SimpleRefreshTokenProvider()
};

// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(OAuthBearerOptions);
}
}

下面是我的 javascript 登录功能(我为此使用了 angularjs)
var _login = function (loginData) {

var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password;

data = data + "&client_id=" + ngAuthSettings.clientId;

var deferred = $q.defer();

$http.post(serviceBase + 'token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (response) {

localStorageService.set('authorizationData', { token: response.access_token, userName: loginData.userName, refreshToken: response.refresh_token, useRefreshTokens: true });
_authentication.isAuth = true;
_authentication.userName = loginData.userName;
_authentication.useRefreshTokens = loginData.useRefreshTokens;

deferred.resolve(response);

}).error(function (err, status) {
_logOut();
deferred.reject(err);
});

return deferred.promise;
};

var _logOut = function () {

localStorageService.remove('authorizationData');

_authentication.isAuth = false;
_authentication.userName = "";
_authentication.useRefreshTokens = false;

};

最佳答案

我今天在这个问题上浪费了一些时间。最后我想我已经找到了解决方案。

覆盖 OAuthAuthorizationServerProvider 中的方法:

public override Task MatchEndpoint(OAuthMatchEndpointContext context)
{
if (context.IsTokenEndpoint && context.Request.Method == "OPTIONS")
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "authorization" });
context.RequestCompleted();
return Task.FromResult(0);
}

return base.MatchEndpoint(context);
}

这似乎做了三件必要的事情:
  • 强制身份验证服务器以 200 (OK) HTTP 状态响应 OPTIONS 请求,
  • 通过设置 Access-Control-Allow-Origin 允许来自任何地方的请求
  • 允许 Authorization通过设置 Access-Control-Allow-Headers 在后续请求中设置 header

  • 在这些步骤之后,angular 最终在使用 OPTIONS 方法请求 token 端点时表现正确。返回 OK 状态,并使用 POST 方法重复请求以获取完整的 token 数据。

    关于asp.net - OWIN token 身份验证 400 来自浏览器的 OPTIONS 的错误请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26614771/

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