ASP.NET Core是一个跨平台的开源Web应用框架,用于开发高性能和可扩展的Web应用程序。在ASP.NET Core中,CookieAuthentication是一种身份验证方案,用于通过Cookie对用户进行身份验证和授权。

一、配置身份验证中间件

在ASP.NET Core 2.0中使用CookieAuthentication需要在Startup.cs文件的ConfigureServices方法中进行配置。首先,在引用命名空间后,使用AddAuthentication方法启用身份验证中间件,并且指定默认的验证方案为CookieAuthentication。代码示例如下:

using Microsoft.AspNetCore.Authentication.Cookies; 

// ...

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
            options.Cookie.Name = "YourCookieName";
            // 配置其他选项
        });

    // 注册其他服务
    // ...
}

其中,CookieAuthenticationDefaults.AuthenticationScheme表示CookieAuthentication的默认验证方案。通过AddCookie方法可以配置CookieAuthentication的选项,比如指定Cookie的名称、是否自动刷新等。

二、在控制器中使用身份验证

在需要进行身份验证的控制器或动作方法上,使用AuthorizeAttribute进行标记。这样只有经过身份验证的用户才能访问该控制器或动作方法。代码示例如下:

[Authorize]
public class HomeController : Controller
{
    // ...
}

三、用户登录和注销

1. 用户登录

在用户登录时,通过调用SignInAsync方法来创建并发送认证Cookie。代码示例如下:

public async Task Login(LoginViewModel model)
{
    // 验证用户身份
    if (IsValidUser(model))
    {
        ClaimsIdentity identity = new ClaimsIdentity(
            new[] {
                new Claim(ClaimTypes.Name, model.UserName)
                // 其他用户信息的声明
            }, CookieAuthenticationDefaults.AuthenticationScheme
        );
        
        ClaimsPrincipal principal = new ClaimsPrincipal(identity);
        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

        return RedirectToAction("Index", "Home");
    }
    else
    {
        ModelState.AddModelError("", "Invalid username or password.");
    }

    return View(model);
}

其中,ClaimsIdentity表示一个用户身份,可以在其中添加用户信息的声明,如用户名、角色等。ClaimsPrincipal表示一个用户主体,包含一个或多个身份。HttpContext.SignInAsync方法用于创建认证Cookie并将其发送给客户端。

2. 用户注销

在用户注销时,通过调用SignOutAsync方法来删除认证Cookie。代码示例如下:

public async Task Logout()
{
    await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
    return RedirectToAction("Index", "Home");
}

四、保护其他资源和使用身份验证信息

如果需要保护某些资源,只允许经过身份验证的用户访问,可以使用Authorize属性。在视图中可以通过User.Identity来获取当前用户的身份验证信息。代码示例如下:

[Authorize]
public class ProtectedController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}
@if (User.Identity.IsAuthenticated)
{
    

欢迎您,@User.Identity.Name!

您的角色:@User.Identity.GetRole()。

其他用户信息:@User.Identity.FindFirst("OtherInfo")。

} else {

请先登录。

}

在视图中,通过User.Identity.Name可以获取当前用户的用户名,User.Identity.GetRole()可以获取用户的角色,User.Identity.FindFirst("OtherInfo")可以获取其他用户信息。

通过以上几个步骤,就可以在ASP.NET Core 2.0中使用CookieAuthentication进行用户身份验证和授权。