多个身份验证属性

时间:2019-08-14 10:43:22

标签: asp.net-web-api

我正在使用.net web-api作为我的网站。 现在,我在网站上设置了不同的身份验证属性,例如用户employee和admin。 我的问题是如何在控制器上使用多个身份验证属性?

  public class AuthFilterManager : Attribute, IAuthenticationFilter
    {
        public bool AllowMultiple => throw new NotImplementedException();


        public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
        {
            var auth = context.Request.Headers.Authorization;

            string[] UserNameAndPass = (auth.Parameter).Split(':');
            string UserName = UserNameAndPass[0];
            string Pass = UserNameAndPass[1];

            Luxury_wheelsEntities entities = new Luxury_wheelsEntities();

            Management manager = entities.Managements.FirstOrDefault(m => m.User_name == UserName);

            if (auth != null && auth.Scheme == "LuxuryWheelsLogin")
            {

                if (LoginSecurity.CheckManagerLogin(UserName, Pass))
                {

                    var Claims = new List<Claim>
                    {
                        new Claim(ClaimTypes.NameIdentifier,(manager.ID)),
                        new Claim(ClaimTypes.Name,(manager.Full_name)),
                        new Claim(ClaimTypes.Gender,(manager.Sex))
                    };

                    var identity = new ClaimsIdentity(Claims, "Token");
                    context.Principal = new ClaimsPrincipal(new[] { identity });
                }
                else
                {
                    context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request);
                }
            }
            return Task.FromResult(0);
        }

        public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
        {
            return Task.FromResult(0);
        }
    }

分别将AuthFilterEmployee和AuthFilterManager正常工作。

   [AuthFilterEmployee ]

        [AuthFilterManager] 
        [Authorize]

        public IEnumerable<User> Get()
        {
            return LuxuryWheelsDB.Users;
        }

0 个答案:

没有答案