名宏 鄭
名宏 鄭

Reputation: 115

.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

Upvotes: 1

Views: 8612

Answers (1)

MingHong Zheng
MingHong Zheng

Reputation: 185

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

Upvotes: 1

Related Questions