c# library impersonate problem - c#

I'm working on a website that has been coded by someone else. The application contains three layers. A website, a web service and a library. The Web service is up for other application to call methods and everything. The website is used by workers to performs queries and everything.
The problem is : The website use the web service that use the library instead of going directly to the library. I want to remove the web service usage and use the library straight away instead. Unfortunately, the library isn't able to connect an external server when called directly from the web site.
The web service used the impersonate method in his web config like so :
<?xml version="1.0"?>
<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<compilation defaultLanguage="c#" debug="true" />
<authorization>
<allow users="*" />
</authorization>
<authentication mode="Windows" />
<identity
impersonate="true"
userName="USERNAME_HERE"
password="PASSWORD_HERE" />
<sessionState
mode="InProc"
stateConnectionString="tcpip=10.96.8.37:42424"
sqlConnectionString="data source=10.96.8.37;Trusted_Connection=yes"
cookieless="false"
timeout="20" />
</system.web>
When the web service use the library, the library identity turns out to be the username specified in the web.config. But when I call it from the website directly the user turns out to be : MY_COMPUTER\ASPNET
How can I sucessfully impersonate within the library itself?
Thanks!
EDIT
Ok, I thought of adding the impersonate piece of code in the website's web.config instead. It turned out that the library used the correct user but the request takes forever and never end. Do you know what could be wrong?

At first glance, you could use these entries in the web.config of your transactional website.
<authorization>
<allow users="*" />
</authorization>
<authentication mode="Windows" />
<identity
impersonate="true"
userName="USERNAME_HERE"
password="PASSWORD_HERE" />
However you want to be really sure this is the right thing to do before you do it.
Security is a big thorny problem that can turn around and bite you in the ass pretty hard. Whichever user you use here should be single purpose. It should have exactly the permissions you need and no more.
Why can't you give the MY_COMPUTER\ASPNET user permissions on the external server?
There are ways to impersonate for a short time which will probably solve your problem more cleanly. I will let someone who actually knows that answer tell you what it is though.

Related

Get username of logon user ASP.NET MVC

I want to get the username of the logon username and domain.
My code for getting it, is in a controller:
User.Identity.GetUserId()
In my web.config is:
<system.web>
<identity impersonate="false"/>
<authentication mode="Windows" />
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime />
<pages controlRenderingCompatibilityVersion="4.0" />
</system.web>
Currently, I only get a empty string. What I have to change to get the Windows username information?
Sidenote for others:
While my research, I also got to the following:
Environment.UserDomainName + #"\" + Environment.UserName
In reference to this, it only delivers the identity in which the thread is running and not the windows information.
EDIT1: I'm currently testing my program in debugging mode.
try this
HttpContext.User.Identity.Name
also make sure you have authorization tag in your system.web in web.config as
<authorization>
<allow users="?" />
</authorization>
and in IIS make sure that you will disable annonymous authentication and enable windows for the same app as
User.Identity.GetUserId() is an extension method from Microsoft.AspNet.Identity. Identity is incompatible with Windows Auth (you have to use one or the other), so I'm not sure what you're actually doing here.
Generally speaking, in Windows Auth, the value of User.Identity.Name will be in the form of {DOMAIN}\{USER}. So if you wanted the domain and/or username, you can split that string on \ and take the part you're after.
When it comes to Identity, User.Identity.Name should be the value of ApplicationUser.UserName, but depending on the setup, it might be ApplicationUser.Email.

I want to disable requiring authentication for one MVC controller action

