ASP.Net Core Cookie 身份验证

创建Cookie身份验证

  • Starup.cs 代码:
    public void ConfigureServices(IServiceCollection services)
    {
        //...

        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        })
        .AddCookie();

        //...
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        // ...

        app.UseAuthentication();

        //...
    }
  • AccountController.cs 代码:
    /// 
    /// 登录 
    /// 
    [HttpPost]
    public async Task Login(string account, string password, string returnUrl)
    {
        //...

        var claimIdentity = new ClaimsIdentity("cookie");
        claimIdentity.AddClaim(new Claim(ClaimTypes.Name, "1"));
        await HttpContext.SignInAsync(
            new ClaimsPrincipal(claimIdentity),
            new AuthenticationProperties { IsPersistent = true });
        
        //...
    }

    /// 
    /// 退出登录
    /// 
    public async Task Logout()
    {
        await HttpContext.SignOutAsync();
    }

转载于:https://www.cnblogs.com/cc1027cc/p/11439990.html

你可能感兴趣的:(ASP.Net Core Cookie 身份验证)