• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 381
  • Last Modified:

How to check the User ID when the page is accessed through routing.

Hi,

I am working on web application and below is my code on Page_Load. I am checking the user ID (LAN user ID) on Page_Load and giving the access to page.

But when the page is being accessed throug routing (below is the code) it is not getting the User ID. It is taking the Server ID under which the application is running.

Is there any way to access the user ID when the page is being accessed through routing.

public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            string lookup = requestContext.RouteData.Values["LookUp"] as string;
            object objPage= BuildManager.CreateInstanceFromVirtualPath("~/Exception.aspx", typeof(Page)) as Page;
            if (!string.IsNullOrEmpty(lookup))
            {
                if (lookup.Equals("Tools",StringComparison.OrdinalIgnoreCase))
                    objPage = BuildManager.CreateInstanceFromVirtualPath("~/PriceChallenge/ToleranceSearch.aspx", typeof(Page)) as Page;
                else if (lookup.Equals("0"))
                    objPage = BuildManager.CreateInstanceFromVirtualPath("~/PriceChallenge/GPQAddAssetTolerance.aspx", typeof(Page)) as Page;
                else if (lookup.Equals("1"))
                    objPage = BuildManager.CreateInstanceFromVirtualPath("~/PriceChallenge/GPQAssetTolerance.aspx", typeof(Page)) as Page;
            }
            return (IHttpHandler)objPage;
        }
protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                int userAuthority = AuthenticateUser(Environment.UserName);
                if (userAuthority == Constants.User_Authority_Level)
                {
                    lnkNew.Visible = true;
                }
                else
                {
                    lnkNew.Visible = false;
                }
                txtAccount.Text = "";
                lnkPdf.Enabled = false;
                lnkPrev.Enabled = false;
                this.SetFocus(txtAccount);
            }
            pageindex = 1;
            //string strAcct = txtAccount.Text;
        }

Open in new window

0
GouthamAnand
Asked:
GouthamAnand
  • 6
  • 4
1 Solution
 
Todd GerbertIT ConsultantCommented:
You probably want Request.LogonUserIdentity.Name, not Environment.UserName.

Try that a while, I'm gonna see if'n I can duplicate the problem myself.
0
 
Todd GerbertIT ConsultantCommented:
Okay, got it... if you do not have a "<identity impersonate=true />" tag in your web.config, then Environment.UserName will reflect the user that the server has been configured to run as.  Otherwise, if you do have a "<identity impersonate=true />" tag in your web.config then Environment.UserName will return the users name.

Request.LogonUserIdentity returns the users name in either case, provided that Windows authentication for the applicaple directory in IIS is enabled, and guest access is disabled.
0
 
GouthamAnandAuthor Commented:
Hi,

I am getting below error

Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the <configuration>\<system.web>\<httpModules> section in the application configuration.

I have below tags in my web.config.

<pages buffer="true" enableSessionState="true">

<httpModules>
      <add name="Session" type="System.Web.SessionStateModule"/>
    </httpModules>
    <sessionState mode="InProc" cookieless="false" timeout="20"/>

And below is my code on Page_Load.


protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write("User ID : " + Session["Username"].ToString());
            if (!IsPostBack)
            {
                Response.Write("I am inside Post Back");
                Response.Write(Environment.UserName);
                int userAuthority = AuthenticateUser(Environment.UserName);

                Response.Write(userAuthority.ToString());
                if (hLevel35.Value == Constants.User_Authority_Level.ToString())
                {
                   //Response.Write("This is from true part:1");
                    lnkNew.Visible = true;
                }
                else
                {
                    //Response.Write("This is from true part:2");
                    lnkNew.Visible = false;
                }
          }

Open in new window

0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
Todd GerbertIT ConsultantCommented:
I meant to mention that while Environment.UserName could get you the correct name, it's better anyway to use Request.LogonUserIdentity.Name - I also forgot to mention that Request.LogonUserIdentity.Name returns the user's name in DOMAIN\username format, so you might need to strip off the domain part (which can be easily done by splitting on the back-slash character).

Sorry, getting forgetful in my old age. ;)

