飞扬的Blog
主页
登录
asp.net core3 多站点利用cookie单点登录注销
"date"
:
"2020-06-15 03:29:47"
"classfiy"
:
"asp.net core"
"author"
:
"飞扬"
"viewTimes"
:
273
返回
#### 1. Startup.cs 中配置 - ConfigureServices 方法内新增: ```csharp services.AddDataProtection() .PersistKeysToFileSystem(new System.IO.DirectoryInfo("{SAVE KEY PATH}"))//保存Key的目录 .SetApplicationName("{APP NAME}"); //把所有子系统都设置为统一的应用名称 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => { options.Cookie.Name = ConfigurationHelper.Get<string>("{COOKIE NAME}");//设置统一的Cookie名称 options.Cookie.Domain = ConfigurationHelper.Get<string>(".baidu.com");//设置Cookie的域为根域,这样所有子域都可以发现这个Cookie options.Cookie.Path = "/"; }); ``` - Configure 方法内新增: ```csharp app.UseAuthentication(); app.UseAuthorization(); app.UseCookiePolicy(new CookiePolicyOptions { MinimumSameSitePolicy = SameSiteMode.Strict, }); ``` #### 2. 这里配置完以后,在Login页面登陆完毕需要配置的代码: ```csharp //添加登陆状态 var claims = new List<Claim>(); claims.Add(new Claim(ClaimTypes.Name, "{User}")); var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), new AuthenticationProperties { IsPersistent = remember, ExpiresUtc = DateTime.UtcNow.AddMinutes(5) }); //注销 await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); ``` #### 3. 在其他站点想要获取已经登陆的用户在View或者Controller: ```csharp if (User.Identity.IsAuthenticated){ var user=User.Identity.Name; } ``` > “User.Identity.IsAuthenticated” 这个对象在:HttpContext、ControllerBase、Veiw等等都可以获取得到。 ------------ ####最后 > 以上三步除了**第 1 步要在主站点和其他需要共享登陆状态的站点都要配置**,后面的登陆和注销在主站点完成就行了。不过也看项目的实际需求。 官方文档传送门:[点击查看](https://docs.microsoft.com/zh-cn/aspnet/core/security/authentication/cookie?view=aspnetcore-3.1#sign-out "点击查看")