use*_*620 1 asp.net asp.net-mvc asp.net-mvc-5
我需要能够像这样在测试中的代码中验证我的用户身份
var identity = new GenericIdentity("ausov@fsb.ru", "UserId");
Thread.CurrentPrincipal = new GenericPrincipal(identity, null);
Run Code Online (Sandbox Code Playgroud)
或者像这样
FormsAuthentication.SetAuthCookie(username, rememberMe);
Run Code Online (Sandbox Code Playgroud)
但这些方法不适用于asp net 5.
要在ASP.NET Core中使用它,首先,使用NuGet添加Microsoft.AspNetCore.Authentication.Cookies
在Startup.cs中,将其添加到Configure方法:
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "PutANameHere",
LoginPath = new PathString("/Account/Login/"),
AutomaticAuthenticate = true,
AutomaticChallenge = true
});
Run Code Online (Sandbox Code Playgroud)
然后调用此登录:
var userClaims = new List<Claim>
{
new Claim(ClaimTypes.Name, userName)
};
var principal = new ClaimsPrincipal(new ClaimsIdentity(userClaims, "local"));
HttpContext.Authentication.SignInAsync("PutANameHere", principal);
Run Code Online (Sandbox Code Playgroud)
有关这方面的更多信息,请查看:https: //docs.asp.net/en/latest/security/authentication/cookie.html