User.Identity.IsAuthenticated在.net核心自定义身份验证中始终为false

时间:2017-07-23 05:15:37

标签: asp.net-core asp.net-core-mvc

任何人都可以查看下面的代码,让我知道为什么我总是假的(User.Identity.IsAuthenticated)??我正确地在浏览器上获取cookie  能够从索赔获得价值但是" User.Identity.IsAuthenticated"总是假的。

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

enter image description here

4 个答案:

答案 0 :(得分:16)

ClaimsIdentity.IsAuthenticated为空或空时,

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

var userIdentity = new ClaimsIdentity("Custom");

答案 1 :(得分:2)

就我而言,问题出在启动文件中。 app.UseAuthentication()行紧接app.UseMvc()行。我撤消了订单,它开始起作用。

答案 2 :(得分:0)

您可以尝试这个。我认为这可以帮助

var userIdentity = new ClaimsIdentity( claims, AuthenticationTypes.Basic);

答案 3 :(得分:0)

我知道这个问题是很久以前问过的,但这对另一个人可能有用。

在Startup.cs类的Configure方法中,在app.UseAuthentication();之前使用app.UseAuthorization();为我修复了该问题。