Search code examples
c#asp.net-coreasp.net-core-identity

.net Core how to use User.Identity.IsAuthenticated


I step by step with MSDB to creating an authentication cookie

step 1. setting start.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
               CookieAuthenticationDefaults.AuthenticationScheme;

            );
            services.AddDbContext<CoreContext>(options =>
                  options.UseSqlServer(Configuration.GetConnectionString("DB")));

            services.AddMvc();
}

step 2. add claims to ClaimsIdentity()

 var claims = new List<Claim>
                {
                new Claim(ClaimTypes.MobilePhone, ""),
                new Claim(ClaimTypes.Name, "")
                };
 var userIdentity = new ClaimsIdentity("Custom");
 userIdentity.AddClaims(claims);
 ClaimsPrincipal userPrincipal = new ClaimsPrincipal(userIdentity);
 HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal);

last step on other action to get User.Identity.IsAuthenticated state

but state always false how to fix problem?

This is my source code


Solution

  • you can try this

    var claims = new List<Claim>
                    {
                        new Claim("user", ""),
                        new Claim("role", "Member")
                    };
    
                HttpContext.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity(claims, SysBase.cookieName, "user", "role")));