AD User Authentication - asp.net

I am attempting to create an ASP.NET (.NET 3.5) website to connect to our Exchange 2010 server through Exchange Web Services, I am able to connect to EWS when I define the username, password and domain to authenticate with but I would like, if possible, to not include login details in my code.
In IIS I have enabled Integrated Windows Authentication for the site, in web.config of the site I have <authentication mode="Windows"/>.
The following code is what I have been woking with:
svc.UseDefaultCredentials = True
svc.Credentials = New WebCredentials()
svc.Url = New Uri(svcURL)
With the above code I am receiving the message:
When making a request as an account that does not have a mailbox, you
must specify the mailbox primary SMTP address for any distinguished
folder Ids.
When I attempt to use svc.Credentials = CredentialCache.DefaultNetworkCredentials (in place of svc.Credentials = New WebCredentials()) I receive the error message:
Unable to cast object of type 'System.Net.SystemNetworkCredential' to
type 'Microsoft.Exchange.WebServices.Data.ExchangeCredentials'.
As mentioned, the only thing that has worked is to define the user credentials to authenticate to by hardcoding user login details, which I would rather not do: svc.Credentials = New WebCredentials("username","password","domain")
Has anyone been able to authenticate to EWS using the credentials of the current logged in user in an ASP.NET website?

By default it is not possible to delegate a user's credentials from one server (the server on which you are hosting your ASP.NET site) to another (your Exchange server). This is known as a "server hop" and Windows will prevent it by default as a security measure.
You have a couple of options to work around this:
Using Kerberos: When Kerberos is enabled it makes it possible to delegate user credentials between servers when using Windows authentication. I do not know the exact details on how to set up Kerberos as I am only a humble developer but maybe your system administrator can assist you. AFAIK, you need to set up your ASP.NET server to allow user delegation.
Setting the user identity of your IIS application pool: If Kerberos is not an option, you may change the identity of the application pool that your ASP.NET site is running under. First define a new application pool in IIS manager. Then go to the Advanced Settings dialog for that application pool and set the identity to a domain user that is allowed to access your Exchange server. More info on the application pool identity here: http://technet.microsoft.com/en-us/library/cc771170(v=WS.10).aspx.
Setting the <identity> element: If you for some reason cannot change the application pool, you may try impersonation of your ASP.NET web site using the <identity> element in your web.config file. ASP.NET gives you the option of storing the credentials in the registry so that you do not have to put them directly in your web.config file. More info here: http://msdn.microsoft.com/en-us/library/72wdk8cc(v=vs.90).aspx
Using the <appSettings> ellement and encryption: The last option I can think of is to simply put the credentials in your web.config file as normal <appSettings> and then encrypt the entire <appSettings> section. You would then simply read the appSettings from your code using the AppSettingsReader class. .NET allows you to encrypt sections of the web.config file out of the box and you can read the settings without event noticing that the section is encrypted. .NET takes care of decrypting for you. More info here: http://msdn.microsoft.com/en-us/library/zhhddkxy.aspx

Related

SSO with Windows Authentication across multiple REST-APIs? (Kerberos Double hop)

