[英]How to change username and password in MVC 4 application using Simple membership
[英]How to require Username Password and CompanyId on WebSecurity.Login in MVC 4 application using Simple membership
我需要為不僅需要Username和Password,還需要CompanyId的用戶實現登錄。 用戶名僅對於公司是唯一的,因此可能會出現多次使用不同的companyId作為記錄的用戶名。 我試圖擴展當前的簡單成員資格提供程序,但是我想這對我不起作用( 如何使WebSecurity.Login使用用戶名或電子郵件登錄? )。 我的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;
}
}
那將如何工作?
如果您在確認用戶名和WebSecurity
詢問如何驗證用戶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;
}
結果是這樣的:
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.