我们的大多数用户已经从更老的本地人那里登录
我们想要转移到我们的 Asp.net Core Intranet 的应用程序
网络应用程序。
您可以使用 OWIN cookie 身份验证中间件。中间件在 ASP.NET Core 中稍作改动。
仅供参考:Microsoft 正在转向基于策略的授权,而不是基于角色的授权。角色声明是为了向后兼容。如果您打算将 AuthorizeAttribute 与角色一起使用,您可能需要查看此 sample 和 usage。
https://leastprivilege.com/2016/08/21/why-does-my-authorize-attribute-not-work/
Login Action Method
在 Login 动作方法中,我们首先使用现有的身份验证机制进行身份验证。然后将用户信息和角色名传递给 SignManager 方法。
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
bool result = // Validate user
if (result)
{
var user = await _userRepository.GetUserByUserNameAsync(model.UserName);
var roleNames = (await _roleRepository.GetRolesForUser(user.Id))
.Select(r => r.Name).ToList();
await _signInManager.SignInAsync(user, roleNames);
}
else
{
ModelState.AddModelError("", "Incorrect username or password.");
}
}
return View("Login", model);
}
SigIn Manager
然后我们创建用户信息作为声明。
public class SignInManager
{
private readonly IHttpContextAccessor _httpContextAccessor;
public SignInManager(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public async Task SignInAsync(User user, IList<string> roleNames)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Sid, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.UserName),
new Claim(ClaimTypes.GivenName, user.FirstName),
new Claim(ClaimTypes.Surname, user.LastName)
};
foreach (string roleName in roleNames)
{
claims.Add(new Claim(ClaimTypes.Role, roleName));
}
var identity = new ClaimsIdentity(claims, "local", "name", "role");
var principal = new ClaimsPrincipal(identity);
await _httpContextAccessor.HttpContext.Authentication
.SignInAsync(Constants.AuthenticationScheme, principal);
}
public async Task SignOutAsync()
{
await _httpContextAccessor.HttpContext.Authentication
.SignOutAsync(Constants.AuthenticationScheme);
}
}
Startup.cs
最后,我们在 Startup.cs 中添加 cookie 身份验证中间件。
public void Configure(IApplicationBuilder app,
IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
Events = new CookieAuthenticationEvents
{
OnRedirectToAccessDenied = context =>
{
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
return TaskCache.CompletedTask;
}
},
AuthenticationScheme = Constants.AuthenticationScheme,
LoginPath = new PathString("/Account/Login"),
AccessDeniedPath = new PathString("/Common/AccessDenied"),
AutomaticAuthenticate = true,
AutomaticChallenge = true
});
...
}