Solved

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

Posted on 2011-03-15
10
367 Views
Last Modified: 2012-06-21
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
Comment
Question by:GouthamAnand
  • 6
  • 4
10 Comments
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 35141844
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
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 35142221
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
 

Author Comment

by:GouthamAnand
ID: 35142542
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
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 35142576
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
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 35144008
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
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 

Author Comment

by:GouthamAnand
ID: 35152455
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
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 35157572
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
 

Author Comment

by:GouthamAnand
ID: 35159252
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
 
LVL 33

Accepted Solution

by:
Todd Gerbert earned 500 total points
ID: 35159437
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
 

Author Closing Comment

by:GouthamAnand
ID: 35167648
Thanks a lot. I really appreciate your help.
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now