Results 1 to 14 of 14

Thread: authentication works..now i need to remember!

  1. #1

    Thread Starter
    Banned jhermiz's Avatar
    Join Date
    Jun 2002
    Location
    Antarctica
    Posts
    2,492

    authentication works..now i need to remember!

    I'm a newbie to asp.net...

    Just creating a simple login page...
    I have the user name nand passwords stored in a database table.

    On the web form I have the text boxes and a check box to "Remember my Password" so they get logged in without having to authenticate themselves.

    How do I implement this "Remember Me" feature. I just want it so that when a user clicks this he / she doesnt have to type in a user name and password.

    I know it has to do with cookies, but can anyone provide example code or steps on how to do this ?

    Here is my authentication code:

    VB Code:
    1. <%@ Page Language="VB" %>
    2. <%@ import Namespace="System.Data" %>
    3. <%@ import Namespace="System.Data.SqlClient" %>
    4. <script runat="server">
    5.  
    6.     Sub Page_Load
    7.        Dim strLinkPath As String
    8.    
    9.        If Not IsPostBack Then
    10.          strLinkPath = String.Format( "Register/Register.aspx?ReturnUrl={0}", _
    11.            Request.Params( "ReturnUrl" ) )
    12.          lnkRegister.NavigateUrl = String.Format( strLinkPath )
    13.        End If
    14.     End Sub
    15.    
    16.     Sub Button_Click( s As Object, e As EventArgs )
    17.        If IsValid Then
    18.          If DBAuthenticate( txtUsername.Text, txtPassword.Text ) > 0 Then
    19.            FormsAuthentication.RedirectFromLoginPage( txtUsername.Text, False )
    20.          End If
    21.        End If
    22.     End Sub
    23.    
    24.     Function DBAuthenticate( strUsername As String, strPassword As String ) As Integer
    25.        Dim conMyData As SqlConnection
    26.        Dim cmdSelect As SqlCommand
    27.        Dim parmReturnValue As SqlParameter
    28.        Dim intResult As Integer
    29.    
    30.        conMyData = New SqlConnection( "Server=blah;UID=IMS;PWD=blah123;Database=blah" )
    31.        cmdSelect = New SqlCommand( "DBAuthenticate", conMyData )
    32.        cmdSelect.CommandType = CommandType.StoredProcedure
    33.        parmReturnValue = cmdSelect.Parameters.Add( "RETURN_VALUE", SqlDbType.Int )
    34.        parmReturnValue.Direction = ParameterDirection.ReturnValue
    35.        cmdSelect.Parameters.Add( "@username", strUsername )
    36.        cmdSelect.Parameters.Add( "@password", strPassword )
    37.        conMyData.Open()
    38.          cmdSelect.ExecuteNonQuery()
    39.          intResult = cmdSelect.Parameters( "RETURN_VALUE" ).Value
    40.        conMyData.Close()
    41.        If intResult < 0 Then
    42.          If intResult = -1 Then
    43.            lblMessage.Text = "Username Not Registered!"
    44.          Else
    45.            lblMessage.Text = "Invalid Password!"
    46.          End If
    47.        End If
    48.        Return intResult
    49.     End Function
    50.  
    51. </script>

    And I can get that part (although even after authentication it does not redirect the user . Now how do I implement the "remember my password" feature??????

  2. #2
    Frenzied Member Magiaus's Avatar
    Join Date
    Mar 2002
    Location
    swamp land
    Posts
    1,267
    i would make a cookie with the login stored (encrypted) and check for it in either OnInit or OnLoad
    Magiaus

    If I helped give me some points.

  3. #3

    Thread Starter
    Banned jhermiz's Avatar
    Join Date
    Jun 2002
    Location
    Antarctica
    Posts
    2,492
    Originally posted by Magiaus
    i would make a cookie with the login stored (encrypted) and check for it in either OnInit or OnLoad
    hmm that's nice If I understood *** you were talking about

    Does anyone have source on how to go about doing this in vb.net / asp.net.

  4. #4
    Frenzied Member Magiaus's Avatar
    Join Date
    Mar 2002
    Location
    swamp land
    Posts
    1,267
    I only have C# code..... sorry.
    Magiaus

    If I helped give me some points.

  5. #5

    Thread Starter
    Banned jhermiz's Avatar
    Join Date
    Jun 2002
    Location
    Antarctica
    Posts
    2,492
    Originally posted by Magiaus
    I only have C# code..... sorry.
    Hmm

    Not a problem...

    Anyone else?

    Its just rather sickening getting web help...there rarely is any..everyone's answer is "do this" or "do that" with no clear details at all. I see it in this asp forum and so many others...

    To be quite honest I don't think web developers are as code comfortable as application developers. I mean if or when someone posts a question for a windows / client - server or tiered type of application the first thing I do is code it and post back with my solution. You rarely if ever have that in web programming..it's almost like everyone just right clicks and does a view source and copy...no knowledge at all...

    Not aimed at anyone..just an observation...

  6. #6
    Frenzied Member Magiaus's Avatar
    Join Date
    Mar 2002
    Location
    swamp land
    Posts
    1,267

    login class

    PHP Code:
        public class LoginResults Base.BusinessObject
        
    {
            
    #region Constructors
            /// <summary>
            /// New LoginResults with a E-mail and password setup.
            /// </summary>
            /// <param name="email">Email address of the person trying to login.</param>
            /// <param name="password">Password of the person trying to login.</param>
            
    public LoginResults(){}
            
    /// <summary>
            /// Used internally by this object to perform basic login functionality.
            /// </summary>
            /// <param name="email">E-mail address of the contact trying login.</param>
            /// <param name="password">Password of the contact trying to login.</param>
            
    private LoginResults(string emailstring passwordint attempt)
            {    
    //preform login logic
                
    this._attempt attempt;
                
    this._attempt++;
                
    //debug help
                
    System.Diagnostics.Debug.WriteLine("/***********************************************");
                
    System.Diagnostics.Debug.WriteLine("*    Email:" email);
                
    System.Diagnostics.Debug.WriteLine("*    Password: " password);
                
    System.Diagnostics.Debug.WriteLine("*    Attempt: " attempt.ToString());
                
    System.Diagnostics.Debug.WriteLine("*************/");
                
    //debug
                
    password password.Trim();
                if(
    password != "" && password != null)
                {

                    
    //backdoor for WebMaster/Admin - ByPass SQL Server
                    
    if((email == "" || email == null) && (password == "" || password == " || password == "" || password == ""))
                    {    //One of the web masters is trying to use web admin override
                        #region WebMaster
                        this._iContact = new Contact();
                        this.Contact.Email = "
    zekenaulty@netnsite.com;gabrielmartin@netnsite.com";
                        this.Contact.Password = password;
                        this.Contact.Gender = "
    Male";
                        this.Contact.Birthday = new System.DateTime(1920, 10, 31, 12, 0, 0, 0);
                        this.Contact.IsActive = true;
                        this.Contact.FirstName = "
    The";
                        this.Contact.MiddleName = "
    Web";
                        this.Contact.LastName = "
    Masters";
                        this.Contact.WebURL = "
    http://netnsite.com";

                        
    this._attempt 0;
                        
    this._isAllowed true;
                        
    this._password password;

                        
    //populate permissions
                        
    _permissions = new ContactPermissionCollection();
                        return;
                        
    #endregion
                    
    }    //success
                    
    else if(email != "" && email != null)
                    {    
    //actual login code follows
                        #region Normal Contact
                        
    if(this._attempt 5)
                        {
                            
    #region Go Away Bad Person
                            
    this._isAllowed false;
                            
    this._iContact null;
                            
    this._permissions null;//new ContactPermissionCollection(((Contact)this.Contact).Key);
                            
    return;
                            
    #endregion
                        
    }
                        else
                        {
                            try
                            {
                                if(
    Helpers.Common.IsValidEmail(email))
                                {
                                    
    this._iContact = new Contact(email);
                                }
                                else
                                {
                                    
    #region Go Away Bad Person
                                    
    this._isAllowed false;
                                    
    this._iContact null;
                                    
    this._permissions null;//new ContactPermissionCollection(((Contact)this.Contact).Key);
                                    
    return;
                                    
    #endregion
                                
    }
                            }
                            catch(
    System.Exception ex)
                            {
                                if(
    ex.Message == "Invalid E-mail Address.")
                                {
                                    
    #region Go Away Bad Person
                                    
    this._isAllowed false;
                                    
    this._iContact null;
                                    
    this._permissions null;//new ContactPermissionCollection(((Contact)this.Contact).Key);
                                    
    return;
                                    
    #endregion
                                
    }
                                else
                                {
                                    throw 
    ex;
                                }
                            }
                            if(
    password == ((Contacts.Contact)this._iContact).Password)
                            {
                                
    this._isAllowed true;
                                
    this._permissions = new ContactPermissionCollection(((Contact)this.Contact).Key);
    //                            if(Business.Contacts.Employee.IsEmployee(Business.Helpers.Convert.ToContact(_iContact).Email))
    //                            {
    //                                _iContact = Business.Helpers.Convert.ToEmployee(_iContact);
    //                            }
    //                            else if()
    //                            {
                                
    return;
                            }
                            else
                            {
                                
    #region Go Away Bad Person
                                
    this._isAllowed false;
                                
    this._iContact null;
                                
    this._permissions null;//new ContactPermissionCollection(((Contact)this.Contact).Key);
                                
    return;
                                
    #endregion
                            
    }
                        }
                        
    #endregion
                    
    }
                }
                else
                {
                    
    #region Go Away Bad Person
                    
    this._isAllowed false;
                    
    this._iContact null;
                    
    this._permissions null;//new ContactPermissionCollection(((Contact)this.Contact).Key);
                    
    return;
                    
    #endregion
                
    }
            }
            
    #endregion
            #region Static Members
            /// <summary>
            /// Static/Shared method used to proccess login requests.
            /// </summary>
            /// <param name="login">LoginResults object</param>
            /// <returns>LoginResults set with the need information to validate a user login attampt.</returns>
            
    public static LoginResults Login(LoginResults login)
            {
                
    login = new LoginResults(login.Emaillogin.Passwordlogin.Attempts);
                return 
    login;
            }
            
    #endregion
            #region Properties
            
    private IContact _iContact;
            
    /// <summary>
            /// IContact object used to store contact information after login.
            /// </summary>
            /// <remarks>
            /// The IContact interface can be cast to Employee, DistributorRep, ManufacturerRep and so on.
            /// To preform the cast check the type of IContact against PKPromo.Business.Contacts.Class.
            /// This allows multi types of contacts to live in this member and still easily expose
            /// all basic contact information before a type check and cast.
            /// </remarks>
            
    public IContact Contact
            
    {
                
    get{return this._iContact;}
            }
            private 
    ContactPermissionCollection _permissions;
            
    /// <summary>
            /// The security permissions granted to this contact.
            /// </summary>
            
    public ContactPermissionCollection Permissions
            
    {
                
    get{return this._permissions;}
            }
            private 
    int _attempt 0;
            
    /// <summary>
            /// The number of time the login has been attempted.
            /// </summary>
            
    public int Attempts
            
    {
                
    get{return this._attempt;}
            }
            private 
    bool _isAllowed false;
            
    /// <summary>
            /// Bool true if login succeded and false if login failed.
            /// </summary>
            
    public bool IsAllowed
            
    {
                
    get{return this._isAllowed;}
            }
            private 
    string _email "";
            
    /// <summary>
            /// Cache E-mail for use in login.
            /// </summary>
            
    public string Email
            
    {
                
    get{return this._email;}
                
    set{this._email value;}
            }
            private 
    string _password "";
            
    /// <summary>
            /// Cache the password for use in login.
            /// </summary>
            
    public string Password
            
    {
                
    get{return this._password;}
                
    set{this._password value;}
            }
            
    #endregion
        

    i love view source
    Magiaus

    If I helped give me some points.

  7. #7
    Frenzied Member Magiaus's Avatar
    Join Date
    Mar 2002
    Location
    swamp land
    Posts
    1,267

    crypto class

    PHP Code:
        public class Crypto
        
    {
            
    #region Crypto
            
    internal static string cryptKey "                                ";  
            
    internal static string cryptIV "                ";
            
    internal static System.Security.Cryptography.RijndaelManaged rj;
            
    internal static string Encrypt(string value)
            {
                
    byte[] System.Text.ASCIIEncoding.ASCII.GetBytes(value);
                
    byte[] key System.Text.ASCIIEncoding.ASCII.GetBytes(cryptKey);
                
    byte[] iv System.Text.ASCIIEncoding.ASCII.GetBytes(cryptIV);
                
    System.IO.MemoryStream ms = new System.IO.MemoryStream();
                
    rj = new System.Security.Cryptography.RijndaelManaged();
                
    rj.Key key;
                
    rj.IV iv;

                
    System.Security.Cryptography.ICryptoTransform encrypt rj.CreateEncryptor();
                
    System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(msencryptSystem.Security.Cryptography.CryptoStreamMode.Write);

                
    cs.Write(b0b.Length);
                
    cs.FlushFinalBlock();

                
    byte[] bo ms.GetBuffer();
                
    int i 0;
                for(
    0bo.Lengthi++)
                {
                    if(
    bo[i] == 0) break;
                }
                return 
    System.Convert.ToBase64String(bo0i);
            }
            
    internal static string Decrypt(string value)
            {
                
    byte[] System.Convert.FromBase64String(value);
                
    byte[] key System.Text.ASCIIEncoding.ASCII.GetBytes(cryptKey);
                
    byte[] iv System.Text.ASCIIEncoding.ASCII.GetBytes(cryptIV);
                
    System.IO.MemoryStream ms = new System.IO.MemoryStream(b0b.Length);
                
    rj = new System.Security.Cryptography.RijndaelManaged();
                
    rj.Key key;
                
    rj.IV iv;

                
    System.Security.Cryptography.ICryptoTransform encrypt rj.CreateDecryptor();
                
    System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(msencryptSystem.Security.Cryptography.CryptoStreamMode.Read);

                
    System.IO.StreamReader sr = new System.IO.StreamReader(cs);
                return 
    sr.ReadToEnd();
            }
            
    #endregion
        

    Magiaus

    If I helped give me some points.

  8. #8
    Frenzied Member Magiaus's Avatar
    Join Date
    Mar 2002
    Location
    swamp land
    Posts
    1,267

    cookie

    that entire cookie thing is strange looking. I don't have any knowledge of it, and the documentation sucks. From what I see the you use Request.Cookies. There is no Save or load method so I asume you pass it a name and it either makes the cokkie or opens the cookie....... then you add values to the values collection or read them. I assume you could check for values by using the Values.Count...... I dunno
    Magiaus

    If I helped give me some points.

  9. #9

    Thread Starter
    Banned jhermiz's Avatar
    Join Date
    Jun 2002
    Location
    Antarctica
    Posts
    2,492

    Re: cookie

    Originally posted by Magiaus
    that entire cookie thing is strange looking. I don't have any knowledge of it, and the documentation sucks. From what I see the you use Request.Cookies. There is no Save or load method so I asume you pass it a name and it either makes the cokkie or opens the cookie....... then you add values to the values collection or read them. I assume you could check for values by using the Values.Count...... I dunno

    Hahahahahaha

    that's awesome see my point NO one knows

  10. #10
    Frenzied Member Magiaus's Avatar
    Join Date
    Mar 2002
    Location
    swamp land
    Posts
    1,267
    The documentation really does suck.....
    Magiaus

    If I helped give me some points.

  11. #11

    Thread Starter
    Banned jhermiz's Avatar
    Join Date
    Jun 2002
    Location
    Antarctica
    Posts
    2,492
    Originally posted by Magiaus
    The documentation really does suck.....
    I know that is why I said see my point.

    Like I said no offense to the web folks, but the documentation, resources, and the wealth of CRAP in .net only makes things 10x worse.

    php / mySQL is so much simpler.

  12. #12
    Frenzied Member Magiaus's Avatar
    Join Date
    Mar 2002
    Location
    swamp land
    Posts
    1,267
    It's actually kind of sad because back in the day of MSVS 98, MSDN was awsome you could find an example of most anything in MSDN. Now It like one line. You get one line of explenation and it tells you what you could have figured out by reading the name of the object.......

    The Documentation on cookies doesn't say how to load or save a cookie. It's Just like:

    Code:
    The HttpCookie class gets and sets properties of individual cookies. The HttpCookieCollection class provides methods to store, retrieve, and manage all the cookies for an entire Web application. ASP.NET code uses the intrinsic Cookies object to create cookies and add them to the cookie collection. When delivering a Web page to a client, the server sends the entire cookie collection with the Set-Cookie header.
    but after reading this again this morning and reading this

    Code:
    HttpCookieCollection Constructor  [C#]See Also
    HttpCookieCollection Class | HttpCookieCollection Members | System.Web Namespace 
    Requirements
    Platforms: Windows 2000, Windows XP Professional, Windows .NET Server family
    Language
    C#
    
    C++
    
    JScript
    
    Visual Basic
    
    Show All
    Initializes a new instance of the HttpCookieCollection class.
    
    [Visual Basic]
    Public Sub New()
    [C#]
    public HttpCookieCollection();
    [C++]
    public: HttpCookieCollection();
    [JScript]
    public function HttpCookieCollection();
    Remarks
    ASP.NET includes two intrinsic cookie collections. The collection accessible through Cookies contains cookies transmitted by the client to the server in the Cookie header. The collection accessible through Cookies contains cookies generated on the server and transmitted to the client in the Set-Cookie header.
    
    Example
    [Visual Basic, C#] The following example creates a new cookie collection object and fills it with the cookies received from the client.
    
    [Visual Basic] 
    Dim MyCookieCollection As New HttpCookieCollection()
     MyCookieCollection = Request.Cookies
    [C#] 
    HttpCookieCollection MyCookieCollection = new HttpCookieCollection();
     MyCookieCollection = Request.Cookies;
    [C++, JScript] No example is available for C++ or JScript. To view a Visual Basic or C# example, click the Language Filter button  in the upper-left corner of the page.
    I think you just add a cookie and it is load automaticly from then on...... I dunno

    If you get this working let me know
    Magiaus

    If I helped give me some points.

  13. #13
    Super Moderator Wokawidget's Avatar
    Join Date
    Nov 2001
    Location
    Headingly Occupation: Classified
    Posts
    9,632
    You can store encrypted cookies on the client PC by using:
    VB Code:
    1. Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
    2. Dim objTicket As FormsAuthenticationTicket
    3. Dim objCookie As HttpCookie
    4. Dim strReturnURL As String
    5.     If ValidateLogin() Then 'my custom function that validates login.
    6.         objTicket = New FormsAuthenticationTicket(txtUsername.Text, False, 30)
    7.         objCookie = New HttpCookie(".ASPXAUTH")
    8.         objCookie.Value = FormsAuthentication.Encrypt(objTicket)
    9.         Response.Cookies.Add (objCookie)
    10.         strReturnURL = Request.Params("ReturnURL")
    11.         If strReturnURL Is Nothing Then
    12.             Response.Redirect ("Main.aspx")
    13.         Else
    14.             Response.Redirect (strReturnURL)
    15.         End If
    16.     Else
    17.         lblMessage.Visible = True
    18.         lblMessage.Text = "Invalid username/password."
    19.     End If
    20. End Sub
    As for the "remember me bit" give me a bit of time and I'll figure it out. Almost have it now.

    Woka

  14. #14
    Super Moderator Wokawidget's Avatar
    Join Date
    Nov 2001
    Location
    Headingly Occupation: Classified
    Posts
    9,632
    I believe that doing:
    VB Code:
    1. objTicket = New FormsAuthenticationTicket(txtUsername.Text, True, 30)
    Changing False to true, will make the cookie persistant.

    You currently on MSN?
    Will be on in 20 mins.

    Try the above code.

    I'll test it when I get home.

    Woof

    PS I have learnt quite a lot of ASP.NET in the last 3 weeks, so I may be able to answer some of your questions. have written some nice forum code using XSLT and XML. Woof

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width