在WinForms
应用程序中,我希望在应用程序生命周期内将当前登录的用户保留在内存中。因此,在后续用户操作中,我可以检查对用户的权限。另一种选择是将用户信息存储在本地文本文件中,但似乎不安全。
用户登录验证码
private void ValidateUser()
{
var hashEntered = Encryption.GetHash(_View.UserID, _View.Password); //hash of the salted password entered by user.
var User = _DataService.GetUser(_View.UserID); //user trying to log in
if (user != null)
{
var hashInDB = user.PassWord;
if (hashEntered != hashInDB)
{
MessageBox.Show("Invalid password");
}
else
{
_MainView.show();
}
}
else
{
MessageBox.Show("Invalid user name");
}
}
因此,对于MainView,当前登录的用户应该可用。
如何在程序退出之前将当前用户对象保留在内存中?
答案 0 :(得分:2)
我建议单身。
public class UserSession{
private static volatile User currentUser;
private static object syncRoot = new Object();
private UserSession() {}
public static User GetUser(){
if (currentUser == null) throw new Exception("Not logged in.");
return currentUser;
}
public static void Login(User user){
if (currentUser != null) throw new Exception("Already logged in");
lock(syncRoot){
currentUser = user;
}
}
public static void Logout(){
lock(syncRoot){
currentUser = null;
}
}
}
答案 1 :(得分:1)
您可以将用户数据存储在System.Threading.Thread.CurrentPrincipal
类型的IPrincipal
中,该Identity
也具有名为IIdentity
的属性(类型为class CustomPrincipal : IPrincipal
{
public IEnumerable<string> Roles { get; set; }
public IIdentity Identity { get; set; }
public bool IsInRole(string role)
{
// check user for appropriate roles
return false;
}
}
class CustomIdentity : IIdentity
{
public int UserId { get; set; }
public string AuthenticationType { get; set; }
public bool IsAuthenticated
{
get { return !string.IsNullOrWhiteSpace(Name); }
}
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
CustomIdentity identity = new CustomIdentity
{
UserId = 1,
Name = "user1"
};
CustomPrincipal principal = new CustomPrincipal
{
Identity = identity,
Roles = new List<string> { "admin", "superAdmin" }
};
System.Threading.Thread.CurrentPrincipal = principal;
}
}
)。这两者之间的区别在于,您只需将用户的安全关联数据(假设权限或角色)存储在主体和Identity中的其他数据中。您可以使用Microsoft已经存在的这两个接口的实现,或者您可以自己构建它们。这是一个例子
ExecutionContext
Principal是Principal
的一部分,因此它将从线程复制到线程。所以即使你要开始一个新的线程或任务或任何试图获得System.Threading.Thread.CurrentPrincipal as CustomPrincipal
的异步工作,它都会在那里
您将使用此代码而不是检索用户主体
System.Threading.Thread.CurrentPrincipal.Identity as CustomIdentity
这是为了获得用户身份
{{1}}