Reputation: 1343
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.
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):
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