Я работаю над веб-приложением ASP.Net, которое использует аутентификацию на основе форм. Я проверяю подлинность в домене Active Directory. Я получаю успешную аутентификацию, получение необходимой информации из AD, а затем используя Response.Redirect(), чтобы перенаправить пользователя на страницу Default.aspx приложения, но вместо этого он возвращается к Login.aspx. Я не могу понять, что происходит не так.Почему мое приложение возвращается на страницу входа после успешной аутентификации?
Вот мой Логин код (получает запускается, когда пользователь вводит свой домен, логин и пароль и нажимает кнопку «Вход»):
protected void btnLogin_Click(object sender, EventArgs e)
{
string adPath = "LDAP://my.ad.path:636";
FormsAuth.LdapAuthentication adAuth = new FormsAuth.LdapAuthentication(adPath);
bool isAuthenticated = false;
//"loggedInUser" is a class to hold information about the user
loggedInUser = adAuth.LoginAndGetRequestorLoginInfo(out isAuthenticated, tbxDomain.Text, tbxUsername.Text, tbxPassword.Text);
if (isAuthenticated)
{
//Create the ticket
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, tbxUsername.Text, DateTime.Now,
DateTime.Now.AddMinutes(60), true, tbxUsername.Text);
//Encrypt the ticket.
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
//Create a cookie, and then add the encrypted ticket to the cookie as data.
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
//Set cookie expiration to match ticket expiration
authCookie.Expires = authTicket.Expiration;
//Add the cookie to the outgoing cookies collection.
Response.Cookies.Add(authCookie);
//Store user information in session to use later
Session["verifiedUser"] = loggedInUser;
//Now redirect to default page
Response.Redirect("~/User/Default.aspx");
}
else
{
lblError.Text = "Authentication did not succeed. Please check your user name and password.";
lblError.Visible = true;
}
} //end method btnLogin_Click
Вот код аутентификации LDAP (в отдельном классе):
using System;
using System.DirectoryServices;
using System.Text;
namespace FormsAuth
{
public class LdapAuthentication
{
private string _path;
private string _filterAttribute;
public LdapAuthentication(string path)
{
_path = path;
}
public bool IsAuthenticated(string domain, string username, string pwd)
{
string domainAndUsername = domain + @"\" + username;
DirectoryEntry entry = new DirectoryEntry(_path);
try
{
//Bind to the native AdsObject to force authentication.
object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = String.Format("(SAMAccountName={0})", username);
search.PropertiesToLoad.Add("SAMAccountName");
SearchResult result = search.FindOne();
if (result == null)
{
return false;
}
//Update the new path to the user in the directory.
_path = result.Path;
_filterAttribute = (string)result.Properties["cn"][0];
}
catch (Exception ex)
{
throw new Exception("Error authenticating user. " + ex.Message);
}
return true;
}
public Requestor LoginAndGetRequestorLoginInfo(out bool isAuthenticated, string domain, string username, string pwd)
{
Requestor req = new Requestor();
DirectoryEntry entry = new DirectoryEntry(_path);
try
{
//Bind to the native AdsObject to force authentication.
object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = String.Format("(sAMAccountName={0})", username);
search.PropertiesToLoad.Add("sAMAccountName");
search.PropertiesToLoad.Add("cn");
search.PropertiesToLoad.Add("sn");
search.PropertiesToLoad.Add("givenName");
search.PropertiesToLoad.Add("employeeID");
search.PropertiesToLoad.Add("telephoneNumber");
search.PropertiesToLoad.Add("mail");
SearchResult result = search.FindOne();
if (result == null)
{
isAuthenticated = false;
return null;
}
//Populate Requestor object with results returned from directory search
if (result.Properties["sAMAccountName"] != null && result.Properties["sAMAccountName"].Count > 0)
{
req.Login = domain + "\\" + result.Properties["sAMAccountName"][0].ToString();
}
if (result.Properties["sn"] != null && result.Properties["sn"].Count > 0)
{
req.LName = result.Properties["sn"][0].ToString();
}
if (result.Properties["givenName"] != null && result.Properties["givenName"].Count > 0)
{
req.FName = result.Properties["givenName"][0].ToString();
}
if (result.Properties["employeeID"] != null && result.Properties["employeeID"].Count > 0)
{
if (result.Properties["employeeID"][0].ToString().Length > 0)
{
req.EmployeeID = Convert.ToInt32(result.Properties["employeeID"][0].ToString());
}
}
if (result.Properties["telephoneNumber"] != null && result.Properties["telephoneNumber"].Count > 0)
{
req.Phone = result.Properties["telephoneNumber"][0].ToString();
}
if (result.Properties["mail"] != null && result.Properties["mail"].Count > 0)
{
req.Email = result.Properties["mail"][0].ToString();
}
}
catch (Exception ex)
{
throw new Exception("Error authenticating user. " + ex.Message);
}
isAuthenticated = true;
return req;
} //end method LoginAndGetRequestorLoginInfo
}
}
Вы проверили, что в файле web.config вы установили авторизацию на свой корень сайта (или папку пользователя), чтобы только '?' Было отказано? Я отказался от авторизации '' 'по ошибке один раз, и это вызвало проблему, похожую на вашу. – Renan
В корневом Web.config это ' Authorization>'. В папке пользователя Web.config это ' '. Пользователь, с которым я тестирую, является членом всех трех ролей (используя SQL Membership для управления ролью). –
timbck2
Имеет ли целевая страница пользователя какой-либо код перенаправления? – Renan