.net核心如何使用User.Identity.IsAuthenticated

时间:2018-03-14 10:51:22

标签: c# asp.net-core asp.net-core-identity

我一步步使用MSDB创建身份验证cookie

步骤1.设置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();
}

步骤2.向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);

获取User.Identity.IsAuthenticated

的其他行动的最后一步

但是状态总是假如何修复问题?

This is my source code

1 个答案:

答案 0 :(得分:1)

你可以试试这个

var claims = new List<Claim>
                {
                    new Claim("user", ""),
                    new Claim("role", "Member")
                };

            HttpContext.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity(claims, SysBase.cookieName, "user", "role")));