Avatar of Mark Klein
Mark Klein
Flag 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
ASP.NET.NET Programming

Avatar of undefined
Last Comment
Mark Klein

8/22/2022 - Mon
disrupt

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

libby9284

How have you set up your roles?  Are you using the default role provider / membership provider or defining your own?  
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.
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
Mark Klein

ASKER
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?
libby9284

Try this site
Mark Klein

ASKER
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.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Mark Klein

ASKER
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.
libby9284

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

Mark Klein

ASKER
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
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
disrupt

Mark Klein

ASKER
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.
disrupt

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
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Mark Klein

ASKER
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.
libby9284

can you post the relevant section of your markup?  
Mark Klein

ASKER
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

Your help has saved me hundreds of hours of internet surfing.
fblack61
disrupt

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
libby9284

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Mark Klein

ASKER
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.
Mark Klein

ASKER
expert  showed tons of patience in digging through to the solution
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.