C# OAuth令牌授权(请求已被拒绝)
我在同一个解决方案中有一个WebApi 2和一个MVC Web项目,在不同的IIS端口上运行。在使用jqueryajax接收到Oauth令牌后,在尝试调用授权控制器方法时,仍然会收到401未经授权的错误消息 启动:C# OAuth令牌授权(请求已被拒绝),c#,asp.net-web-api,asp.net-mvc-5,oauth-2.0,claims-based-identity,C#,Asp.net Web Api,Asp.net Mvc 5,Oauth 2.0,Claims Based Identity,我在同一个解决方案中有一个WebApi 2和一个MVC Web项目,在不同的IIS端口上运行。在使用jqueryajax接收到Oauth令牌后,在尝试调用授权控制器方法时,仍然会收到401未经授权的错误消息 启动: public void Configuration(IAppBuilder app) { HttpConfiguration httpConfig = new HttpConfiguration(); ConfigureOAuthTokenGeneration(ap
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);
}
您必须在ajax调用中包含一个带有承载令牌的
授权
头。请以此为例。
希望有帮助。我试过了,但运气不佳,你能确认我做得对吗?(编辑了我的问题)。成功了!我忘了把“持票人”放在代币前面。谢谢!
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) {
//
});