我使用表單身份驗證的LightSwitch 2011 Web應用程序出現問題。LS 2011 Web應用程序中自己的AD表單身份驗證問題
我已經實現了我自己的登錄屏幕,可以根據活動目錄對用戶進行身份驗證。我的代碼還會檢查用戶是否分配給特定的活動目錄組,以決定是否可以添加/編輯/刪除數據。
登錄表單放置在Login.aspx頁面上。登錄按鈕保持以下代碼:
protected void buttonLogin_Click(object sender, EventArgs e)
{
LdapAuthentication authentication = new LdapAuthentication();
try
{
bool isUserAdmin = false;
if (authentication.IsUserAuthenticated(textBoxUserName.Text, textBoxPassword.Text, ref isUserAdmin))
{
FormsAuthenticationTicket authenticationTicket = new FormsAuthenticationTicket(1,
textBoxUserName.Text, DateTime.Now, DateTime.Now.AddSeconds(1), false, String.Empty);
//Encrypt the ticket.
string encryptedTicket = FormsAuthentication.Encrypt(authenticationTicket);
//Create a cookie, and then add the encrypted ticket to the cookie as data.
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
//Add the cookie to the outgoing cookies collection.
Response.Cookies.Add(authCookie);
//If the everyoneAdmin is set to true the validation of the administratorgroup
//is decativated so we have to grant the current user administrator rights
if (everyoneAdmin)
isUserAdmin = true;
Session["isUserAdmin"] = isUserAdmin ;
Response.Redirect("default.htm");
}
}
catch (Exception ex)
{
labelError.Text = ex.Message;
labelError.Visible = true;
textBoxPassword.Text = String.Empty;
}
}
public bool IsUserAuthenticated(String userName, String password, ref bool isUserAdmin)
{
if (String.IsNullOrEmpty(userName) || String.IsNullOrEmpty(password))
return false;
String domain = String.Empty;
if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["Domain"]))
domain = Convert.ToString(ConfigurationManager.AppSettings["Domain"]).Trim();
else
throw new NullReferenceException("The Domain in the configuration must not be null!");
String ldpa = String.Empty;
if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["LDPA"]))
ldpa = String.Format("LDAP://{0}", Convert.ToString(ConfigurationManager.AppSettings["LDPA"]).Trim());
else
throw new NullReferenceException("The LDPA in the configuration must not be null!");
String administrationGroup = String.Empty;
if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["AdministratorGroup"]))
administrationGroup = Convert.ToString(ConfigurationManager.AppSettings["AdministratorGroup"]).Trim();
else
throw new NullReferenceException("The AdministrationGroup in the configuration must not be null!");
String domainUserName = String.Format(@"{0}\{1}", domain.Trim(), userName.Trim());
DirectoryEntry directoryEntry = new DirectoryEntry(ldpa, domainUserName, password);
try
{
//Bind to the native AdsObject to force authentication.
object obj = directoryEntry.NativeObject;
DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry);
directorySearcher.Filter = String.Format("(SAMAccountName={0})", userName.Trim());
directorySearcher.PropertiesToLoad.Add("cn");
directorySearcher.PropertiesToLoad.Add("memberOf");
SearchResult directorySearchResult = directorySearcher.FindOne();
//unable to find a user with the provided data
if (directorySearchResult == null)
return false;
if (directorySearchResult.Properties["memberof"] != null)
{
//If the memberof string contains the specified admin group
for (int i = 0; i < directorySearchResult.Properties["memberof"].Count; i++)
{
string temp = directorySearchResult.Properties["memberof"].ToString();
// get the group name, for example:
if (directorySearchResult.Properties["memberof"].ToString().ToLower().Contains(administrationGroup.ToLower()))
{
isUserAdmin = true;
break;
}
}
}
}
catch (Exception ex)
{
throw new Exception(String.Format("Error authenticating user.\n\rMessage:\n\r {0}", ex.Message));
}
return true;
}
在保持我實現以下方法CanExcecute
(服務器層)方法的類:
public bool IsCurrentUserAdmin()
{
if (HttpContext.Current.Session["isUserAdmin"] == null)
return false;
return (bool)(HttpContext.Current.Session["isUserAdmin"]);
}
例如, CanExcecute
方法爲一個表
partial void dtFacilities_CanDelete(ref bool result)
{
result = this.IsCurrentUserAdmin();
}
partial void dtFacilities_CanInsert(ref bool result)
{
result = this.IsCurrentUserAdmin();
}
partial void dtFacilities_CanUpdate(ref bool result)
{
result = this.IsCurrentUserAdmin();
}
個WebConfig
<authentication mode="Forms">
<form>s name=".ASPXAUTH"
loginUrl="Login.aspx"
protection="All"
timeout="30"
path="/"
requireSSL="false"
slidingExpiration="true"
defaultUrl="Home.aspx"
cookieless="UseUri" />
</authentication>
<authorization>
<deny users="?">
</deny></authorization>
問題:
的問題是,如果用戶空閒的時間超過了
timeout
會話超時長。所以,會話令牌isUserAdmin
是NULL
。此時我希望應用程序返回到登錄屏幕。 AResponse.Redirect
和Server.Transfer
在IsCurrentUserAdmin()
方法中不起作用。如果會話令牌isUserAdmin
爲NULL
?我怎樣才能讓應用程序將用戶返回到登錄屏幕?請記住,會話令牌設置在login.aspx
頁面代碼後面當用戶關閉Lightswitch應用程序的最終選項卡時,應用程序將打開一個新選項卡並瀏覽過去的登錄頁面,並自動登錄而不處理登錄過程在
login.aspx
頁面。這意味着會話令牌isUserAdmin
是NULL
。即使用戶在關閉應用程序的最終選項卡之前尚未登錄,也會發生這種情況。這又導致問題1.
在此先感謝!
感謝您的答覆的方法不會對我實施工作。問題是,我不能使用HtmlPage.Window.Navigate,因爲我不能引用System.Windows.Browser。爲了清楚起見,在這裏實現了IsCurrentUserAdmin()方法(鏈接到一張圖片來清除它):也許我的方法不是正確的方式,我必須重新考慮它?! –
2012-08-13 14:19:35
也許我的解決方案是過度殺傷。如果你只是調用'FormsAuthentication.SignOut(); Response.Redirect(「default.htm」);'來自'IsCurrentUserAdmin()',甚至是'CanExecute'代碼本身?這應該只需要'System.Web.Security',它應該在'DataService'代碼中可用。 – 2012-08-13 15:32:15
這就是我試過的......但它不起作用。該網站只是加載,並沒有重定向到登錄頁面..我不知道爲什麼,但我想我會在未來避免ls。 :) – 2012-08-13 16:30:45