I have a problem in SignalR connection with Win Auth. When I enable anonymous in IIS Authorize settings, it works but sometimes it gives HTTP 403 Forbidden error. After I researched, I found that I need to disable Anonymous Connections. But when disable and enable the windowsAuth in IIS then there is always HTTP 401.2 UnAuthorized error. How I can connect with WinAuth? For my project I need to use WinAuth.
Not1 : I am using Silverlight 5.
Not2 : I have already tried possible solutions on StackOverflow but none of them worked.
So why cant I use WinAuth? It is enabled everywhere in config files, in IIS settings as well as in my web.config.
I spent 2 days but still I could not find a solution. If you need more information just write a comment. I am not sure what else information I can share. I dont want to put here lots of unnecessary texts.
EDIT:
When I use this code, i.e if I enter the username and password explicitly then it works. Internet Explorer first uses Anonymous Authentication and then it fails then it uses NetworkCredentials directly. This is the code
hubConnection = new HubConnection("URL");
hub = hubConnection.CreateHubProxy("HUBNAME");
hubConnection.Credentials = new System.Net.NetworkCredential("ID", "PASSWORD");
(The ones with capital letters are specific to my app.)
So how can I get Windows Credentials for my Silverlight App? DefaultCredentials does not work for silverlight.
Have you added authorization to your hub?
[Authorize(Roles = "Admin")]
public class AdminAuthHub : Hub
{
}
Related
There is a lot of relevant Info, I hope I won't forget anything. We want an automatic Windowslogin into an intranet website in our domain.
For testing on a client I'm using a chrome browser that has the website whitelisted.
The Server runs IIS Version 10.0.19041 running a ASP.NET 5 website. It connects to a database MS SQL Server in the same domain.
The Connection String has the parameter Integrated Security=SSPI and works with Apps running locally on clients.
This is what is happening for now: Normally the website would ask for credentials, but since it's in the white list I assume it now uses the Windows credentials, how it's explained here https://stackoverflow.com/a/24875309/15631999
using (SqlConnection Verbindung = new SqlConnection(sqlConnectString))
{
Verbindung.Open();
the "Login failed for user" error is thrown, because it tries to connect with the active webserver user, not with the automatically logged in client. System.Security.Principal.WindowsIdentity.GetCurrent().Name returns the account identity in the AppPool.
What we did: (might not all be relevant ...)
We googled a lot the last couple of days to find out what to do. The general keywords seem to be Windows Authentication, maybe impersonation, NTLM.
So we added the Authentication to the ConfigureServices. Now it looks like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews()
.AddXmlSerializerFormatters()
.AddXmlDataContractSerializerFormatters();
services.AddAuthentication(Microsoft.AspNetCore.Server.IISIntegration.IISDefaults.Ntlm);
services.AddSession();
services.AddAuthorization(options =>
{
options.AddPolicy("AuthorizationMode", (policy) =>
{
//unauthenticated
policy.RequireAssertion((e) => true);
});
});
//services.AddMvc();
services.AddHttpContextAccessor();
}
We also tried it with IISDefaults.AuthenticationScheme and without Authorization.
Configure Function snippet:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
SessionOptions s = new SessionOptions();
s.IdleTimeout = System.TimeSpan.FromMinutes(30);
s.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Lax;
s.Cookie.Name = ".acclaro.de.Session";
s.Cookie.IsEssential = true;
app.UseSession(s);
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
(...)
In IIS/Sites/[Website]/Authentication we disabled Anonymous Authentication and enabled Windows Authentication. This means, I think, I don't have to edit the web.config.
We tried it both with Impersonation enabled and disabled. Basic Authentication seem to always ask for Username and PW. So this is not what we want.
We read that I have to change the order of the Providers. Putting Negotiate under NTLM, or downright deleting it doesn't change anything.
I also read that I have to add SPNs. So I executed setspn -a http/[url] [domain controller computer name] at our domain controller.
I don't know what I'm missing. Maybe I just haven't tried the right combination yet. If anyone can help, that would be appreciated. ( Also I hope impersonating other users won't produce problems, when I write in a local temp folder on the Server. I had some Access denied Exceptions in the past. )
If some relevant info is missing, please tell me.
It's a common misconception that Windows Authentication implies Impersonation. When a user authenticates to a server with Windows Integrated auth, the code on the server doesn't automatically start running as that user.
The normal configuration for an Enterprise web app is for IIS to user Windows Auth to authenticate the users, but to connect to SQL Server using the IIS App Pool Identity.
If you want the users to connect as themselves to SQL Server through the web application, that's called "Impersonation" and you need to enable and configure it. There's a SO question here that shows how to perform impersonation in your middleware. But additional confgiuration, like Kerberos Constrained Delegation configuration may be required.
The downsides of doing this are
It's extra work to configure, and you may need your network admins to help.
If users can connect directly to the database through the app, they can do it through other tools too. So security administration is harder, and riskier.
Users can't reuse connections, so you'll have lots of idle connections.
I want to use ASP.NET SimpleMembership to authenticate users that consume my WebAPI. Thinktecture has a wonderful authentication library called Thinktecture.IdentityModel (http://thinktecture.github.com/Thinktecture.IdentityModel.45/) with an example that ties Forms Auth with Basic Auth (source). However, the example uses Membership.ValidateUser() which doesn't work without a ASP.NET Membership provider, which isn't supported by SimpleMembership (source) (edit: this isn't entirely true, see Mark's answer below).
Edit:
Here's what I did:
1) Create a new MVC Internet Application
2) Install Thinktecture.IdentityModel via NuGet
3) Create a model and an api controller via scaffolding:
public class Goober
{
public int GooberId { get; set; }
public string GooberWords { get; set; }
}
4) Ran the project, created a new user and created a new Goober using Fiddler
5) Added [Authorize] to GetGoober(int id)
6) In WebApiConfig.cs added:
var authConfig = new AuthenticationConfiguration();
authConfig.AddBasicAuthentication((userName, password) =>
Membership.ValidateUser(userName, password));
config.MessageHandlers.Add(new AuthenticationHandler(authConfig));
When I run the project and hit api/goober/1 with Fiddler I get a 401 www-Authenticate: unspecified. But if I log in first using the AccountController then use Fiddler I get a 200 and everything is peachy.
Edit
Okay, I think the problem isn't related to my initial question. I suspect it's related to the initialization of SimpleMembership in the template. When I open the project and run debug then hit the api with Fiddler I can't get past Auth. But when I simply click the "register" link on the web frontend I get past Auth. I'm guessing it's because the InitializeSimpleMembershipAttribute is called at the AccountController so doesn't initialize until the controller is called?
I've tried using WebSecurity.Login() in the place of Membership.ValidateUser() but that doesn't work.
I'm at a loss on how to actually implement this. Does anyone have any advice? Or maybe I'm attempting to tackle this problem from the wrong angle?
You are correct that ASP.NET Membership provider is not compatible with the SimpleMembershipProvider however SimpleMembershipProvider does support ValidateUser, see here. Assuming SimpleMembership is correctly configured and initalised you should still be able to call Membership.ValidateUser().
If you have already tried Membership.ValidateUser() and got an error please let me know and we can try resolve it.
Update
So having followed your reproduction steps I have managed to pin-point an error. Having brought the Thinktecture AuthenticationHandler handler inline and run in debug. 30 seconds after a request to the api controller a database connection error is being raised. This is failing asynchronously and silently.
After some fiddling around I believe it is the DefaultConnection connection string which is at fault.
Like me your default connection probably contains a file name like this:
AttachDBFilename=|DataDirectory|\aspnet-MvcApplication3-20121215104323.mdf"
When ValidateUser is called inside the delegate registered at app start up (for validating the credentials) it appears to be failing to resolve |DataDirectory| I found that by updating this path to the full name my connection problems went away.
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-MvcApplication3-20121215104323;Integrated Security=SSPI;AttachDBFilename=C:\mydatabase\file\path\example\aspnet-MvcApplication-20121215104323.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>
I then found this post here, it indicates that the AppDomain has not had it's data directory set correctly at this point.
So once the config set up and the connection string altered with a proper file path and a user name "test" and a password "testing" this request through fiddler got a 200:
GET http://localhost/api/goober/1
User-Agent: Fiddler
Host: localhost
Authorization: Basic dGVzdDp0ZXN0aW5n
As an aside
I found that to get the forms authorisation token to also allow access to the api controllers I had to add this. Otherwise the Thinkteckture code sets the principle back to anonymous:
Add this
authConfig.InheritHostClientIdentity = true;
To counteract this (line 52):
if (_authN.Configuration.InheritHostClientIdentity == false)
{
//Tracing.Information(Area.HttpAuthentication, "Setting anonymous principal");
SetPrincipal(Principal.Anonymous);
}
General information
Operating System: Windows Server 2003 R2 Service pack 2
Webserver: IIS 6
NTAuthenticationProviders: NTLM only
Webapplication: Classic ASP
Browsers used: IE7, IE8, IE9
There’s a Classic ASP web application called knowledgebase, within an IIS website called eblcplaza like so: eblcplaza/knowledgebase/.
eblcplaza has anonymous access AND Integrated Windows Authentication enabled.
knowledgebase has anonymous access disabled and Integrated Windows Authentication enabled
knowledgebase is a Classic ASP application has its own Application pool which runs under the predefined Application pool identity “Network service”
When I’m logged in with my NT account I can access any page I want just fine. The problem is with the WinHttp.WinHttpRequest.5.1 component. It’s used in some parts of knowledgebase to do a server side request to retrieve content from some .asp scripts which reside within the web application.
The problem started when Anonymous access was turned off on knowledgebase . Note, turning it back on is not an option.
Example of a request using WinHttpRequest:
set WinHTTPRequest = Server.CreateObject("WinHttp.WinHttpRequest.5.1")
WinHTTPRequest.SetTimeouts 20000, 20000, 20000, 20000
call WinHTTPRequest.Open("POST", someUrlToAspScript, false)
WinHTTPRequest.SetAutoLogonPolicy 0
WinHTTPRequest.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
WinHTTPRequest.Send strQueryString
Response.Write(WinHTTPRequest.ResponseText)
With SetAutoLoginPolicy set to 0, I get the following error message on the pages where WinHttpRequest is used:
You do not have permission to view this directory or page using the credentials that you supplied.
HTTP Error 401.1 - Unauthorized: Access is denied due to invalid credentials.
Internet Information Services (IIS)
With SetAutoLoginPolicy set to 2 (Do not automatically send user credentials according to MSDN), I get the following error message on the pages where WinHttpRequest is used:
You do not have permission to view this directory or page using the credentials that you supplied because your Web browser is sending a WWW-Authenticate header field that the Web server is not configured to accept.
HTTP Error 401.2 - Unauthorized: Access is denied due to server configuration.
I know for a fact that my NT user account has the proper rights to access those .asp scripts and so does the Network Service account.
I tried figuring out what could be the problem for several days know, tried setting the NTAuthenticationProviders to only NTLM and both Negotiate and NTLM amongst other things, but nothing worked so far.
Please help me out, It’s starting to drive me crazy.
Regards,
Bart
I guess the pages in knowledgebase are accessed with the anonymous account where you start from at eblcplaza. Try to enable NTLM only on the page in eblcplaza where you use the request, you can do that on that file only. Like that your credentials get passed to knowledgebase. On both pages log the Session("username") variable.
First of all let's clear up what it is you asking the server to do. It will have demanded your credentials from the client with which it is now impersonating you for security purposes. The WinHTTP request it is making to a service (WinHTTP doesn't know that its the exact same application) that now demands credentials. What you want this impersonating thread to do is use your creds to authenticate against an "external" service.
I suspect that what is happening here is that the server is not cleared to re-use your credentials in this way. If I recall correctly (which may not be that certain) a server needs to be granted the right to delegate in order to do that. It may also be possible to allow this if Kerberos is used instead of NTLM to perform windows integrated security.
However all that may be academic. You should understand that an app making a http request to itself has the potential to hang when under load in a way that would require a recycle to release.
Consider this alternative. Given that ServicePage.asp is a page used both directly by the browser and by an internal ClientPage.asp do the following.
Rip out the service code from ServicePage.asp and place in a VBScript class in a new ServiceInclude.asp. Now add the this ServiceInclude.asp as an include file in ServicePage.asp where ServicePage.asp only contains the plumbing necessary to instance the class and use it to generate its output.
Modify ClientPage.asp so that instead of attempting WinHttp to ServicePage.asp it simply includes the ServiceInclude.asp, instances the contained class and uses the class to provide the service required.
i have some code that tries impersonate the callers windows security settings and then connect to another WCF service on a different machine
WindowsIdentity callerWindowsIdentity = ServiceSecurityContext.Current.WindowsIdentity;
using (callerWindowsIdentity.Impersonate())
{
NetTcpBinding binding = new NetTcpBinding();
binding.Security.Mode = SecurityMode.Message;
binding.Security.Message.ClientCredentialType = MessageCredentialType.Windows;
EndpointAddress endpoint = new EndpointAddress(new Uri("net.tcp://serverName:9990/TestService1"));
ChannelFactory<WCFTest.ConsoleHost.IService1> channel = new ChannelFactory<WCFTest.ConsoleHost.IService1>(binding, endpoint);
WCFTest.ConsoleHost.IService1 service = channel.CreateChannel();
return service.PrintMessage(msg);
}
But I get the error:
"the caller was not authenticated by the service"
System.ServiceModel .... The request for security token could not be satisfied because authentication failed ...
The credentials I am trying to impersonate are valide windows credential for the box the service is on.
Any ideas why?
In order to support your scenario, you need to have an understanding of how Protocol Transition and Constrained Delegation work. You will need to configure both Active Directory and your WCF service endpoint(s) to support this. Note the use of the Service Principal Name (SPN). Take a look at the following link and see if they help you. The article has a sample to demonstrate the complete end-to-end configuration required to make this work.
How To: Impersonate the Original Caller in WCF Calling from a Web Application
Agree with marc_s this is the double-hop problem.
You need to get the windows authentication all the way through, therefore:
The request must be made in the context of a windows users
IIS must be configured to use windows authentication
Web.config must be set up for windows authentication with impersonate = true
The user that your application pool is running as, must be allowed to impersonate a user. This is the usual place where the double-hop problem occurs.
There is a right called "Impersonate a client after authentication"
http://blogs.technet.com/askperf/archive/2007/10/16/wmi-troubleshooting-impersonation-rights.aspx
Impersonation from you service to the next is a tricky issue, known as "double-hop" issue.
I don't have a final answer for that (I typically avoid it by using an explicit service account for the service that needs to call another service).
BUT: you should definitely check out the WCF Security Guidance on CodePlex and search for "Impersonation" - there are quite a few articles there that explain all the ins and outs of impersonating an original caller and why it's tricky.
Marc
If you are sure you have the credentials right on both hops, the next thing that could be causing the issue is the lack of the EndpointDnsIdentity being set on the endpoint.
DnsEndpointIdentity identity = new DnsEndpointIdentity("localhost"); // localhost is default. Change if your service uses a different value in the service's config.
Uri uri = new Uri("net.tcp://serverName:9990/TestService1");
endpoint = new EndpointAddress(uri, identity, new AddressHeaderCollection());
I've got an ASP .Net application running on IIS7. I'm using the current url that the site is running under to set some static properties on a class in my application. To do this, I'm getting the domain name using this (insde the class's static constructor):
var host = HttpContext.Current.Request.Url.Host;
And it works fine on my dev machine (windows XP / Cassini). However, when I deploy to IIS7, I get an exception: "Request is not available in this context".
I'm guessing this is because I'm using this code in the static constructor of an object, which is getting executed in IIS before any requests come in; and Cassini doesn't trigger the static constructor until a request happens. Now, I didn't originally like the idea of pulling the domain name from the Request for this very reason, but it was the only place I found it =)
So, does anyone know of another place that I can get the host domain name? I'm assuming that ASP .Net has got to be aware of it at some level independent of HttpRequests, I just don't know how to access it.
The reason that the domain is in the request is...that's what's being asked for. For example these are a few stackexchange sites from http://www.stackexchangesites.com/:
http://community.ecoanswers.com
http://www.appqanda.com
http://www.irosetta.com/
If you ping them, you'll see they all point to the same IP/Web Server and be served by the same app (or multiple apps in this case, but the example holds if it was one big one)...but the application doesn't know which one until a host header comes in with the request asking the server for that site. Each request may be to a different domain...so the application doesn't know it.
If however it doesn't change, you could store it as an appSetting in the web.config.
Use global.asax or write a HttpModule and subscribe to start request events. You will have the request passed into your event handler.
Use this instead:
HttpRuntime.AppDomainAppVirtualPath
Or if you want the physical path:
HttpRuntime.AppDomainAppPath
For further reading:
http://weblogs.asp.net/reganschroder/archive/2008/07/25/iis7-integrated-mode-request-is-not-available-in-this-context-exception-in-application-start.aspx