我需要为不仅需要用户名和密码,还需要CompanyId的用户实施登录。用户名仅对公司是唯一的,因此可能会出现多次使用不同companyId作为记录的用户名。我试图扩展我目前的简单会员提供者,但我想这对我不起作用(How to make WebSecurity.Login to login using username or email?)。我的UserProfile表看起来像这样
[Table("UserProfile")]
public partial class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public int CompanyId { get; set; }
我可以通过userId和密码验证用户吗?我需要做这样的事情:
public class ExtendedSimpleMembershipProvider : SimpleMembershipProvider
{
public override bool ValidateUser(string username, string password, int companyId)
{
int userId = GetUserId(username, companyId);
return SomehowValidateUser(userId, password);
}
private int GetUserId(string username, int companyId)
{
var userId = (from users
in context.UserProfile
where (users.UserName.ToLower() == username) || (users.CompanyId == companyId)
select users.UserId).First();
return userId;
}
}
那会怎么样?
答案 0 :(得分:1)
如果您在验证用户名和companyId后询问如何验证用户ID和密码,请尝试直接公开WebSecurity
类。
public override bool ValidateUser(string username, string password, int companyId)
{
// DEV NOTE: change your GetUserId() return to int?
int? userId = GetUserId(username, companyId);
if (userID.HasValue())
return WebSecurity.Login(username, password);
else
return false;
}
答案 1 :(得分:0)
这样做了:
public static bool ValidateUser(string username, string password, string companyName)
{
int companyId = MyRepository.GetCompanyIdByName(companyName);
int? userId = companyId == 0 ? null : MyRepository.GetUserId(username, companyId);
if (userId.HasValue && userId.Value != 0)
{
var userKey = username + "@" + companyName.ToLower();
return WebSecurity.Login(userKey, password);
}
else
{
return false;
}
}