Link to home
Start Free TrialLog in
Avatar of Mark Klein
Mark KleinFlag for United States of America

asked on

Role-based destination URLs

I am trying to set up login to my asp.net project so that the destination page after login depends on the role.  The possible roles are buyer, seller, admin. I am trying to use Roles.IsUserInRole method, but can't get it working
Avatar of disrupt
disrupt
Flag of United States of America image

u can use something like this:
protected void Login1_LoggedIn(object sender, EventArgs e)
    {
        if (User.IsInRole("members"))
        {
            Response.Redirect("member.aspx");
        }
        else if (User.IsInRole("guest"))
        {
            Response.Redirect("guest.aspx");
        }
    }

Open in new window

How have you set up your roles?  Are you using the default role provider / membership provider or defining your own?  
Avatar of Mark Klein

ASKER

I am using the default role provider, stored on sql server.  Same for membership provider.  All of that seems to be working. I am trying to use exactly the code suggested by disrupt, but in vb. Problem is, can't find a place to put it.
That is the code, in that event.  Here's my code-behind:
 Protected Sub Login1_LoggedIn(sender As Object, e As System.EventArgs) Handles Login1.LoggedIn
        If (Roles.IsUserInRole("seller") = True) Then
            Response.Redirect("~/sellers.aspx")
        ElseIf (Roles.IsUserInRole("buyer") = True) Then
            Response.Redirect("~/buyers.aspx")
        End If
    End Sub

Open in new window


But after login, the user is still being switched to the default home page.  Is that b/c of the destination URL?  Or my web.config?
this looks like it will do the job.  A lot of machinery, however. My biggest problem with the simpler code is that I do not seem to have the user name by the time the loggedIn event fires.  That's a mystery.

 I am struggling to translate the c# public classes to vb.net.  Stay tuned.
I am bumping into the same problem I had before--not collecting the user name when I want it.  Throughout my app, I collect the name thusly:
 Dim currentUser As MembershipUser = Membership.GetUser()
    Dim currentUserId As Guid = DirectCast(currentUser.ProviderUserKey, Guid)

Open in new window


this has worked all the time. However when I put this in the loggedIn event handler, where I think the name is available, it is not.
The input parameter to the code at the site you suggested also requires the user name, so I'm still stuck.
if the username isn't available when the loggedin event fires, there's something else wrong.  I don't access the user the way you are, I use HttpContext.Current.User.  On your login page, just User should be sufficient.  Try using that instead.

examples
User.Identity.IsAuthenticated       // boolean check for whether or not user is logged in
User.Identity.Name                      // returns current logged in user's username
User.IsInRole("whicheverRole")  

Open in new window

I put this at the start of my loggedIn event handler
 If User.Identity.IsAuthenticated = True Then       '
            Dim currentuser As String
            currentUser = User.Identity.Name
            User.IsInRole("seller")
        End If

Open in new window


As I expected, isAuthenticated returns False.  Where else can I put this code to check user?  Earlier I had
 If (Roles.IsUserInRole(User.identity.name, "seller") = True) Then
            Response.Redirect("~/sellers.aspx")
        ElseIf (Roles.IsUserInRole("buyer") = True) Then
            Response.Redirect("~/buyers.aspx")
        End If

Open in new window


that used some of what you
That article was not of much help. Mostly about setting up the Roles system.  I think mine is ok. Web config looks like the models. Only buyers can get to the buyers pages, and only sellers can get to the sellers pages. I put this code
If (Roles.IsUserInRole("seller") = True) Then
            Response.Redirect("~/sellers.aspx")
        ElseIf (Roles.IsUserInRole("buyer") = True) Then
            Response.Redirect("~/buyers.aspx")
       End If

Open in new window


into a page where the user s/b a seller, used the debugger, and it was a seller, so I think the Roles stuff is working.
The problem is that I can't capture the user name during the loggedIn event in order to route the user to my desired path. A couple of days ago I tried the 'disposed' event, and if I recall properly, that didn't work either.
you should be able to use this: Page.User.Identity.Name.ToString();

check out this link:
http://forums.asp.net/t/1186509.aspx/1?Page+User+Identity+Name+returns+null
Still struggling.  I read the link.
-can't disable anonymous users b/c they are legit browsers of the site.  Don't think I need to anyway, b/c now users sign in as authenticated users or just browse as anonymous.  I'm merely trying to redirect. When a user does login, I capture (eventually) the user name.  Just having trouble getting it at login

