Calling https process from ASP Net - asp.net

I have an ASP NET web server application that calls another process running on the same box that creates a pdf file and returns it. The second process requires a secure connection via SSL.
The second process has issued my ASP NET application with a digital certificate but I still cannot authenticate, getting a 403 error.
The code is a little hard to show but here's a simplified method ...
X509Certificate cert = X509Certificate.CreateFromCertFile("path\to\cert.cer");
string URL = "https://urltoservice?params=value";
HttpWebRequest req = HttpWebRequest.Create(URL) as HttpWebRequest;
req.ClientCertificates.Add(cert);
req.Credentials = CredentialCache.DefaultCredentials;
req.PreAuthenticate = true;
/// error happens here
WebResponse resp = req.GetResponse();
Stream input = resp.GetResponseStream();
The error text is "The remote server returned an error: (403) Forbidden."
Any pointers are welcome.

Finally fixed (wasted 6 hours on this *&%$##&)
I needed to grant access to the private keys on the digi cert to the account that the calling ASP.NET application runs under. This account is NETWORK SERVICE by default although you may want to run under a more restricted account.
Access is granted with the winhttpcertcfg tool, here's what got it working for me:
winhttpcertcfg -g -s "cert name" -c "LOCAL_MACHINE\MY" -a "NETWORK SERVICE"
where "cert name" is the CN of the digi cert.
More info at http://support.microsoft.com/kb/901183
Thanks to all who helped out with pointers on how to get this working :)

A 403 sounds like an authorization problem, not an authentication problem. It might be caused by the NTFS security settings on the files and folders accessed by your PDF service. Maybe it doesn't have permission to create the PDF file in the output folder?
Can you install the client certificate into your browser, and then access your PDF service through the browser? When you do that, do you still get a 403 or does it work?
Can you temporarily configure the PDF service to allow unencrypted HTTP connections? Does that make the problem go away?
From Windows Explorer, can you grant the "Network Service" account full control over the physical folder corresponding to the root of the PDF service site? Also grant it full control over any other directories it accesses. You should lock things down later after you've figured things out.
Or you can change the application pool to run under a different account - e.g. your own account.
Finally: if you're running IIS 7, you can turn on failed request tracing, which should give you a lot more info about why it failed.

Related

Unable to find SignalR trace logs on disk

