而当我们需要在一个独立的类库中获取存储的用户信息时,我们需要进行如下的操作
第一步,在 Startup.ConfigureServices 方法中注入 HttpContextAccessor 服务
public class Startup { public void ConfigureServices(IServiceCollection services) { // 注入 HttpContext services.AddHttpContextAccessor(); } }第二步,在你需要使用的类库中通过 Nuget 引用 Microsoft.AspNetCore.Http,之后就可以在具体的类中通过注入 IHttpContextAccessor 来获取到用户信息,当然,也可以在此处实现登录、登出的方法
namespace Sample.Infrastructure { public interface ICurrentUser { string UserName { get; } Task SignInAsync(ClaimsPrincipal principal); Task SignOutAsync(); Task SignOutAsync(string scheme); } public class CurrentUser : ICurrentUser { private readonly IHttpContextAccessor _httpContextAccessor; private HttpContext HttpContext => _httpContextAccessor.HttpContext; public CurrentUser(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor)); } public string UserName => HttpContext.User.FindFirst(ClaimTypes.Name)?.Value; public Task SignInAsync(ClaimsPrincipal principal) => HttpContext.SignInAsync(principal); public Task SignOutAsync() => HttpContext.SignOutAsync(); public Task SignOutAsync(string scheme) => HttpContext.SignOutAsync(scheme); } }至此,整块的认证功能就已经实现了,希望对你有所帮助
ReferenceSameSite cookies
Work with SameSite cookies in ASP.NET Core
What does the CookieAuthenticationOptions.LogoutPath property do in ASP.NET Core 2.1?
理解ASP.NET Core验证模型(Claim, ClaimsIdentity, ClaimsPrincipal)不得不读的英文博文
Introduction to Authentication with ASP.NET Core