?
Solved

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

Posted on 2011-03-15
10
Medium Priority
?
378 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Basic Security of Your VPC

So, you’ve got this shiny new VPC and a fancy new application configured on your EC2 servers ready to go. This application is only accessible from your computer, which is great for security, but you need your users to be able to access it! So, what’s the easiest way to do this?

 
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
 

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 2000 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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

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.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Michael from AdRem Software outlines event notifications and Automatic Corrective Actions in network monitoring. Automatic Corrective Actions are scripts, which can automatically run upon discovery of a certain undesirable condition in your network.…
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…
Suggested Courses

770 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