I have the following scenario:
(Client/Browser) => (Web Service/Web API) => (SharePoint REST-Api).
Basically what I want to achive is to have the middle application (WebService/Web API) to act as a facade infront of the SharePoint-REST-API to ease the development for anybody that needs to communicate with our SharePoint-application. (Basically we wrap a few SharePoint-request-calls into one single call in the Web API/Facade).
Now the problem is that I also want to be able to send the logged in Windows user (AD-user) from the Client to the Web Service, and then the web service should act on behalf of that Windows user and perform whatever actions needed in the SharePoint REST-API (this is to make sure that permissions to files and so on are actually set based on the authenticated user).
What we have tried so far is setting uo the Web Service on one server, and SharePoint on a different server.. and then we have tried to setup authentication using Kerberos and delegation, but we could not get this working.
Based on the information I have provided, do you guys think that a "double hop" like this would work if we manage to get Kerberos setup properly?
Another thought that hit me is that maybe we dont have to host the Web Service and the SharePoint applications in two different servers, but we could actually host them both on the same server within one single IIS-server with two sites.
Would this still require Kerberos to be setup with a double hop? Or does a "hop" only count once the ticket actually leaves one server to another.. cause in the case described here, the request from the Web Service to the SharePoint-REST-API would never leave the actual server, but it might cross domains (as in web-domains.. not AD-domains).
Could this work, instead of having to hassle with Kerberos double hop, SPNs and what not..?
when you use integrated authentication, anonymous is disabled at that time and impersonate is enabled.so security settings will not allow your site to access resources on any network servers.
When you authenticate to the IIS server using Integrated Authentication, that uses up your first 'hop'. When IIS tries to access a network device, that would be the double or second hop which is not allowed. iis will not pass those credential to the next network device.
if you use anonymous enable and impersonate off this issue will not occur.
to configure Kerberos Authentication in iis you could follow the below steps:
1)open iis manager and select site.
2)select the authentication feature from the middle pane.
3)enable windows authentication and disable anonymous.
4)With Windows Authentication, click on the Providers from the Action pane.
5)set the provider in below manner:
Negotiate
NTLM
save the changes.
6)go back and select the configuration editor.
from section dropdown select system.webServer/security/authentication/windowsAuthentication.
“useAppPoolCredentials” set to true.
"useKernelMode" to "True" and save the settings.
7)restart the iis.
8)Configure SPNs
open the command prompt as administrator and run below command to check the machine name:
hostname
When you have a custom hostname and you want to register it to a domain account, you need to create a SPN a below.
setspn -a HOST/${FQDN_HOST} ${MACHINE_NAME}
setspn -a http/${FQDN_HOST} ${MACHINE_NAME}
9)after doing that set application pool identity to the custom account and set the username and password.
You could refer this below article for more detailed information:
https://weblogs.asp.net/owscott/iis-windows-authentication-and-the-double-hop-issue
https://active-directory-wp.com/docs/Networking/Single_Sign_On/SSO_with_IIS_on_Windows.html
https://techcommunity.microsoft.com/t5/IIS-Support-Blog/Setting-up-Kerberos-Authentication-for-a-Website-in-IIS/ba-p/324644

ASP.Net web application trying to use Impersonation and Delegation to connect to SQL Server

