授权角色WebAPI oauth owin
我在ASP.NET Web API上使用OWIN中间件实现了令牌授权系统。 我成功地可以使用REST客户端进行身份validation并获取授权令牌来调用API。 如果我将[Authorize]
属性放在我的控制器中的GET操作上,它也可以正常工作。 如果我没有有效的令牌,它会拒绝带有401消息的资源,但是如果我将[Authorize(Roles="admins")]
与roles
参数一起使用,则它无法识别用户的角色。 我validation了数据库中的内容,并检查了用户usersinroles
是否正确填充。
这是一段代码:
[Authorize(Roles = "admins")] public IEnumerable Get() { ClaimsPrincipal principal = Request.GetRequestContext().Principal as ClaimsPrincipal; bool isrole = principal.IsInRole("admins");
我还检查了没有roles
参数的动作,并且isrole
boolean总是为false
。 我必须启用某些function吗?
您必须添加GrantResourceOwnerCredentials方法:
identity.AddClaim(new Claim(ClaimTypes.Role, "admins"));
一步步
在StartUp.cs类中,您应该有一个自定义提供程序,如行
Provider = new CustomAuthorizationServerProvider()
例如:
public void ConfigureOAuth(IAppBuilder app) { OAuthAuthorizationServerOptions oAuthServerOptions = new OAuthAuthorizationServerOptions { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/token"), AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30), Provider = new CustomAuthorizationServerProvider() }; // Token Generation app.UseOAuthAuthorizationServer(oAuthServerOptions); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); }
然后,inheritance自OAuthAuthorizationServerProvider类的CustomAuthorizationServerProvider将覆盖GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext上下文) 。
然后,在检查用户具有正确的用户名和密码后,您必须添加
var identity = new ClaimsIdentity(context.Options.AuthenticationType); ... // other claims ... identity.AddClaim(new Claim(ClaimTypes.Role, "admins")); ... var ticket = new AuthenticationTicket(identity, properties); context.Validated(ticket);
编辑
您可以从DB获取用户角色,而不是使用“admins”编码字符串执行:
var roles = await userManager.GetRolesAsync(userId);
因此,您可以在存储库中添加以下方法:
public async Task> UserRoles(string userId) { IList roles = await userManager.GetRolesAsync(userId); return roles; }
然后从覆盖的GrantResourceOwnerCredentials中调用它,添加:
using (AuthRepository repository = new AuthRepository()) { IdentityUser user = await repository.FindUser(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect"); return; } var roles = repository.UserRoles(user.Id); }
- 带有自定义标头的MVC重定向
- 即使将身份validation模式设置为“Windows”,ASP.Net MVC4 User.Identity.Name也会变为空
- cshtml中的百分比标签
- 堆栈不足以继续安全地执行程序。 ASP.NET MVC 4
- 获取淘汰模型中的MVC人员模型书列表(可观察数组)
- 在MVC中,可以更改@ Html.DropDownListFor中每个列表项的字体(创建类似于MS office的字体下拉列表
- 使用MVC Razor传递列表对象
- Web API自定义validation,以根据已批准值列表检查字符串
- entity framework代码优先问题(SimpleMembership UserProfile表)