views:

3431

answers:

4

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

            }
        }
+5  A: 

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

FormsAuthentication.SetAuthCookie("username", true);
Gromer
It still get catched by if ( Membership.GetUser()==null). Should I try to get the login state in some other way?
marcgg
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 :(
Gromer
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".
marcgg
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.
Gromer
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 that
marcgg
IIRC there is Context.User.IsAuthenticated()
metanaito
Or maybe it's User.Identity.IsAuthenticated I can't remember which...
metanaito
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?
marcgg
Try Request.IsAuthenticated
Greg
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" />
metanaito
Context.User.IsAuthenticated() may see if a user is authenticated, but the fact remains, he cannot get the MembershipUser object with Membership.GetUser().
Gromer
I tried : FormsAuthentication.SignOut(); Response.Write(Request.IsAuthenticated); and the page displayed "True"
marcgg
@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?
marcgg
You need a web.config to tell your site to use Forms authentication.
metanaito
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 madness
marcgg
Are you saying you don't have a web.config file at all?
Matthew Jones
I have one, but it doesn't handle authentication
marcgg
If you are using Forms authentication I think you need it. I can't imagine it working without it... but I could be wrong.
metanaito
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...
marcgg
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).
Matthew Jones
hum... ok, thanks! Do you have any pointers on where to look for a simple tutorial to set this up?
marcgg
You can try Scott Allen's tutorial at http://odetocode.com/Articles/427.aspxAlso, you might want to look at Scott Mitchell's series on the Membership provider:http://www.4guysfromrolla.com/articles/120705-1.aspx
Matthew Jones
thanks, hopefully all this will work ^^
marcgg
You can also try that link I gave in the answers below: http://msdn.microsoft.com/en-us/library/ms998347.aspxIt'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.
metanaito
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.
marcgg
Hurray! I sorted it out. Thanks a lot for your help, people
marcgg
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't
marcgg
Good job, glad you got it working!
metanaito
+1  A: 

Gromer has the answer, but you can also take a look at this MSDN article to learn more:

http://msdn.microsoft.com/en-us/library/ms998347.aspx

metanaito
Like I said, it sounds correct but it's not working since I can't manage to get the fact that the user is successfully logged in. It must be obvious but I'm new to .net
marcgg
+2  A: 

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.

Matthew Jones
what is exactly the loggedIn event?
marcgg
It is an event called by the login control after a user is authenticated. See http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.login.loggedin.aspx
Matthew Jones
thanks .
marcgg
A: 

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
Jason