首页 > 解决方案 > 如何添加基于角色的授权

问题描述

如何创建基于角色的功能?

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

标签: c#asp.net-mvc

解决方案


如果使用功能词引用控制器动作,则需要替换这行代码

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

有了这个

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

之后,您应该能够AuthorizeAttribute在要保护的操作上使用。

[Authorize(Roles = "Admin")]

推荐阅读