简体   繁体   中英

How do I build a custom role based authorization in ASP Core 2?

I have a database that has a user table, access table and a join table assigning a user to multiple access. The site will verify a user by matching the Identity Username from AD with an username in the Users table to verify they can see the site (Intranet). The access table is used to specify which pages they are allow to visit.

In ASP Core 2 how can I use Authorization to perform the same check at Startup to verify they are in the Users table and then take it a step further and use Roles to allow the user access to specific web pages.

I've gone through the documentation but I can't figure out which way to go as the examples use a login that is not necessary in my case using AD.

I have a users table and don't use AD roles because we have a admin for exchange and I do not have access to that.

Thanks in advance

Authorize attribute is the what you are looking for. For example,

[Authorize(Roles = "Admin, User")]

If you are using OAuth for authentication, you will create a ClaimsIdentity while authenticating. Based on the claim, the Authorize attribute will work out of the box. For example,

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

        ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

        if (user == null)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }

        ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
           OAuthDefaults.AuthenticationType);

        AuthenticationProperties properties = CreateProperties(user.UserName);
        AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
        context.Validated(ticket);
        context.Request.Context.Authentication.SignIn(oAuthIdentity);
    }

You can refer to this post , where I have explained a similar scenario in a bit more detail.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM