Comment ajouter une autorisation basée sur les rôles

Nov 07 2020

Comment créer une fonction basée sur les rôles?

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
        try
        {
            ClyBayEntities clyBayEntitiesContext = new ClyBayEntities();
            UserFunctions userFunctions = new UserFunctions();
            // here we check whether the username and pasword is valid

            var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
            
            ApplicationUser user = await userManager.FindAsync(RijndaelEncryption.Encrypt(context.UserName.Trim()), context.Password);

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

            if (user!=null && user.LockoutEnabled==true)
            {
                Log.Info(" user exist :::  but user is lockout");
                context.SetError("invalid_grant", "The user name and/or password is incorrect.");
                return;
            }


            if (!userManager.IsPhoneNumberConfirmed(user.Id))
            {
                context.SetError("invalid_grant", "Please Confirm Your Phone Number! Number Is Not Verified Yet");
                return;
            }
            

            // Get the userdetails from the db
            User userDetails = clyBayEntitiesContext.Users.FirstOrDefault(x => x.AspNetUserId == user.Id);
            if (userDetails.IsDeleted == true)
            {
                Log.Info(" user exist :::  but IsDeleted value is true");
                context.SetError("invalid_grant", "The user name and/or password is incorrect.");
                return;
            }
            // mod: tur461
            var r = await userManager.GetRolesAsync(user.Id);
            string Role = r.Take(1).SingleOrDefault();

            if (userDetails.VerificationStatus == false)
                {
                    //context.SetError("invalid_grant", "Your Account has been suspended. Please contact Administrator.");
                context.SetError("invalid_grant", "Please contact admin to verify.");
                return;
                }


            // Here create an identity for the requesting user
            ClaimsIdentity identity = new ClaimsIdentity(context.Options.AuthenticationType);
                            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                            identity.AddClaim(new Claim("UserId", userDetails.AspNetUserId.ToString()));
                            identity.AddClaim(new Claim("Id", userDetails.ID.ToString()));
                           // identity.AddClaim(new Claim("EmailId", "Email Not Defined"));//userDetails.Email
            identity.AddClaim(new Claim("Name", userDetails.Name.ToString()));
                            identity.AddClaim(new Claim("PhoneNumber", userDetails.PhoneNo.ToString()));
                            identity.AddClaim(new Claim("RoleName", Role));

            
            AuthenticationProperties properties = CreateProperties(Role);
            AuthenticationTicket ticket = new AuthenticationTicket(identity, properties);

            context.Validated(ticket);


            userFunctions.SaveLoginActivity(userDetails.ID);
                //.Info(" identity ::: " + identity);
                return;

        }
        catch (Exception ex)
        {
            Log.Error("Start log ERROR..." + ex);
            throw;
        }
}

Réponses

1 YegorAndrosov Nov 07 2020 at 14:17

Si vous faites référence à l'action du contrôleur avec le mot de fonction , vous devez remplacer cette ligne de code

identity.AddClaim(new Claim("RoleName", Role));

avec ça

identity.AddClaim(new Claim(ClaimsType.Role, Role));

Après cela, vous devriez pouvoir utiliser AuthorizeAttributeles actions que vous souhaitez protéger.

[Authorize(Roles = "Admin")]