Visualizzazione dei risultati da 1 a 2 su 2
  1. #1
    Utente bannato
    Registrato dal
    Dec 2009
    Messaggi
    43

    login - area riservata con formsauth..

    Salve, ho questo codice che uso per un mini sito in asp net 2.0 c#:

    login.aspx
    codice:
    <%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="login.aspx.cs" Inherits="login" %>
    
    <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <p class="msg">Login </p>
        
    
    <asp:Label ID="error" runat="server" Text=""></asp:Label></p>
        
    
    Email<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></p>
        
    
    Password<asp:TextBox ID="txtPass" runat="server"></asp:TextBox></p>
        
    
    <asp:Button ID="BtnLogin" runat="server" Text="Login" onclick="BtnLogin_Click" /></p></asp:Content>
    e il file login.aspx.cs
    codice:
    using System;
    using System.Collections.Generic;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Configuration;
    using System.Data.SqlClient;
    public partial class login : System.Web.UI.Page
    {
        String connectionString = ConfigurationManager.ConnectionStrings["Personal"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
            }
        }
        public bool CheckEmail(string Email)
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                SqlCommand checkEmail = new SqlCommand("SELECT COUNT(*) FROM users WHERE Email=@Email", conn);
                checkEmail.Parameters.AddWithValue("@email", Email);
                int rows = Convert.ToInt32(checkEmail.ExecuteScalar());
                return (rows > 0);
    
            }
    
        }
        public bool CheckPassword(string Password)
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                SqlCommand checkPassword = new SqlCommand("SELECT COUNT(*) FROM users WHERE Password=@Password", conn);
                checkPassword.Parameters.AddWithValue("@password", Password);
                int rows = Convert.ToInt32(checkPassword.ExecuteScalar());
                return (rows > 0);
    
            }
    
        }
        protected void BtnLogin_Click(object sender, EventArgs e)
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                string Email = txtEmail.Text;
                string Password = txtPass.Text;
                if (CheckEmail(Email) == false)
                {
                    error.Text = "Non esiste Email";
    
                }
                else if (CheckPassword(Password) == false)
                {
                    error.Text = "Non Esiste Password";
                }
                else
                {
                    conn.Open();
                    string SQL = "SELECT * FROM users WHERE Email=@Email and Password=@Password";
                    SqlCommand reader_command = new SqlCommand(SQL, conn);
                    reader_command.Parameters.AddWithValue("@Email", txtEmail.Text);
                    reader_command.Parameters.AddWithValue("@Password", txtPass.Text);
                    SqlDataReader reader_exec = reader_command.ExecuteReader();
                    if (reader_exec.Read())
                    {
                        Session["userlogin"] = true;
                        Session["ID"] = reader_exec["ID"].ToString();
                        Session["UserName"] = reader_exec["Username"].ToString();
                        Session["Email"] = reader_exec["Email"].ToString();
                        Session["Livello"] = reader_exec["Livello"].ToString();
                        Session["Ruolo"] = reader_exec["Ruolo"].ToString();
                        Response.Redirect("members.aspx");
                    }
                    else
                    {
                        error.Text = "Non esiste nessun email e password";
                    }
                    reader_exec.Close();
                    error.Text = "GO";
                }
            }
        }
    }
    Ora chiedo ad voi come faccio ad implementarlo dentro ad questo tutorial:

    http://ondotnet.com/pub/a/dotnet/200...rmsauthp1.html

    e vi incollo qui i codici:
    codice:
    <%@ Import Namespace="System.Web.Security " %>
    <html>
      <script language="C#" runat=server>
      void Login_Click(Object sender, EventArgs E) 
      {
      
        // authenticate user: this sample accepts only one user with
        // a name of username@domain.com and a password of 'password'
        if ((UserEmail.Value == "username@domain.com") && 
            (UserPass.Value == "password")) 
        {
          FormsAuthentication.RedirectFromLoginPage(UserEmail.Value, 
                                                    PersistCookie.Checked);
        } 
        else 
        {
          lblResults.Text = "Invalid Credentials: Please try again";
        }
      }
      </script>
      <body>
        <form runat="server">
          <h3>Login Page</h3>
          <hr>
          Email:<input id="UserEmail" type="text" runat="server"/>
          <asp:RequiredFieldValidator ControlToValidate="UserEmail" 
                                      Display="Static" 
                                      ErrorMessage="*" 
                                      runat="server"/>
          
    
    Password:<input id="UserPass" 
                             type="password" 
                             runat="server"/>
          <asp:RequiredFieldValidator ControlToValidate="UserPass" 
                                      Display="Static" 
                                      ErrorMessage="*" 
                                      runat="server"/>
          
    
    Persistent Cookie:<ASP:CheckBox id="PersistCookie" 
                                             runat="server" />
          
    
    <asp:button id="cmdLogin" 
                         text="Login" 
                         OnClick="Login_Click" 
                         runat="server"/>
          
    
    <asp:Label id="lblResults" 
                        ForeColor="red" 
                        Font-Size="10" 
                        runat="server" />
        </form>
      </body>
    </html>
    Mi date una mano ad implementarlo,
    e fare dei web.config per le tre livelli "user,Manager,Admin";

    vi ringrazio molto.
    Aspetto risposte.

    Grazie.

  2. #2
    Utente bannato
    Registrato dal
    Dec 2009
    Messaggi
    43
    c'è lo fatta con un'altro tutorial:
    http://www.codeproject.com/KB/web-se...sroleauth.aspx
    e vin incollo il codice di cui avevo bisogno:

    codice:
    using System;
    using System.Collections.Generic;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Configuration;
    using System.Data.SqlClient;
    using System.Web.Security;
    public partial class login : System.Web.UI.Page
    {
        String connectionString = ConfigurationManager.ConnectionStrings["Personal"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
            }
        }
        public bool CheckEmail(string Email)
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                SqlCommand checkEmail = new SqlCommand("SELECT COUNT(*) FROM users WHERE Email=@Email", conn);
                checkEmail.Parameters.AddWithValue("@email", Email);
                int rows = Convert.ToInt32(checkEmail.ExecuteScalar());
                return (rows > 0);
    
            }
    
        }
        public bool CheckPassword(string Password)
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                SqlCommand checkPassword = new SqlCommand("SELECT COUNT(*) FROM users WHERE Password=@Password", conn);
                checkPassword.Parameters.AddWithValue("@password", Password);
                int rows = Convert.ToInt32(checkPassword.ExecuteScalar());
                return (rows > 0);
    
            }
    
        }
        protected void BtnLogin_Click(object sender, EventArgs e)
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                string Email = txtEmail.Text;
                string Password = txtPass.Text;
                if (CheckEmail(Email) == false)
                {
                    error.Text = "Non esiste Email";
    
                }
                else if (CheckPassword(Password) == false)
                {
                    error.Text = "Non Esiste Password";
                }
                else
                {
                    conn.Open();
                    string SQL = "SELECT * FROM users WHERE Email=@Email and Password=@Password";
                    SqlCommand reader_command = new SqlCommand(SQL, conn);
                    reader_command.Parameters.AddWithValue("@Email", txtEmail.Text);
                    reader_command.Parameters.AddWithValue("@Password", txtPass.Text);
                    SqlDataReader reader_exec = reader_command.ExecuteReader();
                    if (reader_exec.Read())
                    {
                        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
          1, // Ticket version
          txtEmail.Text, // 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_exec["Ruolo"].ToString(), // 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);
    
                        Session["userlogin"] = true;
                        Session["ID"] = reader_exec["ID"].ToString();
                        Session["UserName"] = reader_exec["Username"].ToString();
                        Session["Email"] = reader_exec["Email"].ToString();
                        Session["Livello"] = reader_exec["Livello"].ToString();
                        Session["Ruolo"] = reader_exec["Ruolo"].ToString();
                        // 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.Text = "Username / password incorrect. Please try again.";
                        ErrorLabel.Visible = true;
                    }
                
                    reader_exec.Close();
                }
            }
        }
    }
    grazie mille.!

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.