Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > .NET Frameworks (точка нет фреймворки) > ASP.NET
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 16.01.2012, 05:29   #1
escapade
 
Регистрация: 04.12.2011
Сообщений: 3
По умолчанию formsroleauth

Подскажите пожалуйста как это реализовать если я использую Entity Framework 4.0
http://www.codeproject.com/KB/web-se...sroleauth.aspx

в частости интересует вот этот вот кусок кода
Код:
private void btnLogin_Click(Object sender, EventArgs e)
{
    // Initialize FormsAuthentication, for what it's worth
    FormsAuthentication.Initialize();
 
    // Create our connection and command objects
    SqlConnection conn =
     new SqlConnection("Data Source=localhost;Initial Catalog=web;");
    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandText = "SELECT roles FROM web WHERE username=@username " +
     "AND password=@password";
 
    // Fill our parameters
    cmd.Parameters.Add("@username", SqlDbType.NVarChar, 64).Value =
Username.Value;
    cmd.Parameters.Add("@password", SqlDbType.NVarChar, 128).Value =
     FormsAuthentication.HashPasswordForStoringInConfigFile(
        Password.Value, "md5"); // Or "sha1"
 
    // Execute the command
    conn.Open();
    SqlDataReader reader = cmd.ExecuteReader();
    if (reader.Read())
    {
     // Create a new ticket used for authentication
     FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
        1, // Ticket version
        Username.Value, // Username associated with ticket
        DateTime.Now, // Date/time issued
        DateTime.Now.AddMinutes(30), // Date/time to expire
        true, // "true" for a persistent user cookie
        reader.GetString(0), // User-data, in this case the roles
        FormsAuthentication.FormsCookiePath);// Path cookie valid for
 
     // Encrypt the cookie using the machine key for secure transport
     string hash = FormsAuthentication.Encrypt(ticket);
     HttpCookie cookie = new HttpCookie(
        FormsAuthentication.FormsCookieName, // Name of auth cookie
        hash); // Hashed ticket
 
     // Set the cookie's expiration time to the tickets expiration time
     if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
 
     // Add the cookie to the list for outgoing response
     Response.Cookies.Add(cookie);
 
     // Redirect to requested URL, or homepage if no previous page
     // requested
     string returnUrl = Request.QueryString["ReturnUrl"];
     if (returnUrl == null) returnUrl = "/";
 
     // Don't call FormsAuthentication.RedirectFromLoginPage since it
     // could
     // replace the authentication ticket (cookie) we just added
     Response.Redirect(returnUrl);
    }
    else
    {
     // Never tell the user if just the username is password is incorrect.
     // That just gives them a place to start, once they've found one or
     // the other is correct!
     ErrorLabel = "Username / password incorrect. Please try again.";
     ErrorLabel.Visible = true;
    }
 
    reader.Close();
    conn.Close();
}
как бы это мне архитектуру не порушить?
escapade вне форума Ответить с цитированием
Старый 18.01.2012, 20:10   #2
Droid
Форумчанин
 
Аватар для Droid
 
Регистрация: 24.04.2008
Сообщений: 440
По умолчанию

Цитата:
Сообщение от escapade Посмотреть сообщение
Подскажите пожалуйста как это реализовать если я использую Entity Framework 4.0
http://www.codeproject.com/KB/web-se...sroleauth.aspx

в частости интересует вот этот вот кусок кода
Код:
private void btnLogin_Click(Object sender, EventArgs e)
{
    // Initialize FormsAuthentication, for what it's worth
    FormsAuthentication.Initialize();
 
    // Create our connection and command objects
    SqlConnection conn =
     new SqlConnection("Data Source=localhost;Initial Catalog=web;");
    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandText = "SELECT roles FROM web WHERE username=@username " +
     "AND password=@password";
 
    // Fill our parameters
    cmd.Parameters.Add("@username", SqlDbType.NVarChar, 64).Value =
Username.Value;
    cmd.Parameters.Add("@password", SqlDbType.NVarChar, 128).Value =
     FormsAuthentication.HashPasswordForStoringInConfigFile(
        Password.Value, "md5"); // Or "sha1"
 
    // Execute the command
    conn.Open();
    SqlDataReader reader = cmd.ExecuteReader();
    if (reader.Read())
    {
     // Create a new ticket used for authentication
     FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
        1, // Ticket version
        Username.Value, // Username associated with ticket
        DateTime.Now, // Date/time issued
        DateTime.Now.AddMinutes(30), // Date/time to expire
        true, // "true" for a persistent user cookie
        reader.GetString(0), // User-data, in this case the roles
        FormsAuthentication.FormsCookiePath);// Path cookie valid for
 
     // Encrypt the cookie using the machine key for secure transport
     string hash = FormsAuthentication.Encrypt(ticket);
     HttpCookie cookie = new HttpCookie(
        FormsAuthentication.FormsCookieName, // Name of auth cookie
        hash); // Hashed ticket
 
     // Set the cookie's expiration time to the tickets expiration time
     if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
 
     // Add the cookie to the list for outgoing response
     Response.Cookies.Add(cookie);
 
     // Redirect to requested URL, or homepage if no previous page
     // requested
     string returnUrl = Request.QueryString["ReturnUrl"];
     if (returnUrl == null) returnUrl = "/";
 
     // Don't call FormsAuthentication.RedirectFromLoginPage since it
     // could
     // replace the authentication ticket (cookie) we just added
     Response.Redirect(returnUrl);
    }
    else
    {
     // Never tell the user if just the username is password is incorrect.
     // That just gives them a place to start, once they've found one or
     // the other is correct!
     ErrorLabel = "Username / password incorrect. Please try again.";
     ErrorLabel.Visible = true;
    }
 
    reader.Close();
    conn.Close();
}
как бы это мне архитектуру не порушить?
Конечно это правильно использовать аутентификацию от MS, но я от нее отказался, в связи с их глупонастраиваемым интерфейсом, и усложненой процедурой написания криворукоизвращенного кода, в том числе и элемента управления login и мембершипа. Советую создать свою бд для хранения юзверов и всего лишь одно поле с правами, которое будет зависить от сессий.
1 старый программист, лучше новых 2-х
Droid вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц