Trevi Awater
Trevi Awater

Reputation: 2407

Response headers not setting on OwinContext

I have created a web api that uses the JWT system using this article here. When calling the API from a REST client it works just fine. However when trying to access it from a browser it gives a CORS error since it doesn't send out the correct response headers.

Startup.cs

app.UseCors(CorsOptions.AllowAll);

Note that on my controllers CORS works just fine, it just breaks for the 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);
}

However after making the call to obtain the token, I only get back these response 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

Is there something I'm doing wrong?

Upvotes: 1

Views: 1651

Answers (2)

Rajat
Rajat

Reputation: 422

Make sure you allow CORS in web config

<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>

Upvotes: 0

Federico Dipuma
Federico Dipuma

Reputation: 18295

Note: I'm assuming you are using the same Startup.cs code defined in the liked tutorial.

Try to move the call to app.UseCors(CorsOptions.AllowAll); at the top of your Configuration method in Startup.cs:

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

   HttpConfiguration config = new HttpConfiguration();

   // Web API routes
   config.MapHttpAttributeRoutes();

   ConfigureOAuth(app);

   app.UseWebApi(config);

}

In Owin every middleware in the pipeline is executed only if the preceding passes through the invocation. For this reason app.UseCors is executed only after the AuthenticationMiddleware (in your case OAuthAuthorizationServer) and only if it does not stop the flow in the pipeline (e.g. OAuth returns a response).

Moving the Cors middleware declaration before other middlewares ensures you that it is executed for each request.

Upvotes: 1

Related Questions