Поскольку документация по этому процессу очень расплывчата и запутана (или устарела), я хотел убедиться, что я делал это правильно и не пропустил ни одного шага.
Я пытаюсь создать безопасную систему входа в систему, срок действия которой истекает при закрытии браузера.
- в моем web.config у меня есть следующее -
<authentication mode="Forms">
<forms loginUrl="~/Login.aspx" defaultUrl="Index.aspx" name=".ASPXFORMSAUTH" timeout="100" />
</authentication>
<authorization>
<allow users="?" />
</authorization>
<machineKey decryption="AES" validation="SHA1" validationKey.......... />
Итак, у меня есть форма входа с текстовым полем имени пользователя / пароля и этой кнопкой:
<asp:Button ID="LoginButton" runat="Server" OnClick="Login_Authenticate" Text="Sign in" />
Внутри Login_Authenticate я делаю следующее:
protected void Login_Authenticate(object sender, EventArgs e){
string userName = UserName.Text;
string password = Password.Text;
bool Authenticated = false;
// Here's code that makes sure that Username and Password is CORRECT
if(AuthClass.Authenticate(userName, password)){
Authenticated = true;
}
// error checking does happen here.
if (Authenticated)
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(30), rememberUserName, String.Empty, FormsAuthentication.FormsCookiePath);
string encryptedCookie = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedCookie);
cookie.Expires = DateTime.Now.AddMinutes(30);
Response.Cookies.Add(cookie);
//FormsAuthentication.RedirectFromLoginPage(userName, false);
Response.Redirect("MainPage.aspx");
}
}
--- в MasterPage.master.cs у меня есть следующая проверка в Page_Init () ---
if (Context.User.Identity.IsAuthenticated)
{
int userid = (int)Session["userid"];
if (userid == null)
{
userid = GetUserID(Context.User.Identity.Name);
if (userid != null)
{
Session["userid"] = userid;
}
}
}
EDIT: --- GLOBAL.ASAX; какой-то код, в котором я не совсем уверен, что он верен или знаю, что он делает
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
// look if any security information exists for this request
if (HttpContext.Current.User != null)
{
// see if this user is authenticated, any authenticated cookie (ticket) exists for this user
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
// see if the authentication is done using FormsAuthentication
if (HttpContext.Current.User.Identity is FormsIdentity)
{
// Get the roles stored for this request from the ticket
// get the identity of the user
FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity;
//Get the form authentication ticket of the user
FormsAuthenticationTicket ticket = identity.Ticket;
//Get the roles stored as UserData into ticket
string[] roles = { };
//Create general prrincipal and assign it to current request
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(identity, roles);
}
}
}
}
- с этого момента на каждой странице я использую идентификатор пользователя сеанса для сбора информации и содержимого пользователя и обеспечения надлежащей аутентификации пользователя и разрешения группы-роли.
Это все правильно? Или мне нужно где-то что-нибудь расшифровать?
Достаточно ли этого для безопасного входа пользователя? Или мне не следует беспокоиться о проверке подлинности с помощью форм и найти собственный способ создавать собственные файлы cookie и управлять ими самостоятельно?