Я осмотрелся и не могу найти краткие шаги, которые мне нужно предпринять для реализации аутентификации на моем веб-сайте. Я использую C # 3.5 с бэкэндом SQL Server.
В моей базе данных есть таблица User и UserRole.
В моем приложении 5 каталогов, содержащих страницы aspx.
Администратор
Общее
UserRole1
UserRole2
Открытый
Мне нужна защита на основе ролей для Admin, UserRole1 и UserRole2.
Мой web.config выглядит так ...
<system.web>
<authentication mode="Forms">
<forms name=".Authentication" loginUrl="UI/Common/Login.aspx" protection="All" path="/" timeout="30" />
</authentication>
...
</sytem.web>
<location path="UI/Admin">
<system.web>
<authorization>
<allow roles="Admin"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
<location path="UI/UserRole1">
<system.web>
<authorization>
<allow roles="UserRole1"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
<location path="UI/UserRole2">
<system.web>
<authorization>
<allow roles="UserRole2"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
Я разместил элемент управления для входа на своей странице Login.aspx, и мой Login.aspx.cs в настоящее время выглядит так.
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
if ((from u in db.Users where u.UserName == Login1.UserName select u).Count() == 1)
{
User user = (from u in db.Users where u.UserName == Login1.UserName select u).First();
//custom Encryption class, returns true if password is correct
if (Encryption.VerifyHash(Login1.Password, user.Salt, user.Hash))
{
string myRole = (from ur in user.UserRoles where ur.UserRoleID == user.UserRoleID select ur.Role).First();
//???
}
else
{
e.Authenticated = false;
}
}
else
{
e.Authenticated = false;
}
}
Энн, и я застрял, я не знаю, как сказать моему приложению, какова роль моего пользователя.
Пожалуйста, помогите мне:)
Спасибо!
Edit:
Я изменил свой код события Authenticate на
string role = (from ur in user.UserRoles where ur.UserRoleID == user.UserRoleID select ur.Role).First();
if (!Roles.RoleExists(role))
Roles.CreateRole(role);
if (Roles.FindUsersInRole(role, user.UserName).Length == 0)
Roles.AddUserToRole(user.UserName, role);
e.Authenticated = true;
string returnUrl = Request.QueryString["ReturnUrl"];
if (returnUrl == null) returnUrl = "/";
Response.Redirect(returnUrl);
Тем не менее, я продолжаю возвращаться к экрану входа в систему.
После входа в систему Fiddler capture выглядит как
302 /Web/UI/Common/Login.aspx?ReturnUrl=%2fWeb%2fUI%2fAdmin%2fDefault.aspx
302 /Web/UI/Admin/Default.aspx
200 /Web/UI/Common/Login.aspx?ReturnUrl=%2fWeb%2fUI%2fAdmin%2fDefault.aspx
Редактировать 2:
Мне кажется, что я установил и запустил аутентификацию, но случайно получаю сообщения об ошибках канала соединения
Моя аутентификация выглядит так:
FormsAuthentication.Initialize();
if (!Roles.RoleExists(role))
Roles.CreateRole(role);
if (Roles.FindUsersInRole(role, user.UserName).Length == 0)
Roles.AddUserToRole(user.UserName, role);
e.Authenticated = true;
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
user.UserName,
DateTime.Now,
DateTime.Now.AddMinutes(30), // value of time out property
true, // Value of IsPersistent property
string.Empty,
FormsAuthentication.FormsCookiePath);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
if (ticket.IsPersistent) authCookie.Expires = ticket.Expiration;
authCookie.Secure = false; //set to true when https is enabled
Response.Cookies.Add(authCookie);
FormsAuthentication.RedirectFromLoginPage(user.UserName, true);