//app.UseIdentity();app.UseCookieAuthentication(options => {//options.AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme;// "MyCookieMiddlewareInstance";options.LoginPath = new PathString("/Account/Unauthorized/");options.AccessDeniedPath = new PathString("/Account/Forbidden/");options.AutomaticAuthenticate = true;options.AutomaticChallenge = true;});
using System.Security.Claims;using Microsoft.AspNet.Authentication.Cookies;using Microsoft.AspNet.Identity;
2、Controller中的登录代码
public async Task<IActionResult> Login(){var claims = new List<Claim>();claims.Add(new Claim(ClaimTypes.Name, "Admin")); // value of this.User.GetUserName() or this.User.Identity.Nameclaims.Add(new Claim(ClaimTypes.NameIdentifier, "10001")); // value of this.User.GetUserId();claims.Add(new Claim("SelfDefined1", "value1"));var ci = new System.Security.Claims.ClaimsIdentity(claims, IdentityCookieOptions.ApplicationCookieAuthenticationType);var cp = new System.Security.Claims.ClaimsPrincipal(ci);await HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, cp );return View("Index");}
注意,在创建ClaimsIdentity时, AuthenticationType 参数是必须的。
因为 this.User.IsSignedIn(); 是靠这个参数带验证是否登录的。
3、Controller中取登录信息的代码:
bool signed = this.User.IsSignedIn();string userName = this.User.Identity.Name;userName = this.User.GetUserName();
为了使用方便,常定义一些 ClaimsPrincipal(this.User) 的扩展方法来取各种登录时保存的变量。