您必须添加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()); }
然后,继承自的CustomAuthorizationServerProvider 的 OAuthAuthorizationServerProvider 强> class会覆盖 的 GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) 强> 。
然后,在检查用户具有正确的用户名和密码后,您必须添加
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<IList<string>> UserRoles(string userId) { IList<string> 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); }