User.Identity.IsAuthenticated always false in .net core custom authentication

情到浓时终转凉″ 提交于 2019-12-30 04:28:05

问题


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


回答1:


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");



回答2:


In my case the problem was in the startup file. app.UseAuthentication() line was coming after app.UseMvc() line.I reversed the orders and it started to work.




回答3:


You can try this one. I think this can help

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




回答4:


I know this question was asked a long time ago, but it might be useful to another person.

Using app.UseAuthentication(); right before app.UseAuthorization(); inside the Configure method in the Startup.cs class fixed it for me.



来源:https://stackoverflow.com/questions/45261732/user-identity-isauthenticated-always-false-in-net-core-custom-authentication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!