t_plusplus
t_plusplus

Reputation: 4209

Windows Authentication - Get windows username

I have an MVC4 application which uses Windows Authentication (WA), which is setup on Webconfig file as such:

  <system.web>
    <authentication mode="Windows"/>
  </system.web>

I am using this line of code to get the UserName, which in turn I am using in the LINQ Query shown:

var userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

var  loc  = (from l in data.Locations.OrderBy(l => l.LocationName)
                        join s in data.LocationSecurities.Where(s=> s.UserName.Contains(userName)) on l.LocationID equals s.LocationId
                        select new
                        {
                            LocationId = l.LocationID,
                            Name = l.LocationName
                        }
                        ).ToList().Distinct();

This works in debug mode, however it doesn't when the Application is published to the localhost or the Webserver. I have looked at SQL Profiler. It seems to be taking the username as the DefaultAppPool, which is not bringing back any results!

This is the profiler trace:

exec sp_executesql N'SELECT 
[Extent1].[LocationID] AS [LocationID], 
[Extent1].[LocationName] AS [LocationName]
FROM  [admin].[Location] AS [Extent1]
INNER JOIN [admin].[LocationSecurity] AS [Extent2] ON [Extent1].[LocationID] = [Extent2].[LocationID]
WHERE [Extent2].[UserName] LIKE @p__linq__0 ESCAPE N''~''',N'@p__linq__0 nvarchar(4000)',@p__linq__0=N'%DefaultAppPool%'

Any idea on why this is happening?

Thanks in advance.

Upvotes: 0

Views: 883

Answers (3)

Mike Marks
Mike Marks

Reputation: 10139

Try HttpContext.User.Identity.Name. You retrieve the user's currently logged-in name via the current HttpContext.

Upvotes: 1

Nagaraj S
Nagaraj S

Reputation: 13484

Code in your web.config:

 <authentication mode="Windows">
         </authentication>

.Code in page:

Response.Write(Page.User.Identity.Name);

msdn

Upvotes: 1

Dave Bish
Dave Bish

Reputation: 19656

To get the currently logged-in user from within an action method (Via Windows auth) you have to query the current HttpContext, with something like:

HttpContext.User.Identity.Name

Upvotes: 4

Related Questions