how to use a business identity provider (e.g. ADFS2) - asp.net-mvc-4

I am running Win 7, IIS 7.0, VS2012
I have created asp.mvc4 web app
I have ADFS2.0 on a separate VM
Using the Identity and Access tools in VS 2012
I select use a business identity provider (e.g.ADFS2) and type the url to the STS metadata document.
https://server.local/federationmetadata/2007-06/federationmetadata.xml
edited the web config
<system.web>
...
<httpModules>
...
<remove name="FormsAuthentication" />
</httpModules>
</system.web>
and this
<system.webServer>
...
<modules>
...
<remove name="FormsAuthentication" />
</modules>
</system.webServer>
Also have checked that Windows Authentication was disabled for the project
The website redirects to a url like this http:// localhost /WebSite/login.aspx?ReturnUrl=%2fWebSite%2f which has a 'The resource cannot be found' error.
What else do I have to fiddle with to make this work?
The Microsoft doco is lightweight http://blogs.msdn.com/b/vbertocci/archive/2012/03/15/windows-identity-foundation-tools-for-visual-studio-11-part-iii-connecting-with-a-business-sts-e-g-adfs2.aspx
I already have had similar problems with the local development STS MS Identity and Access Tool MVC 4

Ok this has taken me days to work out but these were the things I did to get it running. There is much more to do.
Prerequisites:
An ADFS 2.0 service running somewhere on your domain.
IIS 7 with a self signed certificate or a certificate that you can use across your domain.
Visual Studio 2012 with the Identity and Access (version 1.0.2) Extension installed.
A MVC4 web application set to run on IIS.
Ensure that Self Signed Certificate is added to the site so you can access it via https.
You may have to tweak the firewall settings of you machines to allow access to your ADFS 2.0 service.
On the Development Workstation
In your MVC4 Project
Open up the Identity and Access Dialog by right-clicking your web project.
Choose Use a business identity provider (e.g. ADFS2)
Enter the path to the STS metadata document e.g. https://{PATH TO ADFS SERVER}/FederationMetadata/2007-06/FederationMetadata.xml
Enter the realm for your application e.g. https://{WEB APPLICATION URL}/
The trailing slash makes a difference.
Exit the dialog by accepting these changes.
Add the following code to your project
using System;
using System.IdentityModel.Services;
namespace NAMESPACE
{
public class FixedWsFederationAuthenticationModule : WSFederationAuthenticationModule
{
public override void RedirectToIdentityProvider(string uniqueId, string returnUrl, bool persist)
{
//This corrects WIF error ID3206 "A SignInResponse message may only redirect within the current web application:"
//First Check if the request url doesn't end with a "/"
if (!returnUrl.EndsWith("/"))
{
//Compare if Request Url +"/" is equal to the Realm, so only root access is corrected
//https://localhost/AppName plus "/" is equal to https://localhost/AppName/
//This is to avoid MVC urls
if (String.Compare(System.Web.HttpContext.Current.Request.Url.AbsoluteUri + "/", base.Realm, StringComparison.InvariantCultureIgnoreCase) == 0)
{
//Add the trailing slash
returnUrl += "/";
}
}
base.RedirectToIdentityProvider(uniqueId, returnUrl, persist);
}
}
}
On the ADFS 2.0 Server
If you used a self signed certificate navigate to your web application https://{WEB APPLICATION URL}/ and change the zone to trusted site.
In the address bar of the browser you should be able to right click on the certificate and install (you can only install Certificates from trusted sites) The certificate needs to be installed under Trusted Root Authorities -> Registry,
Open the ADFS Console, add Relying Party Trusts, with Federated Metadata address https://{WEB APPLICATION URL}/FederationMetadata/2007-06/FederationMetadata.xml
Add some custom rules
MVC4 needs these rules in order to make a usable ClaimsPrincipal
Add a pass-through rule on the Name property.
And these 2 custom rules
=> issue(Type = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", Value = "true");
=> issue(Type = "http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", Value = "true");

Related

MSAL doesn't pop up when project is published to Azure VM

Below is my code to popup and login through MSAL.
var app = PublicClientApplicationBuilder.Create(msal.ClientId)
.WithDefaultRedirectUri()
.WithTenantId(msal.TenantId)
.Build();
var result = await app.AcquireTokenInteractive(msal.Scopes).ExecuteAsync();
Code above works when it's running on my local machine.
And below is my settings in Azure AD. Its working when I set it to localhost:5000
But when I set the localhost to 'myWebAppUrl' which is hosted on Azure Virtual Machine. MSAL won't popup. And it will just return "The operation was cancelled". Anything I missed here?
Please check the below points.
In azure ad,the reply URL must begin with the scheme https, unless using localhost. ex:http://localhost:5000
Else you can use something like https://yourappurl and don’t forget to Grant admin consent
Under Permissions for the scopes you have in azure ad.
Please check Redirect URI restrictions
Apps that use system browsers: http://localhost
Apps that use embedded
browsers:https://login.microsoftonline.com/common/oauth2/nativeclient
For Node.js, you can use msal://redirect
Please check Add a redirect URI section and Client application configuration (MSAL) | Microsoft Docs
And check if you can use confidential client to your app
.
Some authentication libraries like MSAL.NET use a default value of
urn:ietf:wg:oauth:2.0:oob when no other redirect URI is specified,
which is not recommended. This default will be updated as a breaking
change in the next major release.
Other references
Instantiate a public client app (MSAL.NET) - Microsoft identity platform | Microsoft Docs
Initialize MSAL.NET client applications - Microsoft identity platform | Microsoft Docs

Apply Windows authentication on ASP.NET core 2.2 published site without getting chrome Sign in dialog box

Trying to implement windows authentication on my published asp.net core 2.2 application.
Hosting server is Windows server 2016 (IIS).
I would like to use the active directory logged in user account to authenticate the user on my application.
I'm getting the user details by these methods:
User.Identity.Name; //return null in local host, worked when IIS
System.Security.Principal.WindowsIdentity.GetCurrent() // local host
I keep getting in the browser, the Sign in dialog box (although I would like to get rid of it, even when entering credentials - <username> + password - it doesn't authenticated).
I would like to get rid of it
Stop getting error 401 - unauthorized
I've configured what ever I was advised - both IIS and browser, but still - keep getting it:
Browser:
Browser security - Entered the host IP address to the trusted sites
IIS:
Set Authentication => enable Windows Authentication to true.
Through web.config - set "forwardWindowsAuthToken" to "true".
Site Configuration:
In the IIS site configuration (applicationHost) - system.webserver -> Security -> Authentication -> windows authentication -> "UseKernelmode" = "true"
ApplicationPool:
.NET CLR Vesrion = "No Managed Code"
Managed Pipeline Mode = " Integrated"
event tried to change in the "advanced settings" the Identity from "ApplicationPoolIdentity" to "NetworkService"
NTFS permissions:
Set basic and defaults Permissions to the account<Server host Name>\IIS_IUSRS on the server published code directory: Read & Execute, List folder contents, Read.
Maybe the problem is here - because the IIS_IUSRS account is defined in the server and not in the domain ?
You can try this method to solve the problem:
Open iis and in Windows Authentication, Right-Click to set the Providers, set the NTLM to be FIRST.
Check that under Advanced Settings... the Extended Protection is Accept and Enable Kernel-mode authentication is checked.

Why does UWP app get 401 Unauthorized against local IIS with Windows authentication?

Problem
When running a UWP app (with the Enteprise Authentication capability) that makes an HTTP request to a local IIS website protected by Windows authentication, the app receives a 401 Unauthorized response. If the app is run on a different computer than IIS (either the app is moved to a different computer or a remote Windows authentication-protected URL is requested), the request succeeds.
IIS
I am running Windows 10 Enterprise (Anniversary Edition) joined to an AD domain.
On my local IIS instance, I've enabled Windows authentication and disabled anonymous authentication for the default website. The enabled providers are "Negotiate" and "NTLM".
I've also created a test.aspx page at the root that contains simply:
<%= User.Identity.Name %>
If I visit http://localhost/test.aspx in Edge, Chrome, or IE, I am authenticated correctly and presented with my user name.
UWP
I've created a simple UWP app (targeting build 14393) with the following capabilities:
<Capabilities>
<Capability Name="internetClient" />
<Capability Name="privateNetworkClientServer" />
<uap:Capability Name="enterpriseAuthentication" />
<uap:Capability Name="userAccountInformation" />
</Capabilities>
The app's code is simply:
public MainPage()
{
this.InitializeComponent();
var result = Nito.AsyncEx.AsyncContext.Run(async () =>
{
using (var httpClient = new System.Net.Http.HttpClient())
{
return await httpClient.GetStringAsync("http://localhost/test.aspx");
}
});
textBlock.Text = result;
}
Result
If the requesting UWP app and IIS are on the same computer, the HTTP request in the UWP app fails with 401 Unauthorized.
The network profiler shows that authentication is attempted (note that the multiple requests are part of the WWW-Authenticate challenge/response scheme):
If the requesting app and IIS are on different computers, the request succeeds.
That is, if I change the request URL so that it is my development computer's FQDN (http://localhost/test.aspx becomes http://computername.domain/test.aspx) and run the app on a second computer (in other words, the app on the second computer calls my development computer's IIS), the request succeeds. Alternatively, I can successfully run the UWP on my development computer but call a remote IIS.
A few more details
The UWP app's request results in a 200 OK if anonymous authentication is enabled on the localhost IIS.
I have "Allow local network loopback" checked in the app's Debug property page, and I've verified that the loopback is enabled with checknetisolation.
UWP can't connect to loopback or localhost.
There is a workaround if you're side loading or in an enterprise environment: https://msdn.microsoft.com/en-us/library/windows/apps/dn640582.aspx

MVC4 Windows Authentication Redirect to Account/Login

I am setting up Windows Authentication in an MVC 4 application using Visual Studio 2013 and using the IIS Express Development Server. However, I get redirected to /Account/Login (as if I were using forms authentication).
I have no reference to WebMatrix in my bin folder (or anywhere) as described here: ASP.NET MVC3 and Windows Auth on IIS keeps redirecting to /Account/Login.
I have added these entries to appSettings in the web.config as suggested by this post:
MVC5 Redirects to Login.aspx when using Windows Authentication
<add key="autoFormsAuthentication" value="false" />
<add key="enableSimpleMembership" value="false"/>
Here is what I have done so far:
Added windows authentication to system.web.
<authentication mode="Windows"/>
Added the [Authorize] attribute to my controller. I have also tried using the authorization tag in the web.config instead of the attribute on the controller (deny users="?"). The results are the same.
For the Development Server settings in my project I changed these settings:
Anonymous Authentication = Disabled
Windows Authentication = Enabled
I can find no reference to FormsAuthentication. I can't figure out why it still redirects to a non-existent login page.
When the project was created it may have been done using a template that added Startup.Auth in the App_Start folder in your project. (The default template uses Individual User Accounts if you did not change it to windows authentication as the Authentication method in the create new ASP.Net Project dialog)
Try commenting out these lines if they are present
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
Or if you have not added anything to this file you could remove it completely and the call to it
ConfigureAuth(app);
found in the startup.cs in the root of the project
Now most of the account controller is no good to use if this case so be prepared to clean that up also.
This line is important and correct in the web config
<authentication mode="Windows"/>
these lines are probably not directly related to the issue and can be removed
<add key="autoFormsAuthentication" value="false" />
<add key="enableSimpleMembership" value="false"/>
The other development settings are also correct.

adfs windows authentication

I have tried searching for this and can't find anything.
I want users to have a true SSO experience. Meaning they login to their computer and when they hit a web app that we have set up trust with in ADFS they are taken straight to that website. Right now no matter what they are taken to the ADFS forms login page. We only want the forms login page to appear if the user is not already connected to the network. Otherwise, ADFS should recoginize that the user is on the network and use the windows authentication.
What do I have to change in ADFS to make this happen?
In ADFS web.config, what order do you have for:
<localAuthenticationTypes>
<add name="Integrated" page="auth/integrated/" />
<add name="Forms" page="FormsSignIn.aspx" />
<add name="TlsClient" page="auth/sslclient/" />
<add name="Basic" page="auth/basic/" />
</localAuthenticationTypes>
Is Forms on top?
Are these users on the internet or intranet?
Do you use an ADFS proxy?
One option is to add a handler for the RedirectingToIdentityProvider event by placing the code just below this paragraph in your global.asax. This gives you a chance to jump in before the browser is redirected to ADFS and modify what the request (query string) looks like. You can do this to specify authentication types, or home realms (if you have multiple federations and want to skip HRD), and probably a lot of other stuff I don't know about.
void Application_Init()
{
FederatedAuthentication.WSFederationAuthenticationModule.RedirectingToIdentityProvider += new EventHandler<RedirectingToIdentityProviderEventArgs>(WSFederationAuthentication_RedirectingToIdentityProvider);
}
Then you would add code to your handler that might look something like this:
void WSFederationAuthentication_RedirectingToIdentityProvider(object sender, RedirectingToIdentityProviderEventArgs e)
{
WSFederationAuthenticationModule instance = FederatedAuthentication.WSFederationAuthenticationModule;
SignInRequestMessage request = instance.CreateSignInRequest(Guid.NewGuid().ToString(), instance.Realm, true);
request.AuthenticationType = "urn:federation:authentication:windows";
Response.Redirect(request.WriteQueryString());
}
When you set the request.AuthenticationType to that value, you're telling ADFS that you want to do windows (integrated) authentication. This was all that was required for me to get it to work. I didn't have to bother with switching the order of the authentication types in the web.config as nzpcmad suggested.
Also, for this to work, IIS and your web browser are working some magic outside of AD FS and your relying party, so in IE your users have to go to tools > Internet Options > Security and add the site to your Local Intranet sites. There's probably a way to push this out with group policies or something, but that's another question. Anyway, now that I think of it, this may be the only step you're missing.