I'm trying to use Impersonation and Delegation in an intranet ASP.Net web-app in order to pass authenticated users' credentials onto a SQL Server.
The web server and SQL server are two separate machines, but in the same domain, so Delegation is required.
I've done the following:
set <authentication mode="Windows"/> and <identity impersonate="true"/> in my web-app's web.config.
enabled Constrained Delegation from the web server to the MSSQLSvc service on the SQL Server, in Active Directory.
enabled only Windows Authentication in the website, through IIS.
Apparently this should all work, but it doesn't (the SQL Server is denying access to the anonymous user - "Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'").
In IIS7, the Application Pool is set to use Integrated Pipleline Mode and is running with the NetworkService Identity. The website only has Windows Authentication enabled, Extended Protection is Off, Kernel-mode authentication is enabled, and NTLM is the provider.
All the web pages I've read seem to indicate that my setup should work. What am I missing?
I've discovered the answer:
The Windows Authentication provider in IIS7 must be set to Negotiate:Kerberos, not NTLM. This means that the Kernel-mode authentication setting must be disabled. This seems to be fine. I think I'm right in saying that Kernel-mode authentication is required when using a custom identity, i.e. one specific identity. Delegation can use an arbitrary number of identities. So all is well.
I've written a blog post about this too, which goes into a bit more detail.
No - it is not accurate to say you need Kerberos, an SPN, to trust the server for delegation, and that this is the ONLY way to do it. Yes, this is one way to do it (and you do need all of it to make it happen via Kerberos), but it is not the ONLY way, or even technically the most secure way or easiest way. Do you really want to have to do extra configurations and create a login for every web user to your DB in SQL? What if any one of those accounts is compromised? More accounts, more vulnerabilities.
No, create a Domain service account, instead, and let that access SQL. If your security guys lock down things, give that user these rights: Logon as a service, Logon as a batch job, and Allow logon locally. Or, if this is just to develop and test the theory or you don't care or can't find the settings or are still getting errors later on, and this might not get a large following, but give it local Admin (sometimes you gotta do what you gotta do - some security pros lock down things tighter than I would care to write about - can always troubleshoot security later to lock it back down). Then set that account as the custom account on the app pool and give that account a login in SQL. Give it dbo on just THAT ONE database.
On the website in IIS, set the authentication type as Windows. I've seen them say "Basic" in other blogs so Kerberos will work, but NTLM uses Windows authentication. In IIS 7, you may also want to enable ASP .NET impersonation. Personally, I've only tried this on IIS 6, but the principal is the same.
In the web.config, add this under <configuration>, which is a "peer" to <system.web>:
<connectionStrings>
<add
name="NorthwindConnectionString"
connectionString="Data Source=serverName;Initial
Catalog=Northwind;Integrated Security=SSPI;User
ID=userName;Password=password"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
And in <system.web>:
<authentication mode="Windows"/>
<identity impersonate="true"
userName="domain\user"
password="password" />
Then read the string into your app like this:
using System.Configuration;
string connString = String.Empty;
if (ConfigurationManager.ConnectionStrings.ConnectionStrings.Count > 0)
{
connString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
if (connString != null) // do DB connection stuff here
Console.WriteLine("Northwind connection string = \"{0}\"",
connString.ConnectionString);
else
Console.WriteLine("No Northwind connection string");
}
See http://msdn.microsoft.com/en-us/library/ms178411.aspx.
If it will not connect with the service account after filling in that account in the web.config for the impersonate tag and the SQL connection, you can then use impersonation methods using WindowsImpersonationContext (http://msdn.microsoft.com/en-us/library/system.security.principal.windowsimpersonationcontext.aspx). Specifically, you want wic.Impersonate() and wic.Undo() after getting their token. You can read in the service account domain, name, and password from the web.config, in the form of AppKeys.
In short, there are ways around the issues. You can even encrypt the password in the web.config - both in the ConnectionString, and if you want to store it in an AppKey instead of directly in the "impersonate" tag, if you don't want plain text passwords in there (which I'd recommend against), and so you can have it for the creation of a Logon token, if you need to use the Impersonation methods (as I did).

ASP.NET web app can't use multiple impersonation for authenication