I have created an mvc application I don't want authentication for one functionality in my application. I want that the user should able to open the page from the URL without log in.Right now if I enter the URL to open that functionality directly then it will take me to the sign on page. I want to bypass the authentication process in one functionality.
I have tried following code in my web.config.
<location path="ControllerName">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
And I have also added [AllowAnonymous] attribute to the some action of my controller.
The following code that i have written for authentication in my web.config.
<modules runAllManagedModulesForAllRequests="true">
<remove name="FormsAuthentication"/>
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule"/>
<remove name="AuthorisationModule"/>
<add name="AuthorisationModule" type="ProjectName.AuthorisationModule(which is for autentication), Project Name"/>
</modules>
There is an authentication for the whole application and I want discard the authentication of just one feature of my mvc application. So I have added the following code in my web.config
<location path="ControllerName">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
So using this code it's working fine.
Something that may help with your issue is the fact that you can have multiple web.config files -- if you put a web.config in a subdirectory within your project, then you can include configuration options specific only to that subdirectory. As such, you may want to try adding a subfolder to contain just the controller which you want to make publicly available, and then creating a separate web.config file allowing open access to that subdirectory. As per this answer regarding wildcards in web.config files, here is example code that should suffice as a standalone web.config to provide
<?xml version="1.0"?>
<configuration>
<system.web>
<authorization>
<deny users="*"/>
</authorization>
</system.web>
</configuration>
That way you don't have to mess around with specifying the one controller or action you want to give access to, as the distinction is made by the organization of the files in the directory structure.

Asp.net randomly stops obeying forms authentication whitelist

