[英]OAuth token authorization (request has been denied)
我在不同IIS端口上運行的同一解決方案中有一個WebApi 2和一個MVC Web項目。 在使用jQuery AJAX收到我的Oauth令牌后,我在嘗試調用授權的Controller方法時仍然收到401 Unauthorized錯誤消息。
啟動:
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);
}
我認為我已經嘗試了“此請求已被拒絕授權。” 使用OWIN oAuth中間件(具有單獨的Auth和資源服務器)時出現錯誤消息 :
其他一切都按預期工作(web api,cors,token generation,......),我做錯了什么? (涉及到很多代碼,所以如果我需要從我的項目中添加其他代碼,請告訴我。
編輯:
Ajax調用(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) {
//
});
您必須在ajax調用中包含帶有承載令牌的Authorization
標頭。 請以此響應為例。 我希望它有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.