Sam
Sam

Reputation: 1343

OAuth token authorization (request has been denied)

I have a WebApi 2 and a MVC Web project in the same solution running on different IIS ports. After recieving my Oauth token using jQuery AJAX I still get a 401 Unauthorized error message when trying to call an authorized Controller method.

enter image description here

Startup:

public void Configuration(IAppBuilder app)
{
    HttpConfiguration httpConfig = new HttpConfiguration();
    ConfigureOAuthTokenGeneration(app);
    ConfigureOAuthTokenConsumption(app);
    ConfigureWebApi(httpConfig);
    app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
    app.UseWebApi(httpConfig);
}

CustomOAuthProvider:

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
    var userManager = context.OwinContext.GetUserManager<UserManager>();
    User user = await userManager.FindAsync(context.UserName, context.Password);

    // checks with context.SetError() results.

    ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");
    oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, "User"));

    var ticket = new AuthenticationTicket(oAuthIdentity, null);
    context.Validated(ticket);
}

Thinks I've tried from I get "Authorization has been denied for this request." error message when using OWIN oAuth middleware (with separate Auth and Resource Server):

  1. Updating all the Owin packages to latest version (Web project does not use any Owin functionality so it is not installed here).
  2. Api and web are different projects but on same machine, so same machinekey.
  3. OAuth Token configuration comes before the WebApi configuration in Startup.cs.
  4. Claims are made: oAuthIdentity consist out of a role and an admin claim (http://schemas.microsoft.com/ws/2008/06/identity/claims/role: User)

Everything else works as expected (web api, cors, token generation,...), what am I doing wrong? (There is a lot of code involved, so let me know if I need to place an other piece of code from my projects.

EDIT:

Ajax call (Solution by jumuro):

var token = sessionStorage.getItem(tokenKey); // Same as the generated login token
$.ajax({
    type: 'POST',
     // Don't forget the 'Bearer '!
    beforeSend: function (xhr) { xhr.setRequestHeader('Authorization', 'Bearer ' + token) },
    url: 'http://localhost:81/api/auth/test', // Authorized method
    contentType: 'application/json; charset=utf-8'
}).done(function (data) {
    //
});

Upvotes: 4

Views: 2550

Answers (1)

jumuro
jumuro

Reputation: 1532

You have to include an Authorization header with the bearer token in the ajax call. Please see this reponse as an example. I hope it helps.

Upvotes: 1

Related Questions