我在不同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软件包更新到最新版本(Web项目不使用任何Owin功能,因此不在此处安装).
> Api和Web是不同的项目,但在同一台机器上,所以同样的机器密钥.
> OAuth令牌配置在Startup.cs中的WebApi配置之前.
>声明:oAuthIdentity由角色和管理员声明组成(http://schemas.microsoft.com/ws/2008/06/identity/claims/role:用户)
其他一切都按预期工作(web api,cors,token generation,……),我做错了什么? (涉及到很多代码,所以如果我需要从我的项目中添加其他代码,请告诉我.
编辑:
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) { // });
解决方法
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。