ASP.Net Core Cookie 身份验证

Posted cc1027cc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 代码:
    /// <summary>
    /// 登录 
    /// </summary>
    [HttpPost]
    public async Task<IActionResult> 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 );
        
        //...
    

    /// <summary>
    /// 退出登录
    /// </summary>
    public async Task<IActionResult> Logout()
    
        await HttpContext.SignOutAsync();
    

以上是关于ASP.Net Core Cookie 身份验证的主要内容,如果未能解决你的问题,请参考以下文章