OWIN令牌认证400来自浏览器的OPTIONS请求错误

VsM*_*MaX 11 asp.net angularjs owin asp.net-web-api2

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

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

我在应用程序中启用了所有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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

下面是我的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;

    };
Run Code Online (Sandbox Code Playgroud)

knr*_*knr 34

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

覆盖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);
}
Run Code Online (Sandbox Code Playgroud)

这似乎做了三件必要的事情:

  • 强制auth服务器以200(OK)HTTP状态响应OPTIONS请求,
  • 通过设置允许来自任何地方的请求 Access-Control-Allow-Origin
  • 允许Authorization通过设置在后续请求中设置标头Access-Control-Allow-Headers

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


VsM*_*MaX -3

解决了。问题是未使用 OPTIONS 请求标头 Access-Control-Request-Method 发送

  • 本来要回复你的,但你解决了,很高兴我的教程和代码示例很有用:) (2认同)
  • 这里同样的问题。而且我仍然不明白如何解决这个问题。 (2认同)
  • 如果您详细说明如何解决该问题,我会很高兴。我使用@knr 提出的解决方案解决了该问题 (2认同)