HttpWebRequest and Authentication - asp.net

I am trying to use Forms Authenication with the httpwebrequest but I seem not to have any success. Here is what I am doing:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = WebRequestMethods.Http.Get;
// Authentication items -------------------------------------------
request.UseDefaultCredentials = false;
request.PreAuthenticate = true;
// Attempt to set username and password:
CredentialCache cc = new CredentialCache();
cc.Add(
new Uri(url),
"Basic",
new NetworkCredential("username", "validpassword", "domain")
);
request.Credentials = cc;
request.AllowAutoRedirect = true;
request.KeepAlive = true;
request.Timeout = 10000;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
// request html
response = (HttpWebResponse)request.GetResponse();
The problem is that even with a valid password and username for the domain this is always throwing an exception.
Can anyone help?
NOTES:
Exception Type: WebException
Exception Message: "The remote server returned an error: (401) Unauthorized."
Exception Status: Protocol
Error Exception Occurring at: response =(HttpWebResponse)request.GetResponse();
Exception Stack Trace: None
... sorry

I add Credentials for HttpWebRequest .
myReq.UseDefaultCredentials = true;
myReq.PreAuthenticate = true;
myReq.Credentials = CredentialCache.DefaultCredentials;
I’d like to know the sub status code of the 401 error you encountered. The 401 error contains the following sub status code:
401.1: Access is denied due to invalid credentials.
401.2: Access is denied due to server configuration favoring an alternate authentication method.
401.3: Access is denied due to an ACL set on the requested resource.
401.4: Authorization failed by a filter installed on the Web server.
401.5: Authorization failed by an ISAPI/CGI application.
401.7: Access denied by URL authorization policy on the Web server.
Because the project works well on your machine, I doubt it is a process identity issue. By default the application pool in IIS 6.0 uses “Network Service” as its identity. This account is restricted, so that you may encounter access deny issue.
For troubleshooting purpose, please try to change the application pool’s identity to “Local System”. If this method can resolve the issue, change back the identity to “Network Service”, and grant read/write permission to the xml file you want to read/write.
About how to change application pool’s identity, please refer to the following steps:
1. Open IIS manager (Start | Control Panel | Administrative Tools | Internet Information Services Manager).
2. Expand the “Application Pools” node.
3. Right click the application pool which your project is using, and then select “Properties”.
4. Click “Identity” tab.
5. Choose “Local System” in the Predefined dropdown list.
About how to grant permission to a file, please check these steps:
1. Open Windows Explorer.
2. Right click the file, and then select "Properties".
3. Click the "Security" tab.
4. Add "Network Service" in access list and check "Modify", "Read", and "Write" for it.
In addition, other files may cause this issue too, you can use Filemon to monitor any access file deny issues.
FileMon for Windows v7.04
http://www.microsoft.com/technet/sysinternals/FileAndDisk/Filemon.mspx

Related

Reporting Services 2008 - 401: Unauthorized

