响应 headers 未在 OwinContext 上设置

Response headers not setting on OwinContext

我已经创建了一个网站 api,它使用本文 here 中的 JWT 系统。从 REST 客户端调用 API 时,它工作正常。但是,当尝试从浏览器访问它时,它会出现 CORS 错误,因为它没有发出正确的响应 headers.

Startup.cs

app.UseCors(CorsOptions.AllowAll);

请注意,在我的控制器上 CORS 工作正常,它只是为 OAuthAuthorizationServer 中断。

CustomOAuthProvider.cs

public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
    context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

    var user = Database.Users.FirstOrDefault(u => u.Email == context.UserName);

    if (user == null || !BCrypt.Net.BCrypt.Verify(context.Password, user.Password))
    {
        context.SetError("invalid_grant", "The user name or password is incorrect.");
        return Task.FromResult<object>(null);
    } 

    var companyId = int.Parse(context.OwinContext.Get<string>("company_id"));
    var company = user.Companies.FirstOrDefault(c => c.Id == companyId);

    if (company == null)
    {
        context.SetError("invalid_grant", "You don't belong to that company!");
        return Task.FromResult<object>(null);
    } 

    var identity = new ClaimsIdentity("JWT");
    identity.AddClaim(new Claim("uue", user.Email));

    var props = new AuthenticationProperties(new Dictionary<string, string>
    {
        { "audience", company.ServerUrl }
    });

    var ticket = new AuthenticationTicket(identity, props);

    context.Validated(ticket);
    return Task.FromResult<object>(null);
}

但是在调用获取令牌后,我只得到这些响应 headers。

Content-Length:1245
Content-Type:text/html
Date:Wed, 20 Apr 2016 20:34:40 GMT
Server:Microsoft-IIS/8.5
X-Powered-By:ASP.NET

我做错了什么吗?

注意:我假设您正在使用喜欢的教程中定义的相同 Startup.cs 代码。

尝试将调用移至 Startup.csConfiguration 方法顶部的 app.UseCors(CorsOptions.AllowAll);

public void Configuration(IAppBuilder app)
{
   app.UseCors(CorsOptions.AllowAll);

   HttpConfiguration config = new HttpConfiguration();

   // Web API routes
   config.MapHttpAttributeRoutes();

   ConfigureOAuth(app);

   app.UseWebApi(config);

}

在 Owin 中,管道中的每个中间件只有在前面的调用通过时才会执行。出于这个原因 app.UseCors 仅在 AuthenticationMiddleware 之后执行(在您的情况下 OAuthAuthorizationServer)并且仅当它不停止管道中的流程时(例如 OAuth returns 响应).

将 Cors 中间件声明移到其他中间件之前可确保它针对每个请求执行。

确保在网络配置中允许 CORS

<httpProtocol>
      <customHeaders>
        <clear />
        <add name="Access-Control-Allow-Methods" value="GET,PUT,POST,OPTIONS,DEBUG" />
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="authorization,content-type" />
      </customHeaders>
    </httpProtocol>