ASP.NET Membership: how to set the user as logged in

77,578

Solution 1

Put this in Login1_Authenticate before calling Response.Redirect("/admin/default.aspx");

FormsAuthentication.SetAuthCookie("username", true);

Solution 2

Try moving your code and Gromer's suggestion to the LoggedIn event.

protected void Login1_LoggedIn(object sender, EventArgs e)
    {
        if(Membership.ValidateUser(Login1.UserName, Login1.Password))
        {
            FormsAuthentication.SetAuthCookie(Login1.UserName, true);
            Response.Redirect("/admin/default.aspx");
        }

    }

EDIT: Like Gromer said, only do this if you have to execute some business code after the user is logged in and before s/he is redirected.

EDIT EDIT: Visual Studio describes the Authenticate event as, "called to authenticate the user," which implies that the user is not authenticated before the event is called. Thus, you cannot confirm that the user is logged in because s/he has not been authenticated yet.

Solution 3

While I don't know how much help this will be, this is boilerplate code I use to discern between admin users or regular users. Works great for me.

On your login page, probably onclick create your user object and call some function with this code (UserRole is an Enum with your roles):

If admin Then 
            If role = UserRole.Admin Then
                RedirectFromLoginPage(username & "|" & userid, False)
                Return True
            Else
                Return False
            End If
        Else
            If String.IsNullOrEmpty(Current.Request.QueryString("ReturnUrl")) Then
                SetAuthCookie(username & "|" & userid, True)
            Else
                RedirectFromLoginPage(username & "|" & userid, True)
            End If
            Return True
        End If

In your web.config:

<location path="admin">
    <system.web>
        <authorization>
            <allow roles="Admin"/>
            <deny users="*"/>
        </authorization>
    </system.web>
</location>
.....
<system.web>
<authentication mode="Forms">
        <forms loginUrl="/registration/login.aspx" timeout="129600"/>
    </authentication>
    <authorization>
        <allow users="*"/>
    </authorization>
</system.web>

... and if you really want, in your Global.asax page:

    Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
    If Request.IsAuthenticated Then
''
'get your roles for the current user'
''
 Dim userRoles() As String = Split(roles, "|")
        'Add the roles to the User Principal'
        HttpContext.Current.User = New GenericPrincipal(User.Identity, userRoles)
    End If
End Sub
Share:
77,578
marcgg
Author by

marcgg

Trying to build useful software. Find me on twitter or give my blog a read!

Updated on May 15, 2020

Comments

  • marcgg
    marcgg about 4 years

    I am trying to get the Membership Provider to work.

    So far I have:

     <asp:Login ID="Login1" runat="server" OnAuthenticate="Login1_Authenticate">
     </asp:Login>
    

    calling :

    protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
    {
        if(Membership.ValidateUser(Login1.UserName, Login1.Password))
        {
            Response.Redirect("/admin/default.aspx");
            // Set the user as logged in?
        }
    }
    

    If I enter the correct login/password, the ValidateUser function returns true. So my question is: how do I set the user as logged in?

    I am testing this in my pages doing :

    protected void Page_Load(object sender, EventArgs e)
    {
        if ( Membership.GetUser()==null)
        {
            Response.Redirect("/admin/login.aspx");
        }
        // else "you are logged in, congratulations"                
    }
    

    I would have used the default functions, but it is just not working and a google search made me think that I will save time by actually recoding all that myself.

    Anything will help!

    EDIT: Regarding the accepted answer, it is the correct one for "how to set the user as logged in" and works fine. It didn't fixed my specific problem but only a part of it. Thought if you look thought the comments you will find interesting pointers.

    EDIT 2 and solution: Ok I finally worked it out thanks to all the comments. Here is what I did, it's simpler than what I expected :

    Page that checks login state:

     protected void Page_Load(object sender, EventArgs e)
     {
         if ( !Request.IsAuthenticated)
         {
             Response.Redirect("/admin/login.aspx");
         }  
    

    Log out:

       protected void LoginStatus1_Logout(object sender, LoginCancelEventArgs e)
       {
           FormsAuthentication.SignOut();
           Response.Redirect("/admin/login.aspx");
       }
    }
    

    web.config:

    <authentication mode="Forms" />
    

    login:

    protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
    {
        if(Membership.ValidateUser(Login1.UserName, Login1.Password))
        {
            FormsAuthentication.SetAuthCookie(Login1.UserName, true);
            Response.Redirect("/admin/default.aspx");
    
        }
    }