I've an application that connects to Reporting Services in SQL Server 2008 R2.
The error is the following:
System.Net.WebException: The request failed with HTTP status 401: Unauthorized.
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse
(SoapClientMessage message, WebResponse response, Stream responseStream,
Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke
(String methodName, Object[] parameters)
at Microsoft.SqlServer.ReportingServices2005.Execution.ReportExecutionService.LoadReport
(String Report, String HistoryID)
The application is running in production fine in 2 different customers, so it's not a codeing issue.
I'm trying to install it now on a customer's server, which is using AD. The SQL Server and the IIS is all in the same machine though, so I don't really care about AD.
It runs if I run IE as Administrator, but it doesn't work with other users. The ASP.NET app is connecting to SSRS using a user created in the local machine (called ReportingServicesUser), member of the ReportingServicesUser group.
Things I've tried:
Adding ReportingServicesUser to the Site Settings in the RS website (did the same for Network Service, IUSR, the Authenticated Users group, Local Service, etc)
Adding ReportingServicesUser to the folder permissions in the RS website (did the same for Network Service, IUSR, the Authenticated Users group, Local Service, etc)
Added permissions for that users to the databases (app database and RS related dbs)
Added NTFS permissions to the RS folders (I will double check though).
Connecting to the RS using http://localhost, http://computername and http://domain.com
For reference, the code is this (simplified version):
var service = new ReportExecutionService();
service.Credentials = new NetworkCredential("ReportingServicesUser", "password");
service.Url = "http://computername:90/ReportServer/ReportExecution2005.asmx";
service.ExecutionHeaderValue = new ExecutionHeader();
var execInfo = new ExecutionInfo();
execInfo = service.LoadReport("path-to-the-report", null);
===> Here it throws the exception
I've read a lot of posts and pages about this but I cannot get an answer that works for me.
OK, I've finally had to change the code to:
rs.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
and it worked. Probably there's another solution but I couldn't find it out.
Are you sure you gave "ReportingServicesUser" browse permissions for the specific report in ssrs? The request never made it to the server it seems but I would check \Reporting Services\LogFiles just to be certain.
Also, Your "report user" user needs to be defined on the reporting server with the credentials you send.

Get token from ADFS

I'm trying to obtain a token from ADFS to that I can use it with an on-premise Windows Service Bus installation. I may not have ADFS properly configured because I get the following message:
MSIS3127: The specified request failed.
The code to access the token is as follows:
string adrecaSTS = "trust/13/usernamemixed";
WS2007HttpBinding binding = new WS2007HttpBinding();
binding.Security.Message.EstablishSecurityContext = false;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
binding.Security.Mode = SecurityMode.TransportWithMessageCredential; //https
string baseSSLUri = #"https://<myadfs>/adfs/services/";
WSTrustChannelFactory trustChannelFactory = new WSTrustChannelFactory(binding, new EndpointAddress(baseSSLUri + adrecaSTS));
trustChannelFactory.TrustVersion = TrustVersion.WSTrust13;
trustChannelFactory.Credentials.UserName.UserName = "username";
trustChannelFactory.Credentials.UserName.Password = "password";
WSTrustChannel tokenClient = (WSTrustChannel)trustChannelFactory.CreateChannel();
//create a token issuance issuance
RequestSecurityToken rst = new RequestSecurityToken(RequestTypes.Issue);
//call ADFS STS
SecurityToken token = tokenClient.Issue(rst);
The endpoint is enabled on ADFS and my client (laptop on separate domain) trusts the certificate from ADFS.
Do I need to set up some kind of trust or something further? This error message is not particularly helpful.
See here:
https://github.com/thinktecture/Thinktecture.IdentityServer.v2/blob/master/src/Libraries/Thinktecture.IdentityServer.Protocols/WSFederation/HrdController.cs
The ValidateToken method has most of the code - but you first need to extract the InnerXml from the generic token and turn that into a SAML security token (again using a token handler).
Found the issue. I was trying to log on as an administrator account. When I used a regular user it worked.
I also had to modify the RequestSecurityToken to have a KeyType of KeyType.Symmetric
I see that you solved your issue, but here is some additional inforamation to potentially help others that might have the same error message but a different cause.
The AD FS error, "MSIS3127...", can have multiple causes. For us, it was caused by one of our relying party claim rules specifying an AD FS attribute store that didn't exist.
In order to debug the error, we checked the Event Viewer on all of the servers running AD FS, and that's where we found the detailed message that called out the attribute store problem. So, if anyone else gets the same error message, then I suggest checking the Event Viewer on AD FS to see if there are additional logs.
Note that AD FS logs to the Event Viewer under the folder/node of Applications and Services Logs => AD FS => Admin

Webservice with Clientcertificate gives error Could not create SSL/TLS secure channel when running in IIS

I have the following code to access a webservice using a Client certificate. All seems to work fine when I run this code in a console application. If I try to run it from a web application running in IIS 7. I get the error "The request was aborted: Could not create SSL/TLS secure channel."
This is the code :
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Ssl3 | System.Net.SecurityProtocolType.Tls; //from other stackoverflow case
System.Net.ServicePointManager.Expect100Continue = true; //from other stackoverflow case
db2wsService service = new db2wsService();
service.Url = this.WebserviceUrl;
HttpServerUtility server = HttpContext.Current.Server;
X509Certificate certificate = new X509Certificate(server.MapPath(this.CertificatePath), this.CertificatePassword);
service.ClientCertificates.Add(certificate);
service.PreAuthenticate = true;
//do some stuff here to call webservices
I had same encountered problem. this solution is winhttpcertcfg. if you search about using on the google , you will find it.

How to pass HostingEnvironment.Impersonate credentials to ExchangeService EWS?

Is it possible to pass the credentials of the user browsing my asp.net web application to the EWS FindAppointments call?
I'm only trying to return calendar details for the active browsing user, who will without doubt have permission to read their own calendar, so the issue should not relate to Exchange impersonation with the EWS api discussed here.
The code below works just fine when running localhost, but running from the web server, despite Windows Authentication and Identity Impersonation being configured it throws an access denied error.
using (HostingEnvironment.Impersonate())
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.UseDefaultCredentials = true;
service.AutodiscoverUrl(UserEmailAddress);
Mailbox mb = new Mailbox(UserEmailAddress);
FolderId cfCalendarFolderID = new FolderId(WellKnownFolderName.Calendar, mb);
CalendarView cvCalendarView = new CalendarView(DateTime.Now, DateTime.Now.AddDays(30), 1000);
cvCalendarView.MaxItemsReturned = 3;
Perhaps I'm missing a simple way to pass the HostingEnvironment credentials to my ExchangeService object?
Is there a way to check what the service.UseDefaultCredentials are?
I'm not able to use the following as there isn't a way to get the password from the windows authenticated impersonated user.
service.Credentials = new System.Net.NetworkCredential(username, password, domain);
I've also tried the following, but get the same ServiceResponseException access denied errot.
service.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
service.PreAuthenticate = true;
Thanks in advance of your kind assistance.
Additional info which may or may not be relevant:
The Application Pool Identity for the website is NetworkService.
The UserEmailAddress variable is set from an AD lookup based on System.Security.Principal.WindowsIdentity.GetCurrent().Name
EDIT (14th Aug 2012)
To achieve what I'd like to do above, I believe the HostingEnvironment.Impersonate isn't required.
Instead I need to use the ExchangeService's ImpersonatedUserId property.
More details on that here
Only problem though is we're running Exchange 2007 and the power shell command for enabling a service account to impersonate all users (that you would use pass in to the .Credentials parameter) only appears to be compatible with Exchange 2010.
You should try using WebCredentials instead of NetworkCredential - see related SO post. There seems to be an issue with EWS and AutoDiscover + NetworkCredentials

Login error connecting to salesforce.com from Flex

Has anyone suddenly encountered login errors from their users trying to connect to salesforce.com from a Flex app using as3salesforce.swc?
I get the following error... password removed to protect the innocent...
App Domain = null
Api Server name = na3.salesforce.com
_internalServerUrl = https://na3.salesforce.com/services/Soap/u/14.0
loading the policy file: https://na3.salesforce.com/services/Soap/cross-domain.xml
Your application must be running on a https server in order to use https to communicate with salesforce.com!
login with creds
loading the policy file: https://na3.salesforce.com/services/crossdomain.xml
Your application must be running on a https server in order to use https to communicate with salesforce.com!
invoke login
intServerUrl is null
intServerUrl = https://na3.salesforce.com/services/Soap/u/14.0
_invoke login
'5A5D3012-7717-E3C2-9B39-FFBBFF1F1B47' producer set destination to 'DefaultHTTPS'.
Method name is: login
'direct_http_channel' channel endpoint set to http://localhost/pm_server/pm/
'5A5D3012-7717-E3C2-9B39-FFBBFF1F1B47' producer sending message 'E32C7199-72C1-B258-B483-FFBC1641173D'
'direct_http_channel' channel sending message:
(mx.messaging.messages::HTTPRequestMessage)#0
body = "<se:Envelope xmlns:se="http://schemas.xmlsoap.org/soap/envelope/"><se:Header xmlns:sfns="urn:partner.soap.sforce.com"/><se:Body><login xmlns="urn:partner.soap.sforce.com" xmlns:ns1="sobject.partner.soap.sforce.com"><username>simon.palmer#dialectyx.com</username><password>******</password></login></se:Body></se:Envelope>"
clientId = (null)
contentType = "text/xml; charset=UTF-8"
destination = "DefaultHTTPS"
headers = (Object)#1
httpHeaders = (Object)#2
Accept = "text/xml"
SOAPAction = """"
X-Salesforce-No-500-SC = "true"
messageId = "E32C7199-72C1-B258-B483-FFBC1641173D"
method = "POST"
recordHeaders = false
timestamp = 0
timeToLive = 0
url = "https://na3.salesforce.com/services/Soap/u/14.0"
'5A5D3012-7717-E3C2-9B39-FFBBFF1F1B47' producer connected.
Method name is: login
Error: Ignoring policy file at https://na3.salesforce.com/crossdomain.xml due to meta-policy 'by-content-type'.
'5A5D3012-7717-E3C2-9B39-FFBBFF1F1B47' producer acknowledge of 'E32C7199-72C1-B258-B483-FFBC1641173D'.
responseType: Fault
Saleforce Soap Fault: sf:INVALID_LOGIN
INVALID_LOGIN: Invalid username, password, security token; or user locked out.
Comunication Error : sf:INVALID_LOGIN : INVALID_LOGIN: Invalid username, password, security token; or user locked out. : [object Object]
Obviously nobody else out there is building Flex apps on top of salesforce.com..
yippee, I'm first.
Anyhow, I just found out that this is a bug at salesforce.com as at 6th December 2008. The issue is that the scripts which handle login do not cope adequately with the redirect necessary because of load balancing on the salesforce.com servers.
It should be possible to go through the www front door of salesforce.com's api with a URL such as...
"https://www.salesforce.com/services/Soap/u/13.0";
where the 13 represents the version of their API you are targetting. However, all users are actually assigned to a specific server, so the front door should redirect the login request to the approriate place, and it doesn't if you are coming from Flex.
A workround is to specify your server in the URL, such as...
"https://na5.salesforce.com/services/Soap/u/13.0";
...which is what I was doing. That's fine if you are a single user accessing the same resources continually and your account remains attached to that server. However if...
You are distributing your app so anyone who has a salesforce.com enterprise account can log in OR
Your account gets moved because of some internal load balancing (which is what happened to me)
then the approach of providing a fixed server won't work.
The bug (as far as I understand it) is that the www route doesn't adequately redirect to your host server. Last intelligence was that it will be fixed "soon".
I wish I could mark this as the answer...

Resources