我正在尝试确定处理我的应用程序的当前身份验证的最佳方法。我的应用程序没有任何身份验证,但在访问我的应用程序之前将从登录页面处理。如果他们成功验证我的应用程序将收到包含凭据和其他用户信息的cookie。
在整个用户会话中确定cookie是否存在的最佳方法是什么?我目前正在启动页面上阅读cookie但如果用户将页面标记为过去,则会导致问题。我应该检查每个页面请求是否存在cookie,或者当用户点击默认页面并以某种方式存储时,我可以预先检查吗?
这是我目前从cookie中抓取用户的方式
UserId = _ltpaToken.LTPATokenParse();
if (UserId == "")
{
_logger.Error("No User found");
return RedirectToPage("/Error");
}
else
{
HttpContext.Session.SetString("UserId", UserId);
return RedirectToPage();
//user is good to
}
然后在另一页上再次检查UserId
UserId = _httpContextAccessor.HttpContext.Session.GetString("UserId");
if(UserId == null)
{
Response.Redirect("ToCompanyLoginPage");
}
//continue on to page load
有一个更好的方法吗?
var currentUserName = User.Identity.Name;
无处不在,角色也是不错的选择
var currentUserRole = User.IsInRole(“Admin”);
调节器
public class PersonAuthorizationController : Controller
{
private readonly SignInManager<IdentityUser> _signInManager;
private readonly UserManager<IdentityUser> _userManager;
private readonly MainDbContext _context;
public PersonAuthorizationController(
MainDbContext context,
UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
_context = context;
}
// GET: Contact/PersonAuthorization
public async Task<IActionResult> Index()
{
var currentUserId = _userManager.GetUserId(User);
return View();
}
如果你需要除了default authentication以外的东西,你可以使用这样的东西
首先创建一个简单的用户类
public class MyCustomUser
{
public int Id { get; set; }
public string Name { get; set; }
public string GivenName { get; set; }
}
在ConfigureServices
方法中的startup.cs中
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromDays(7);
options.LoginPath = "/Account/CustomLogin";
options.Cookie.Name = "MyAuthCookieName";
}
);
在Configure
方法中的startup.cs中
app.UseAuthentication();
然后你的控制器中的SignIn
动作你可以写这样的东西,以保存用户的索赔信息(what are claims?)
//Inside your SignIn method
//User info should be taken from DB
MyCustomUser user = new MyCustomUser()
{
Id = 1,
Name = "Mr.Awesome",
GivenName = "John Doe"
};
//Add user information
List<Claim> claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.Name),
new Claim(ClaimTypes.GivenName, user.GivenName)
};
//Create the principal user from the claims
ClaimsIdentity identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
ClaimsPrincipal principal = new ClaimsPrincipal(identity);
AuthenticationProperties authenticationProperties = new AuthenticationProperties() {IsPersistent = false};
//Create the authentication cookie and store it
await this.HttpContext
.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
principal, authenticationProperties);
// DONE!