I'll take a closer look at the session state error in a few minutes.
0
 
Todd GerbertIT ConsultantCommented:
Okay, that should work - although are you setting the Session["UserName"] value somewhere? You won't be able to read it if it hasn't been set yet.

At the top of the .aspx file for this page the first line should be <%@ Page Language="C#" AutoEventWireup="true" CodeFile="blahblah" Inherits="blahblah" %>, is there an EnableSessionState="False" parameter in that <%@ Page %> tag?

By the way, all of those values are the defaults - so you can remove <pages buffer="true" enableSessionState="true">, <add name="Session" type="System.Web.SessionStateModule"/> and <sessionState mode="InProc" cookieless="false" timeout="20"/> from your web.config.
0
 
GouthamAnandAuthor Commented:
My problem is not with Environment.UserName.

I will explain my problem here.

My web application is working fine if I type http://web-isn35-gpq:9045/PriceQuery/PriceChallenge/GPQAssetTolerance.aspx.

But I want to hide 'GPQAssetTolerance.aspx' from user. So I have implemented routing and the URL will be - http://web-isn35-gpq:9045/PriceQuery/PriceChallenge/Tools

Now when I type http://web-isn35-gpq:9045/PriceQuery/PriceChallenge/Tools user authentication is not happening becuase of routing.

Can you suggest me now?
0
 
Todd GerbertIT ConsultantCommented:
Your problem is with Environment.UserName.  Routing has nothing to do with it.

Do not use Environment.UserName.

Do use Request.LogonUserIdentity.

Environment.UserName returns the user running the code.  The web server is what is running the code. The web server logs on as IUSR_WHATEVER, so Environment.UserName returns IUSR_WHATEVER.

Request.LogonUserIdentity is the person who is sitting at the client computer and viewing the website.

In order to get the remote users' identity, you should have <authentication mode="Windows" /> in the web.config, and the web site in IIS must not allow anonymous access.

I setup a test site with 2 pages: Default.aspx and RouteHandlerPage.aspx.  Both pages show the values of Environment.UserName and Request.LogonUserIdentity.Name.  Detault.aspx is reached directly (like normal) and RouteHandlerPage.aspx is reached through the TestRouteHandler.  Note that Environment.UserName and Request.LogonUserIdentity show different things - but they never change, whether routing is used or not.
tgerbert-429863.flv
0
 
GouthamAnandAuthor Commented:
In my case both are same except the domain name. below is the output to my below code.

Login user Name : ENT\System-dnt-GPQ-s
Environment User Name : SYSTEM-DNT-GPQ-S
I am in Post back
Login user Name : ENT\System-dnt-GPQ-s
Environment User Name : SYSTEM-DNT-GPQ-S

When I run locally in my machine -

Login user Name : ENT\gt47
Environment User Name : GT47
I am in Post back
Login user Name : ENT\gt47
Environment User Name : GT47

So, that means, in server it is taking the server ID (System-dnt-GPQ-s) under which the application is running , but not the user login ID (gt47). That is my problem.

It is not allowing me to use the session variable (as below) - if I use session variable it says

"Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the <configuration>\<system.web>\<httpModules> section in the application configuration. "

protected void Page_Load(object sender, EventArgs e)
        {
            Session["Username"] = Request.LogonUserIdentity.Name;  
        }
Response.Write("Login user Name :  " + Request.LogonUserIdentity.Name + "<br />");
            Response.Write("Environment User Name :  " + Environment.UserName.ToUpper() + "<br />");
            if (!IsPostBack)
            {
                Response.Write(" I am in Post back <br />");
                Response.Write(" Login user Name :  " + Request.LogonUserIdentity.Name + "<br />");
                Response.Write(" Environment User Name :  " + Environment.UserName.ToUpper() + "<br />");

Open in new window

0
 
Todd GerbertIT ConsultantCommented:
You have anonymous access enabled - turn it off (what version of IIS are you using?).

Put <authentication mode="Windows" /> in your web.config, within the <system.web> section.

See my comment above about session state, http:#a35144008.
0
 
GouthamAnandAuthor Commented:
Thanks a lot. I really appreciate your help.
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 6
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now