.net核心自定义身份验证中的User.Identity.IsAuthenticated始终为false [英] User.Identity.IsAuthenticated always false in .net core custom authentication

查看:757
本文介绍了.net核心自定义身份验证中的User.Identity.IsAuthenticated始终为false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以检查下面的代码,让我知道为什么我总是虚假(User.Identity.IsAuthenticated)吗??我在浏览器上正确获取了cookie,并且 能够从Claim中获取价值,但"User.Identity.IsAuthenticated"始终为假.

Can anyone please check below code and let me know why I'm getting always false (User.Identity.IsAuthenticated)??. I'm getting cookie on my browser properly and able to get value from Claim but "User.Identity.IsAuthenticated" always false.

public async Task<IActionResult> Login(string phoneNumber, int otp, string returnUrl)
    {
        if (this.accountService.ValidateOTP(phoneNumber, otp))
        {
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.MobilePhone, phoneNumber),
                new Claim(ClaimTypes.Name, phoneNumber)
            };
            var userIdentity = new ClaimsIdentity();
            userIdentity.AddClaims(claim);
            ClaimsPrincipal userPrincipal = new ClaimsPrincipal(userIdentity);

            await HttpContext.Authentication.SignOutAsync("MyCookieMiddlewareInstance");
            await HttpContext.Authentication.SignInAsync("MyCookieMiddlewareInstance", userPrincipal,
                new AuthenticationProperties
                {
                    ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
                    IsPersistent = false,
                    AllowRefresh = false
                });

            if (string.IsNullOrWhiteSpace(returnUrl))
            {
                return RedirectToAction("Create", "Ad");
            }
            else
            {
                return Redirect(returnUrl);
            }
        }

        return BadRequest();
    }

推荐答案

ClaimsIdentity.IsAuthenticatedClaimsIdentity.AuthenticationType为空或为空时返回false.为了避免这种情况,请停止使用无参数的ClaimsIdentity构造函数,并使用接受authenticationType参数的重载:

ClaimsIdentity.IsAuthenticated returns false when ClaimsIdentity.AuthenticationType is null or empty. To avoid that, stop using the parameterless ClaimsIdentity constructor and use the overload accepting an authenticationType parameter:

var userIdentity = new ClaimsIdentity("Custom");

这篇关于.net核心自定义身份验证中的User.Identity.IsAuthenticated始终为false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