2014-10-28 46 views
9

OPTIONS我使用令牌认证基于本文的小项目请求无效:http://bitoftech.net/2014/06/09/angularjs-token-authentication-using-asp-net-web-api-2-owin-asp-net-identity/OWIN令牌认证400从浏览器

一切似乎除了一两件事,做工精细:OWIN基于令牌的认证不允许OPTIONS请求on/token端点。 Web API返回400错误请求,并且整个浏览器应用程序停止发送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); 
     } 
    } 

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

    }; 

回答

-3

解决它。问题不是通过OPTIONS请求头发送访问控制请求方法

+2

正想回答你,但你解决它,很高兴我的教程和代码示例是有用的:) – 2014-10-28 21:40:43

+2

同样的问题在这里。而且我还没有理解如何解决这个问题。 – otaviosoares 2014-11-18 14:13:27

+2

我会一直很好,如果你阐述了你是如何解决这个问题..我解决了它使用@knr – Aziz 2015-07-31 15:47:57

31

我今天在这个问题上已经失去了一些时间。最后我想我已经找到了解决方案。您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); 
} 

这似乎做三件所需的东西:

  • 力auth服务器响应选项200(OK)HTTP状态请求,
  • 通过设置允许请求来自任何地方Access-Control-Allow-Origin
  • 允许Authorization头设置在subseq通过设置的向上请求Access-Control-Allow-Headers

经过这些步骤后,角度最终在使用OPTIONS方法请求令牌端点时表现正确。返回OK状态,它重复使用POST方法获取完整令牌数据的请求。

+0

感谢@knr,您的解决方案对我来说工作得很好。 我还在响应中添加了标头“允许”,给出了针对资源承认的HTTP动词列表: context.OwinContext.Response.Headers.Add(“Allow”,new [] {“GET,POST,PUT ,DELETE,HEAD“}); – 2015-07-08 08:48:06

+0

谢谢@knr,你的解决方案也适用于我。 – 2015-08-14 13:45:46

-4

这应该做的伎俩:

app.UseCors(CorsOptions.AllowAll); 
+2

请稍作解释,以便其他用户可以了解问题的原因以及解决方案的工作原理。谢谢 :) – 2015-06-23 16:36:18