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

3

33

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");

    }
}
Sestina answered 26/5, 2009 at 19:29 Comment(0)
F
41

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

FormsAuthentication.SetAuthCookie("username", true);
Frill answered 26/5, 2009 at 19:32 Comment(24)
It still get catched by if ( Membership.GetUser()==null). Should I try to get the login state in some other way?Sestina
IMO, you should only deal with this login stuff on the Login.aspx page. The SetAuthCookie works, I've used it before. If it doesn't work for you, there is something somewhere else in your code that is messing it up :(Frill
All my code is up there. What I'm trying to do elsewhere than on the login page is "if not logged in then redirect to the login page".Sestina
Why are you handling that event anyways? From what you posted, you are only redirecting the user, which can be done by the DefaultURL in the Web.config or the ReturnURL in the query string. I understand if you have to do business logic for your domain, but if you are only redirecting, try killing the event handler and letting Membership do its thing.Frill
I have URL rewritting and when I let Membership do its thing it breaks, that's why I'm doing it that way. I feel there should be something like "user.isLoggedIn" or something to help me do thatSestina
IIRC there is Context.User.IsAuthenticated()Bochum
Thanks for putting up with my nonsense. Ok so there is a Context.User.Identity.IsAuthenticated, but it returns true even if I run FormsAuthentication.SignOut(). So basically it's always true. Do you have an idea?Sestina
Not really sure, but make sure that in your web.config you don't have this: <authentication mode="Windows" /> it should be: <authentication mode="Forms" />Bochum
Context.User.IsAuthenticated() may see if a user is authenticated, but the fact remains, he cannot get the MembershipUser object with Membership.GetUser().Frill
I tried : FormsAuthentication.SignOut(); Response.Write(Request.IsAuthenticated); and the page displayed "True"Sestina
@webdtc Do I neet the web.config to handle that? Can't I just handcode all that manually going if(isConnected) or something like that?Sestina
You need a web.config to tell your site to use Forms authentication.Bochum
I just want to use it in some specif parts of the website, like 3-4 pages out of 60. Wouldn't that make everything more complicated? I don't understand why I can't have access to a function that tells me if I'm logged in. There must be something I'm not getting, but to me it's sounds like Authentication 101... I really try to avoid all this xml madnessSestina
Are you saying you don't have a web.config file at all?Viticulture
I have one, but it doesn't handle authenticationSestina
If you are using Forms authentication I think you need it. I can't imagine it working without it... but I could be wrong.Bochum
It sounds like overkill, making everything really complicated for just a few pages. I guess I am coding in .NET so it was something to expect...Sestina
If you are using the default MembershipProvider, you ought to use the authentication in the web.config file. Otherwise, .NET has no way of knowing whether a user is authenticated (unless you wanted to write your own provider, in which case you would still need to hook it up in web.config).Viticulture
hum... ok, thanks! Do you have any pointers on where to look for a simple tutorial to set this up?Sestina
You can try Scott Allen's tutorial at odetocode.com/Articles/427.aspx Also, you might want to look at Scott Mitchell's series on the Membership provider: 4guysfromrolla.com/articles/120705-1.aspxViticulture
You can also try that link I gave in the answers below: msdn.microsoft.com/en-us/library/ms998347.aspx It's kind of bland and probably doesn't speak to a new .net developer, but it shows exactly how to set up the default Membership provider.Bochum
Thanks! I think I'll end up creating a new questions for it later on if I'm stuck again, since we're out of the scope of this one now.Sestina
Hurray! I sorted it out. Thanks a lot for your help, peopleSestina
I think that the main problem was that the web.config was not set correctly. I thought that changing this for the whole application will break things... but it didn'tSestina
V
6

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.

Viticulture answered 26/5, 2009 at 19:41 Comment(2)
what is exactly the loggedIn event?Sestina
It is an event called by the login control after a user is authenticated. See msdn.microsoft.com/en-us/library/…Viticulture
H
1

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
Headstall answered 26/5, 2009 at 20:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.