I tried following links to generate server side SignalR trace on my production environment:
http://www.asp.net/signalr/overview/testing-and-debugging/enabling-signalr-tracing#server_text
https://github.com/SignalR/SignalR/wiki/Tracing-on-the-server-side
But, trace is not getting saved on disk as mentioned in the links(e.g., "default_traces.txt" or "transports.log.txt" respectively).
Please suggest where trace log file get saved?
I also checked following folders mentioned in first tutorial:
C:\inetpub\logs\LogFiles\W3SVC1
C:\inetpub\logs\FailedReqLogFiles\W3SVC1
But nothing related with SignalR found there. Any idea?
In my environment (VS2015 + IIS Express) log files are stored in web application folder (folder with web.config).
Be sure that your application pool has write permission on logs folder.
Also check SignalR error on client side. It can direct you to the cause of the problem.
For example, if client receives response 401 (Not authorized) (for example, on $.connection.hub.start()) it could mean that authentication middleware can not authenticate the client and responds with 401 without passing the request further through OWIN pipeline to SignalR. In this case SignalR does not emit any logs (it doesn't know about any request).

The remote server returned an error: (401) Unauthorized. Using CSOM in ASP.NET

I'm tried to pull some SharePoint 2013 list data I created which works fine when running locally on my machine and when run locally one the server. I'm user the same credentials when running both locally and locally on the server. The issue is when I publish and navigate to my ASP.NET app on the server I get the "The remote server returned an error: (401) Unauthorized." Error...
I've looked at a bunch of the posts on stackoverflow and some other articles on the web
This points out that the context seems to be using IUSR:
http://blogs.msdn.com/b/sridhara/archive/2014/02/06/sharepoint-2013-csom-call-from-web-part-fails-with-401-for-all-users.aspx
This one mentions to try setting the default network credentials:
https://sharepoint.stackexchange.com/questions/10364/http-401-unauthorized-using-the-managed-client-object-model
I've tried using the fixes mentioned in the article as well as trying to force the context to use DefaultNetworkCredentials but no luck. I would like for the app to use the credentials of the logged in user and not the machine...
Here is the code I'm using:
SP.ClientContext context = new SP.ClientContext("MySPDevInstance");
context.Credentials = CredentialCache.DefaultNetworkCredentials;
Entity entity = context.Web.GetEntity(collectionNamespace, collectionName);
LobSystem lobSystem = entity.GetLobSystem();
LobSystemInstanceCollection lobSystemInstanceCollection = lobSystem.GetLobSystemInstances();
context.Load(lobSystemInstanceCollection);
context.ExecuteQuery();
LobSystemInstance lobSystemInstance = lobSystemInstanceCollection[0];
FilterCollection filterCollection = entity.GetFilters(filter);
filterCollection.SetFilterValue("LimitFilter", 0, 1000);
EntityInstanceCollection items = entity.FindFiltered(filterCollection, filter, lobSystemInstance);
The server is running IIS 6.0
Any advice would be much appreciated!
Thank you
I presume your ASP.NET web site is using Windows Integrated (NTLM) authentication. A user authenticated this way cannot authenticate to a second location from the server side (the web server.) You are experiencing what is known as the "double-hop" (1) limitation of NTLM. You must use a dedicated account on the server side, or if you really do want to use the logged-in user's identity, you must use an authentication scheme that permits delegation, such as Kerberos.
If you really need the user's identity to access SharePoint data and you cannot change the authentication scheme, then the best way to do this is to use the JavaScript CSOM. This means the user is authenticating directly to the SharePoint server (a single hop, not double) and your ASP.NET site serves the page containing this script to the user.
(1) http://blogs.msdn.com/b/knowledgecast/archive/2007/01/31/the-double-hop-problem.aspx
Use Default Credentials worked for me:
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.UseDefaultCredentials = true;
Setup the crendentials by code:
SP.ClientContext context = new SP.ClientContext("MySPDevInstance");
context.Credentials = new NetworkCredential("username", "password");
You should put this at the configuration file to change it without publishing or recompiling the application.
Just to add one more setting that I encountered. If the account is restricted to access only certain servers than add the client machine to that account as well. For example if a web application is hosted on Server A and trying to connect to SharePoint 2010 on Server B with account ABC then make sure that account has access to Server A in Active Directory. Normally the AD account doesn't have restrictions to connect to machines but in my case the account was restricted to only certain machines. I added my web application hosted server to the account and it worked.

changing aspnet user to the domain user to access iis

I'm running IIS5.0 and I am trying to change the ASP.NET process account to my domain user account.
I have followed everything possible here.
When I browse the .svc file (this is a wcf service) I am getting this error:
Server Application Unavailable The
web application you are attempting to
access on this web server is currently
unavailable. Please hit the "Refresh"
button in your web browser to retry
your request.
Administrator Note: An error message
detailing the cause of this specific
request failure can be found in the
application event log of the web
server. Please review this log entry
to discover what caused this error to
occur.
Eventlog says:
aspnet_wp.exe could not be started.
The error code for the failure is
80070522. This error can be caused when the worker process account has
insufficient rights to read the .NET
Framework files. Please ensure that
the .NET Framework is correctly
installed and that the ACLs on the
installation directory allow access to
the configured account.
When I run the client, I get the following error:
The content type text/html;
charset=utf-8 of the response message
does not match the content type of the
binding (application/soap+xml;
charset=utf-8). If using a custom
encoder, be sure that the
IsContentTypeSupported method is
implemented properly. The first 872
bytes of the response were: '
From ASP.NET 2.0 onwards, the correct method to ensure that a user account has the correct rights to run as the worker process identity is to run this command:
aspnet_regiis -ga [account]
You need to run the aspnet_regiis command that matches the ASP.NET version you plan on running:
ASP.NET 2.0 -
%SYSTEMROOT%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -ga [account]
ASP.NET 4.0 -
%SYSTEMROOT%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ga [account]
If you put your Domain Account under IIS_WPG group, it should ideally work. If it doesn't work, there is a sure shot way of fixing it.
In IIS 6... step 1 is applicable... since you are on IIS 5, ignore step 1
Run it with Local System to begin with. If the applications runs, it means your IIS is configured well and you can proceed with the step 2.
Change the account to your domain account, and ensure that you have put the account in IIS_WPG as well. After that, run the tool called Process Monitor http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx
Browse the application now. If you still get the error, switch to the Process Monitor and stop capture [menu option].
Search for Access denied and fix it. Link

Calling Remote Web Service -- "The request failed with HTTP status 401: Unauthorized"

I am calling a remote service and authenticating using a certificate. When testing with a Console App, everything works fine. When calling from an ASP.NET Website (.NET 4.0, IIS7) I receive a response code of 401 -- Unauthorized.
I am adding the certificate using code such as:
var client = new TheGeneratedProxy();
client.ClientCertificates.Add(new X509Certificate("D:\cert.pfx", "myPassword"));
(NOTE: I have also loaded the .pfx into the local Certificate Store using IE. The certificate is loaded into my "Personal" store -- so I suspect this to be the problem, since the Website will be running under a different account.)
I think the problem is that your IIS user (Network Service / ASPNET) doesn't have access to the certificate. In order to grant Network Service to access the certificate in the store, download the following tool: winhttpcertcfg (http://www.microsoft.com/downloads/details.aspx?familyid=c42e27ac-3409-40e9-8667-c748e422833f&displaylang=en)
Now open command prompt and type:
winhttpcertcfg –g –c LOCAL_MACHINE\My –s ORGNAME –a "Network Service"
Please note that "Network Service" can be substituted with any other account. I.e. if you you have configured a custom user for your app pool, you should put this user as the value for the -a parameter.
ORGNAME should be substituted with the Organisation name you specified during the creation of your cert.

Access Denied errors accessing IIS WMI provider from ASP

I have a Windows 2003 server running IIS 6 and have some scripts that do automated setup and creation of websites. They are not working on a new server I cam commissioning (they already work happily on 3 other W2K3 servers). The problem appear to boil down to WMI security on the IIS provider. The ASP code below represents the problem (although it is not the original code that causes the problem - this is a simplified demonstration of the problem).
Set wmiProvider = GetObject("winmgmts:\\.\root\MicrosoftIISv2")
If wmiProvider is Nothing Then
Response.Write "Failed to get WMI provider MicrosoftIISv2<br>"
End If
Response.Write "Querying for IISWebService...<br>"
Set colItems = wmiProvider.ExecQuery("Select * From IISWebServer",,0)
Response.Write "Error: " & Hex(Err.Number) & " (" & Err.Description & ")<br>"
If I run this in my browser, I get an access denied error reported after the ExecQuery call. I have set WMI access for the IUSR_ user from the Root branch all the way down. In fact, I can query for IP address information using the CIMV2 provider quite happily. If I put the IUSR user in the machine admins group it all works, but I don't really want to do that.
This must be a DCOM/WMI security problem, but I can't work out what else there is. Can anyone shed any light?
After reading G. Stoynev's comment asking if any events were logged in the Windows Logs, I checked the event logs on the server to which I'm attempting to access IIS remotely via WMI, and lo and behold I found an event with the following text:
Access to the root\WebAdministration namespace was denied because the namespace is marked with RequiresEncryption but the script or application attempted to connect to this namespace with an authentication level below Pkt_Privacy. Change the authentication level to Pkt_Privacy and run the script or application again.
See the code in this answer to the related SO question c# - "Access is denied" Exception with WMI.
Here's some example C# code that I added that seemed to resolve this issue for me:
ConnectionOptions options = new ConnectionOptions();
options.Authentication = AuthenticationLevel.PacketPrivacy;
ManagementScope managementScope = new ManagementScope(#"\\remote-server\root\WebAdministration", options);
// ...
If this is something that you intend to run as a tool for yourself or your admin (as opposed to the unwashed anonymous masses), here is a way I have used in the past (YMMV):
Set up a new directory in your website (e.g. /SiteCreate) and place your WMI scripts there
Configure a Windows user that has appropriate rights (probably admin in this case but you should use whatever is pertinent to your app)
Turn off the anonymous access to the directory you created in step 1 and then set the security to allow access only to the user you created in step 2 (turn on the authentication for that directory)
Now, when you navigate to that directory in your browser, you should get a login prompt. When you enter the username/password you created in step 2 your script will have the appropriate rights to perform your WMI requests.
Not a DCOM issue, more so a WMI security and encryption issue. Try changing the GetObject moniker to include impersonation and pktPrivacy, eg:
Set wmiProvider = GetObject("winmgmts:{impersonationLevel=impersonate;authenticationLevel=pktPrivacy}!\root\MicrosoftIISv2")
Refer to the follow MS article for more info:
http://msdn.microsoft.com/en-us/library/aa393618(v=vs.85).aspx

Resources