Authorization roles WebAPI oauth owin

孤人 提交于 2019-11-30 01:43:41

You must add in GrantResourceOwnerCredentials method:

identity.AddClaim(new Claim(ClaimTypes.Role, "admins"));

Step by step

In StartUp.cs class, you should have a custom provider, like the line

Provider = new CustomAuthorizationServerProvider()

for example:

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());
}

Then, your CustomAuthorizationServerProvider that inherits from OAuthAuthorizationServerProvider class will override GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context).

Then, after checking that the user has correct UserName and Password, you must add

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);

Edited

You can get user roles from DB instead of using the "admins" harcoded string doing:

var roles = await userManager.GetRolesAsync(userId);

So you can add the following method in your repository:

public async Task<IList<string>> UserRoles(string userId)
{
    IList<string> roles = await userManager.GetRolesAsync(userId);

    return roles;
}

And then call it from your overrided GrantResourceOwnerCredentials adding:

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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!