I have a asp.net app (uses windows authentication for access) which (stipulated by the security team) needs to connect to a remote SQL Server 2005 using integrated security.Because of the fact that it is remote SQL server I needed to impersonate a custom account (impersonating the original caller would not work) via :
<identity impersonate = "true" userName="domainname\user" password="password" />
This workes fine. The rub is my app also connects to an SSRS server for reporting needs using the ReportViewer control. The report server is on a separate server and the security team mandates that all calls to this server must be using the original window's account for auditing purposes. It seems my only option was to to try and separate my app into folders and use a "location" tag in my web.config and use separate identity tags. Such as:
<location path="Reporting">
<system.web>
<identity impersonate = "true"/>
</system.web>
</location>
Note: no username and password specified which means it should impersonate the original caller.
However to make matters even more complicated my app is a Masterpage/content page app. The master page makes calls to SQL to populate menus and such. Bottom line is the dual impersonation track is not working. I am ready to throw my hands up and declare that that this can not be done. If there was a way where I could have the app impersonate the original caller which would satisfy my SSRS auditing needs yet make connections to SQL server as the custom domain account. I cannot use SQL authentication: not allowed although that would solve this issue.
Have you tried the following setup:
Set impersonation to true. This is necessary for authentication into the application and for access to the SSRS to use current user logged in.
Use one connection string to SSRS that has Integrated Security set to true, so that the impersonated user passes straight through.
Use a second connection string, with the custom user name and password hard coded into the connection string. You can encrypt the connection string section of the web.config so that it isn't visible to human eyes, but the framework will automatically decrypt this on the fly when creating a connection.
I have a similar situation (need a specific account to retrieve specific data, but the general impersonation for the rest of the service functionality) and this setup is working.
EDIT: The general syntax for encrypting your web.config from the command prompt is:
aspnet_regiis -pef "connectionStrings" [PhysicalPathToApplication] -prov "DataProtectionConfigurationProvider"
Encryption is done on a machine per machine basis, so the encryption will have to be done on the specific server. You can pull up more documentation on this if needed.
You should be able to switch the impersonation on and off, so you can go back to using the default account running the site. I will have to check, it's been a while since I have done it.
This looks like a start as to how to do it:
System.Security.Principal.WindowsImpersonationContext impersonationContext;
impersonationContext =
((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate();
//Insert your code that runs under the security context of the authenticating user here.
impersonationContext.Undo();
Essentially you just impersonate the appropriate user for the calls you need, and then "undo" the context and turn it off. It goes back to the default user after that.
Here is a link to the windows identity class:
http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.aspx

DefaultCredentials in Accessing CRM / Sharepoint Web Services

I made an application that access CRM's web service. The problem is, when I deployed the dll into Sharepoint server, it returned error 401 unauthorized. Apparently the System.Net.CredentialCache.DefaultCredentials didn't work (my suspicion). Here's the code.
CrmSdk.CrmAuthenticationToken token = new CrmSdk.CrmAuthenticationToken();
token.AuthenticationType = AuthenticationType.AD;
token.OrganizationName = ORGANIZATION_NAME;
CrmService service = new CrmService();
service.Url = "http://crmserver:5555/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.PreAuthenticate = true;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
It goes vice-versa.
When I made application that access Sharepoint's webservice (coding the plugin) and deployed it to CRM server. It couldn't access the Sharepoint's web service. Unauthorized error. Here is the code:
Lists listService = new Lists();
listService.PreAuthenticate = true;
listService.Credentials = System.Net.CredentialCache.DefaultCredentials;
listService.Url = "http://sharepointserver/webname/_vti_bin/Lists.asmx";
My CRM server and Sharepoint server are in the same domain.
For both code, if I changed the credentials part into something like this then deploy it on server, it can run.
service.Credentials = new NetworkCredential("username", "password", "domain");
Still, I don't want to do this because it reveals user's password in the code. May anyone help me?
The IIS in both server doesn't allow Anonymous Access and it uses Integrated Windows Authentication.
Thank you
From my local computer, I can access the CRM web services or Sharepoint web services. I guess I'm authorized because the DefaultCredentials sent my credentials that its password is saved in the "Stored Username and Password" (Control Panel > User Accounts > tab Advanced > Manage Passwords)
This way, I don't have to type:
service.Credentials = new NetworkCredential("username", "password", "domain");
and my DefaultCredentials from my local comp is authorized to access the web services.
I tried to implement this on the Sharepoint server that access CRM web services. and..tadaa..it won't work. hahaha..
can we inject credentials to DefaultCredentials in server?
the last thing I want to do is to hardcode the useraccount (like the code above)
Could be that you need to be running Kerberos for authentication, but cannot be sure and it is a pain to setup just to check.
Have you verified that the default credentials are the same as those when you explicitly state them? It could be that the default credentails are those of another account that you wouldn't expect.
EDIT #1: Per the remarks for the DefaultCredentials property on MSDN:
DefaultCredentials represents the
system credentials for the current
security context in which the
application is running. For a
client-side application, these are
usually the Windows credentials (user
name, password, and domain) of the
user running the application. For
ASP.NET applications, the default
credentials are the user credentials
of the logged-in user, or the user
being impersonated.
You'll also want to ensure that the user accessing the CRM page (making the call to the SharePoint web service) can access the web service with their credentials and vice versa. If they can then it would seem more likely that some kind of impersonation is happening.
Edit #2: Assuming that you have access to both the CRM and SharePoint server you might take a peak into both the application and system logs. One or both should likely indicate a failed login and indicate which account attempted to access the resource (in this case the web services).
By using DefaultCredentials means the ASP.NET worker process or IIS worker process will take the credential of the user who run the IIS Application Pool.
so if your Dynamics CRM Application Pool is run under a user account Custom-CRM-Domain\JohnDoe, that means it will take the privileges under user account Custom-CRM-Domain\JohnDoe.
Please check the user account who run the application pool of the CRM\Sharepoint Application IIS Web application.
These are the steps to check the Application Pool:
Open the website -> Right Click -> Choose Properties
Select the Home Directory tab
Notice the Application Pool name at the dropdownlist below
Now, go to the Application Pools folder
Try to find the Application Pool name which has been listed in the step 3 -> Right Click and choose Properties
Select the "Identity" tab and you will find the user account who run the application pool
Hope this helps.
service.Credentials = System.Net.CredentialsCache.DefaultNetworkCredentials;
Try that.
Not familiar with Sharepoint, but can't you just store the connection information in a configuration and use built in tools for securing your web.config? Thats what I do.
https://web.archive.org/web/20211029043331/https://aspnet.4guysfromrolla.com/articles/021506-1.aspx
to be able use defaultcredentials, the user in active directory must be defined both in SharePoint and CRM and have enough privileges to do what you are doing with code.
And try to use sdk (crm have helper classes) instead of service definitions.
For fixing this issue you need to know first which user is running the App pool as the others said and if you need to use CredentialCache.DefaultCredentials then you have to add the user lets say svcadmin or the like into "Secondary site collection administrator" by running SharePoint central administration application . By that SP allows to the user which the credential has been passed through to access the things it needs.

How do I set access permissions for the search web service in Search Server 2008 Express?

I have installed Microsoft Search Server 2008 Express on a Windows 2003 server and created a search content source (our corporate website) for testing. I can search this source just fine from the Search Centre.
From an ASP.NET web application I am trying to query the provided web service as described here
I am using impersonation settings in the web.config to specify the user account the request runs under but I cannot find out how to set up that user in the Search Server to allow it to make the query.
<authentication mode="Windows"/>
<identity impersonate="true" userName="MyDomain\MyUser" password="myPassword" />
If I use my own network credentials I get the results back, as I am set up with Full Control permissions in the Search Server instance, but when I use an alternate domain account for this (MyDomain\QueryUser) I get this error:
System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> Attempted to perform an unauthorized operation.
I have added the user to the server in Search Server > Site Settings > Permissions > Add Users and have given the account Full Control but it still cannot use the webservice. Is there a setting somewhere I am missing?
**EDIT
Ok, I have tried Gordon's suggestion and using the credentials the Sharepoint application is using makes the error go away. Also, adding the second domain user to the local Administrators group on the server makes the error go away.
What permissions are these changes granting the webservice? Do I have to resort to using these work arounds or can I give my domain user appropriate permissions in Sharepoint somewhere?
the key to access the Search webservice of MOSS is
1) to authenticate properly
2) to force the MOSS webservice to use that identity
for the first part check if all properties are properly assigned for your networkcredential, i usually provide these:
NetworkCredential credentials = new NetworkCredential(userName, password, domain);
service.PreAuthenticate = true;
service.Url = your_ws_fullurl;
service.UseDefaultCredentials = false;
service.useDefaultCredentialsSetExplicitly = true;
service.Credentials = credentials;
for the second part one solution is to remove the IUSR (IIS anonymous user) the right to access the /_vti_bin/Search.asmx file with IIS (got to the /_vti_bin/ folder, right click to file security properties), this way MOSS will retrieve the credentials provided in the credential cache and you won't have the "unauthorized operation" message

Resources