The problem
Last month we move our asp.net website farm from Server 2008 R2 to Server 2012 R2 and upgraded to asp.net 4.5. We are using cookied forms authentication to prevent unauthorized access to the website.
<authorization>
<deny users="?" />
<allow users="*" />
</authorization>
We have certain assets and pages (ex: sign in page) that are whitelisted in the web.config:
<location path="signin">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
Over the last few months we've been noticing that IIS/Asp.net randomly stops obeying the whitelist and assume everything needs to be authenticated. All requests to the site on that server will be redirected to the signin page which then throws a 500 error. No whitelisted assets can be retrieved.
There are then 2 errors in the event viewer that we can see when IIS is messed up. The first:
Exception type: NullReferenceException
Exception message: Object reference not set to an instance of an object.
at System.Web.PipelineModuleStepContainer.GetNextEvent(RequestNotification notification, Boolean isPostEvent, Int32 eventIndex)
at System.Web.HttpApplication.PipelineStepManager.ResumeSteps(Exception error)
at System.Web.HttpApplication.BeginProcessRequestNotification(HttpContext context, AsyncCallback cb)
at System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context)
This second one doesn't show up all the time:
Event code: 4005
Event message: Forms authentication failed for the request. Reason: The ticket supplied has expired.
The iis process will be working find for hours then all the sudden start doing this weirdness. As soon as we recycle the app pool, or even just modify the web.config the site starts working again.
Things we've tried
Honestly we are quite stumped. This wasn't happening on our old servers, but we've made quite a few changes to our site since then but nothing related to authentication.
We are in a webfarm and we define our machine key inside of our web.config.
<machineKey validationKey="XXX" decryptionKey="XXX" validation="SHA1" decryption="AES" />
We are targeting asp.net 4.5
<httpRuntime targetFramework="4.5" executionTimeout="120" maxQueryStringLength="4096" minFreeThreads="72" minLocalRequestFreeThreads="88" maxRequestLength="32768" />
We recreated the application pool within IIS.
Not sure if it matters but we use IIS Shared Config and shared certificates.
The issue is happening on all of the web servers in the farm, not just one.
We reinstalled the OS on one of the servers yesterday... so we'll see if that fixes anything.
It doesn't seem to be tied to memory usage. Sometimes iis is only using 4gb, sometimes 6gb.
It doesn't seem to be tied to a certain page execution that we can tell.
I've run debug diag against a memory dump and there aren't any threads that are running long nor crazy memory usage.
Yea, we are stumped. Any help is appreciated.
I had a similar experience, changing IIS to allow anonymous authentication solved it for me. In your case, I would recommend 2 things:
Try Enabling Anonymous Authentication in IIS (Visit http://technet.microsoft.com/en-us/library/cc770966%28v=ws.10%29.aspx to see how)
Modifiy your code as shown below
<location path="signin">
<system.web>
<authorization>
<allow users="?" />
<allow users="*" />
</authorization>
</system.web>
</location>
I hope this helps
I'll answer my own question with what we did to solve the issue, even though we never did find the root cause. We noticed that the server would start ignoring the whitelist rules when it got too heavy under load. Not much load, maybe 40% utilization over the course of 5 minutes. After that it would start ignoring things.
The simple solution for us was to throw more hardware at the issue. We are running 6 webservers instead of 3. We haven't seen the whitelist issue since then. So honestly... we have no idea what's up.
While I can't say exactly what the issue is, I can share a similar experience.
We had a site that used forms authentication and also assumed it was failing and forcing everyone to authenticate. What we discovered was that the website was crashing and IIS was returning the default website instead. It took us a while to figure out. You might want to check to make sure you're not looking at a similar situation.
Can you show your Authentication node from your web.config ?
It should be something like this :
<authentication mode="Forms">
<forms name="Logon" loginUrl="~/Logon.aspx" protection="All" timeout="60" defaultUrl="~/Default.aspx" />
</authentication>
Are you using the asp.net session state server ? If you do check if the service asp.net state server is started.

ASP.NET Forms Authentication always redirecting back to Login page

I have a problem with an incredibly simple website using simple Forms authentication.
I have a a single page Default.aspx and a Login.aspx.
Default.aspx is protected by <deny users="?" />
The Login.aspx calls
FormsAuthentication.RedirectFromLoginPage( tbUserName.Text, chPersist.Checked );
I used Fiddler to check if the redirect works. It does. But the Default page always redirects back to the Login page (HTTP/1.1 302 Found).
The cookie is created as expected and Fiddler tells me it's there. But it just won't load the default page.
I tried so many combinations, but the only thing that makes the default page load "successfully" is when I turn off the deny="?" rule in IIS/web.config. But then all users can get to the page, which is not what I want.
Web.config on the server and my machine:
<authentication mode="Forms">
<forms loginUrl="Login.aspx" name=".ASPXFORMSAUTH" defaultUrl="Default.aspx" cookieless="UseCookies" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
Ironically all this is working great in any case when I debug the site in Visual Studio, but upon deployment it does not work. The web.config is deployed with the site.
I have no idea why this still isn't working.
Anyone?
Try recycle the application pool.. and then restart the IIS server.
This can be as one solution for you.
If you have the following line of code in your web.config file remove it.
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
</modules>
</system.webServer>
You could check, that IIS has activated Forms Authentication for that site. If this is disabeld, it might result in odd behaviour when trying to authenticate via form.

ASP.NET web app sessions issue

I developed an ASP.NET web application that is installed on a "live" IIS 7.5. The web app uses http sessions to pass parameters between pages for logged in users. This works great on my development machine (tested with local IIS in VS2010 IDE), but when this web app is uploaded to a client's IIS and they start using it (Google Chrome and IE browsers), at some random moments the session variables seem to disappear. My first guess was to increase the session timeout setting via web.config file by adding this line:
<configuration>
<system.web>
<sessionState timeout="20"></sessionState>
</system.web>
</configuration>
But that doesn't seem to fix the issue. So it made me wonder, what other settings are there concerning sessions? Something like an internal folder that keeps a cache of all sessions that gets overflown on an actual IIS? Any ideas?
EDIT: Following #wy__'s suggestion, I modified the web.config file and started seeing the same issue on my dev machine. Here's the whole system.web section as I have it now:
<system.web>
<compilation targetFramework="4.0" debug="false"/>
<pages validateRequest="false"/>
<httpRuntime requestValidationMode="2.0" executionTimeout="110" maxRequestLength="262144"/>
<sessionState timeout="20" cookieless="true" regenerateExpiredSessionId="true"></sessionState>
</system.web>
I also checked and there's only one w3wp.exe process running.
By default, the session uses cookies to track user sessions. If you are not sure whether users turn them off or not, you can configuring cookieless session.
i.e.
<configuration>
<system.web>
<sessionState cookieless="true" regenerateExpiredSessionId="true" />
</system.web>
</configuration>

Categories

Resources