-I did put in the sub w/ e.authentication=True, and that didn't change anything

-I did preface User.Identity.Name w/ Page, to no effect

I appreciate your patience hanging in w/ me on this.
can you post the relevant section of your markup?  
here's the code for login.aspx.vb
I've had so many different versions that I've lost track.  mostly I put in lines and debug, seeing if I can trap the user name

Imports System.Web.Security
Partial Class Login

    Inherits System.Web.UI.Page

    Protected Sub Login1_Authenticate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.AuthenticateEventArgs) Handles Login1.Authenticate
        e.Authenticated = True
    End Sub


    Protected Sub Login1_LoggedIn(sender As Object, e As System.EventArgs) Handles Login1.LoggedIn
        Dim currentuser As String = Page.User.Identity.Name.ToString()

        If (Roles.IsUserInRole("seller") = True) Then
            Response.Redirect("~/sellers.aspx")
        ElseIf (Roles.IsUserInRole("buyer") = True) Then
            Response.Redirect("~/buyers.aspx")
        End If

    End Sub
End Class

Open in new window


and here is my web.config
<connectionStrings>
    <add name="lucidequipmentConnectionString" connectionString="Data Source=lucidequipment.db.3377297.hostedresource.com;Initial Catalog=lucidequipment;Persist Security Info=True;User ID=luxxxxxxxxxt;Password=xxxxxxxxxxx"
      providerName="System.Data.SqlClient" />
    <add name="SqlRoleManagerConnection"
         connectionString="Data Source=lucidequipment.db.3377297.hostedresource.com;Initial Catalog=lucidequipment;Persist Security Info=True;User ID=lssss;Password=xxxx"/>
  </connectionStrings>

  
  
  <system.web>
    <roleManager
      enabled="true"
      cacheRolesInCookie="true"
      cookieName=".ASPROLES"
      cookieTimeout="30"
      cookiePath="/"
      cookieRequireSSL="true"
      cookieSlidingExpiration="true"
      cookieProtection="All"
     defaultProvider="SqlRoleProvider">
      
      <providers>
        <add
          name="SqlRoleProvider"
          type="System.Web.Security.SqlRoleProvider"
          connectionStringName="SqlRoleManagerConnection"
          applicationName="website3"
           />
      </providers>
    </roleManager>
	
    <authentication mode="Forms">
      <forms name=".ASPXFORMSAUTH" />
    </authentication>
  
    <authorization>
      <allow users="?" />
      <allow roles="admin"/>
    </authorization>
	
    <membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15">
      <providers>
        <add
          name="SqlProvider"
          type="System.Web.Security.SqlMembershipProvider"
          connectionStringName="lucidequipmentConnectionString"
          applicationName="Website3"
          enablePasswordRetrieval="false"
          enablePasswordReset="true"
          requiresQuestionAndAnswer="true"
          requiresUniqueEmail="true"
          passwordFormat="Hashed" />
      </providers>
    </membership>

    <compilation debug="true" strict="false" explicit="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77Axxxxxxxx089"/>
      </assemblies>
    </compilation>
    <customErrors mode="Off"/>
     
 </system.web>

  <system.net>
    <mailSettings>
      <smtp from="admin@lucideq.com">
        <network host="smptout.secureserver.net" port="3535"  defaultCredentials="false" userName="mark@seabreezelane.net" password="xxxxxx"/>
      </smtp>
    </mailSettings>
  </system.net>

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
  </system.webServer>

</configuration>

Open in new window

Did you try the second suggestion?  

FormsAuthentication.SetAuthCookie(UserName, False)

or

  FormsAuthentication.RedirectFromLoginPage(UserName, False)

or

 Protected Sub Login1_Authenticate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.AuthenticateEventArgs) Handles Login1.Authenticate
        e.Authenticated = True
    End Sub
ASKER CERTIFIED SOLUTION
Avatar of libby9284
libby9284
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hey, that looks like it is going to work.  It did grab the user name. My redirect code is not working, but I should be able to fix that. Need to drive to CT right now, be back on line tonight to finish this off. Thanks so much.
expert  showed tons of patience in digging through to the solution