在上下文中添加角色

时间:2019-05-24 16:15:49

标签: c# .net asp.net-web-api oauth claims-based-identity

我有以下代码可以很好地进行身份验证

 // POST api/Account/AddExternalLogin
        [Route("AddExternalLogin")]
        public async Task<IHttpActionResult> AddExternalLogin(AddExternalLoginBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

            AuthenticationTicket ticket = AccessTokenFormat.Unprotect(model.ExternalAccessToken);

            if (ticket == null || ticket.Identity == null || (ticket.Properties != null
                && ticket.Properties.ExpiresUtc.HasValue
                && ticket.Properties.ExpiresUtc.Value < DateTimeOffset.UtcNow))
            {
                return BadRequest("External login failure.");
            }

            ExternalLoginData externalData = ExternalLoginData.FromIdentity(ticket.Identity);




            if (externalData == null)
            {
                return BadRequest("The external login is already associated with an account.");
            }



            IdentityResult result = await UserManager.AddLoginAsync(User.Identity.GetUserId(),
                new UserLoginInfo(externalData.LoginProvider, externalData.ProviderKey));

             await UserManager.AddClaimAsync(ticket.Identity.GetUserId(), new Claim(ClaimTypes.Role, "Admin123"));



            if (!result.Succeeded)
            {
                return GetErrorResult(result);
            }

            return Ok();
        }

我在上面的代码中添加了一行,将角色“ Admin123”添加到上下文中,如下所示。

 await UserManager.AddClaimAsync(ticket.Identity.GetUserId(), new Claim(ClaimTypes.Role, "Admin123"));

但是我无法使用authorize(roles =“ Admin123”)

进行验证

我在做什么错?

0 个答案:

没有答案