How to use Windows authentication on ASP.NET Core subpath only? - asp.net-core

I am trying to configure Windows authentication on a subroute only in my ASP.NET Core MVC app.
My problem is that when I add
services.AddAuthentication().AddNegotiate()
I get an error
The Negotiate Authentication handler cannot be used on a server that directly supports Windows Authentication.
which lead me to adding web.config as the docs explained:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<security>
<authentication>
<anonymousAuthentication enabled="false" />
<windowsAuthentication enabled="true" />
</authentication>
</security>
</system.webServer>
</location>
</configuration>
and the error goes away. However, now the Windows authentication is popping up on each request.
I tried changing the location path to .testendpoint but that then throws the original error at the base path.
So is it possible and how do I make such only /testendpoint will ask for Windows authentication and the remaining of the application will work with whatever other auth I configured in my ASP.NET Core app?

Another way using endpoint routing:
We have an application schema for the application that will be used all over the app called eavfw.
Using a custom endpoint here called login/ntlm with metadata new AuthorizeAttribute(NegotiateDefaults.AuthenticationScheme) its only allowed to be visited by a valid windows authenticated user.
Here we then create the user in our DB using its AD username.
endpoints.MapGet("/.auth/login/ntlm", async httpcontext =>
{
var loggger = httpcontext.RequestServices.GetRequiredService<ILogger<Startup>>();
var windowsAuth = await httpcontext.AuthenticateAsync(NegotiateDefaults.AuthenticationScheme);
if (!windowsAuth.Succeeded)
{
loggger.LogWarning("Not authenticated: Challening");
}
if (windowsAuth.Succeeded)
{
loggger.LogWarning("Authenticated");
var name = string.Join("\\", windowsAuth.Principal.Claims.FirstOrDefault(c => c.Type.EndsWith("name")).Value.Split("\\").Skip(1));
var context = httpcontext.RequestServices.GetRequiredService<DynamicContext>();
var users = context.Set<SystemUser>();
var user = await context.Set<SystemUser>().Where(c => c.PrincipalName == name).FirstOrDefaultAsync();
if (user == null)
{
user = new SystemUser
{
PrincipalName = name,
Name = name,
// Email = email,
};
await users.AddAsync(user);
await context.SaveChangesAsync();
}
var principal = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] {
new Claim(Claims.Subject,user.Id.ToString())
}, "ntlm"))
{
};
await httpcontext.SignInAsync("ntlm",
principal, new AuthenticationProperties(
new Dictionary<string, string>
{
["schema"] = "ntlm"
}));
httpcontext.Response.Redirect("/account/login/callback");
}
}).WithMetadata(new AuthorizeAttribute(NegotiateDefaults.AuthenticationScheme));
using a auxility authentication cookie, we can now make it such that specific areas of our app that requires windows authentication, it can simply rely on Authorize("ntlm") as it automatically forward the authenticate call to check if already signin, and it as part of the signin call in the endpoint above actually sign in eavfw.external before it redirects to the general account callback page that will do some final validation before signing in eavfw from the eavfw.external cookie
services.AddAuthentication().AddCookie("ntlm", o => {
o.LoginPath = "/.auth/login/ntlm";
o.ForwardSignIn = "eavfw.external";
o.ForwardAuthenticate = "eavfw";
});
So there are a few ways to extend and use the authentication system in auth core depending on how MVC framework heavy your application is.

Just thought I'd share this tidbit of information:
First off, just because you installed Windows Authentication with Server Manager, doesn't mean it's enabled in IIS. It's NOT enabled, by default.
You have to open IIS Manager, click on your server (NOT the website - the name of the server machine hosting IIS). Then click on Authentication - you will see "Windows Authentication" is disabled. Enable it. Now it will work.
Check this is correctly set first, before making other config changes. The default project for dotNet5 and dotNet6 will work w/o any modifications if IIS is correctly configured for Windows Authentication.

In order to have a certain page/action method secured via Windows authentation, specify the corresponding authentication scheme in the action methods Authorize attribute.
[Authorize(AuthenticationSchemes = IISServerDefaults.AuthenticationScheme)]
public IActionResult UsingWindowsAuthentication()
Make sure to have Windows authentication enabled on your website.
In order to use other authentication schemes, e.g. "Individual Accounts", anonymous authentication is also enabled.
The controllers and/or action methods that must not use Windows Authentication have the default scheme specified.
For example, for an ASP.NET Core MVC project that uses the out of the box "Individual Accounts" authentication type as default authentication method, that is Identity.Application.
[Authorize(AuthenticationSchemes = "Identity.Application")]
public IActionResult Index()
See the documentation about how to set up and configure multiple authentication schemes.

Related

How to handle session time out using azure identity authentication - .net core app 3.1

How can I sign out a user form ASP.NET Core MVC 3.1.27 application after 5 minutes of inactivity or so. I have created the application using Azure Identity platform (Azure AD) as authentication type.
I tried implementing it using one of microsoft documentation but it is not working for me. please find the documentation link. https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-6.0
I have added session Middleware in Configure method of startup.cs class
I have added session Dependency Injection service in ConfigureServices method of startup.cs class
Thanks in advance for your help.
• You will have to use the ‘authenticationElement’ within your ASP.Net application to identify the users who view your application by using either the ‘configuration Element’, ‘system.web Element’ or ‘authentication Element’ in the application schema along with the attributes and child elements such as ‘mode, forms, passport’ as shown below which needs to be edited in the ‘web.config’ file of the application: -
<authentication mode="Windows">
<forms
name=".ASPXAUTH"
loginUrl="login.aspx"
defaultUrl="default.aspx"
protection="All"
timeout="30"
path="/"
requireSSL="false"
slidingExpiration="true"
cookieless="UseDeviceProfile" domain=""
enableCrossAppRedirects="false">
<credentials passwordFormat="SHA1" />
</forms>
<passport redirectUrl="internal" />
</authentication>
• Once, the above authentication element schema is implemented, this will ensure that the user gets logged out after the specified period of inactivity. Also, along with the above, you can also configure the ‘app's cookie’ in ‘Program.cs’ by calling the ‘ConfigureApplicationCookie’ class as below by calling the ‘AddIdentity’ or ‘AddDefaultIdentity’ parameters as shown below: -
builder.Services.ConfigureApplicationCookie(options =>
{
options.AccessDeniedPath = "/Identity/Account/AccessDenied";
options.Cookie.Name = "YourAppCookieName";
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
options.LoginPath = "/Identity/Account/Login";
// ReturnUrlParameter requires
//using Microsoft.AspNetCore.Authentication.Cookies;
options.ReturnUrlParameter =
CookieAuthenticationDefaults.ReturnUrlParameter;
options.SlidingExpiration = true;
});
Wherein the ‘ExpireTimeSpan’ is duration after which the cookie will expire and ‘SlidingExpiration’ will tell the parent handler, i.e., ‘ConfigureApplicationCookie’ and ‘authentication Element’ in the application schema to issue a new cookie with the configured expiration time. Thus, by implementing the above, you can configure the inactivity timeout in your ASP.Net application.
For more information, kindly refer to the below links for clarification: -
https://learn.microsoft.com/en-us/previous-versions/dotnet/netframework-4.0/532aee0e(v=vs.100)?redirectedfrom=MSDN
https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity-configuration?view=aspnetcore-6.0&viewFallbackFrom=aspnetcore-2.1

ASP.NET disable authorization depending on host

I have an ASP.NET Core application and I have decorated my constroller/actions with Authorize attribute. In Startup.cs, I have defined the authentication like this:
services.AddAuthentication(Microsoft.AspNetCore.Server.IISIntegration.IISDefaults.AuthenticationScheme);
When I run my application in IIS or IIS Express, authorization works. However, I want to disable authorization when running in hosts that don't support Windows authentication like Console application.
I was thinking of doing this:
services.AddMvc(options =>
{
if (!isWindowsAuthenticationSupported)
options.Filters.Add(new AllowAnonymousFilter());
});
If this is the right approach, how would I set the isWindowsAuthenticationSupported variable?
Here is the code to determine if Windows authentication is supported:
string iisHttpAuth = Environment.GetEnvironmentVariable("ASPNETCORE_IIS_HTTPAUTH");
bool isWindowsAuthenticationSupported = false;
if (iisHttpAuth != null && iisHttpAuth.ToLowerInvariant().StartsWith("windows"))
isWindowsAuthenticationSupported = true;

Aspnet Core with Adfs 2016 OpenId can't sign out

I setup an MVC project with Aspnet Core targeting Net461. Authentication is configured to use Adfs from a Windows Server 2016 system. I managed to get sign in working, however, when I click sign out I am given a page cannot be displayed error. Browsing back to the home url shows that the user is still logged in also. Any suggestions?
You might find this sample useful (even though it is for Azure ADFS, it works for local installs as well): https://github.com/Azure-Samples/active-directory-dotnet-webapp-openidconnect-aspnetcore
The logout action method like the following work well in my case:
[HttpGet]
public IActionResult SignOut()
{
var callbackUrl = Url.Action(nameof(SignedOut), "Account", values: null, protocol: Request.Scheme);
return SignOut(
new AuthenticationProperties { RedirectUri = callbackUrl },
CookieAuthenticationDefaults.AuthenticationScheme,
OpenIdConnectDefaults.AuthenticationScheme);
}
This will redirect you to the /Account/SignedOut after it completes and you need to register your /signout-callback-oidc endpoint for your client as well. This endpoint is used (by default) by the OIDC ASP.NET Core middleware.

MVC5: User.Identity.IsAuthenticated always returns true

Our company has SSO site where all our applications gets redirected if the user is not authenticated. The SSO site authenticates the user using Forms authentication. and its been working for all the applications.(ASP.NET applications)
Now we have new MVC5 application created using VS 2013. I am trying to use Forms Authentication. If the user is not authenticated I want to redirect the user to login url ( SSO site). Below is my code. But when I debug, the user is always Authenticated.
IsAutheticated property is true, AuthenticationType is "Negotiate", and Identity is "Windows" ( even though in config file its "Forms")
(Note I am debugging in VS with IIS express if that make difference. Also it's MVC 5 application, is it because of OWIN. How do I know?)
<system.web>
<compilation debug="true" targetFramework="4.5" />
<authentication mode="Forms" >
<forms loginUrl="/Account/Login"></forms>
</authentication>
<authorization>
<deny users="?" />
</authorization>
public class AccountController : Controller
{
public ActionResult Login()
{
string loginUrl = AppSettings.Authentication.LoginUrl;
string failOverUrl = AppSettings.Authentication.FailoverLoginUrl;
string securityGroup = AppSettings.Authentication.SecurityGroup;
if (!User.Identity.IsAuthenticated) // IsAutheticated is always true, why?
{
var returnUrl = "someresturnurl";
MyAuthenticator.Authenticate(loginUrl, failOverUrl, returnUrl, securityGroup);
}
else
{
// Redirect the user if they are already authenticated.
return RedirectToAction("Index", "Home");
}
}
}
In ASP.NET MVC5 authentication mechanism has changed significantly.
Possibly all you authentication configuration comes from OWIN Startup class.
Here is a link where you can find how this configuration may look like
HttpListener listener = (HttpListener)app.Properties["System.Net.HttpListener"];
listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication;
This is a good topic about ASP.NET identity basics
I hope this will help.

Sharing ASP.NET simplemembership authentication across web roles and client applications

I've been trying to figure this out for a while now, reading a lot of blogs, MSDN documentation, sample code and other stackoverflow questions and have yet to get this to work.
Here is my scenario:
I am using Windows Azure to host two web roles. One is my MVC4 web API, the other is my MVC4 web app which uses the web API. I also have a number of client applications using .NET that will access the web API.
So my main components are:
Web API
Web App
.NET Client
I want to use forms authentication that is 'hosted' in the Web App. I am using the built in simplemembership authentication mechanism and it works great. I can create and log in to accounts in the Web App.
Now I also want to use these same accounts to authenticate the Web API, both from the Web App and any .NET client apps.
I've read numerous ways to do this, the simplest appearing to be using Basic Authentication on the Web API. Currently I am working with this code as it appears to solve my exact problem: Mixing Forms Authentication, Basic Authentication, and SimpleMembership
I can't get this to work. I log in successfully to my Web App (127.0.0.1:81) and when I try to call a Web API that requires authentication (127.0.0.1:8081/api/values for example) the call fails with a 401 (Unauthorized) response. In stepping through the code, WebSecurity.IsAuthenticated returns false. WebSecurity.Initialized returns true.
I've implemented this code and am trying to call my Web API from my Web App (after logging in) with the following code:
using ( var handler = new HttpClientHandler() )
{
var cookie = FormsAuthentication.GetAuthCookie( User.Identity.Name, false );
handler.CookieContainer.Add( new Cookie( cookie.Name, cookie.Value, cookie.Path, cookie.Domain ) );
using ( var client = new HttpClient() )
{
//client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
// "Basic",
// Convert.ToBase64String( System.Text.ASCIIEncoding.ASCII.GetBytes(
// string.Format( "{0}:{1}", User.Identity.Name, "123456" ) ) ) );
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Cookie",
Convert.ToBase64String( System.Text.ASCIIEncoding.ASCII.GetBytes( User.Identity.Name ) ) );
string response = await client.GetStringAsync( "http://127.0.0.1:8080/api/values" );
ViewBag.Values = response;
}
}
As you can see, I've tried both using the cookie as well as the username/password. Obviously I want to use the cookie, but at this point if anything works it will be a good step!
My ValuesController in my Web API is properly decorated:
// GET api/values
[BasicAuthorize]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
In my Global.asax.cs in my Web API, I am initializing SimpleMembership:
// initialize our SimpleMembership connection
try
{
WebSecurity.InitializeDatabaseConnection( "AzureConnection", "User", "Id", "Email", autoCreateTables: false );
}
catch ( Exception ex )
{
throw new InvalidOperationException( "The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex );
}
This succeeds and WebSecurity later says that it is initialized so I guess this part is all working properly.
My config files have matching authentication settings as required per MSDN.
Here is the API config:
<authentication mode="Forms">
<forms protection="All" path="/" domain="127.0.0.1" enableCrossAppRedirects="true" timeout="2880" />
</authentication>
<machineKey decryption="AES" decryptionKey="***" validation="SHA1" validationKey="***" />
Here is the Web App config:
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" protection="All" path="/" domain="127.0.0.1" enableCrossAppRedirects="true" timeout="2880" />
</authentication>
<machineKey decryption="AES" decryptionKey="***" validation="SHA1" validationKey="***" />
Note, I am trying this locally (hence the 127.0.0.1 domain), but referencing a database hosted on Azure.
I haven't got to trying any of this from a .NET client application since I can't even get it working between web roles. For the client app, ideally I would make a web call, passing in username/password, retrieve the cookie, and then use the cookie for further web API requests.
I'd like to get what I have working as it seems pretty simple and meets my requirements.
I have not yet tried other solutions such as Thinktecture as it has way more features than I need and it doesn't seem necessary.
What am I missing?
Well, this is embarrassing. My main problem was a simple code error. Here is the correct code. Tell me you can spot the difference from the code in my question.
using ( var handler = new HttpClientHandler() )
{
var cookie = FormsAuthentication.GetAuthCookie( User.Identity.Name, false );
handler.CookieContainer.Add( new Cookie( cookie.Name, cookie.Value, cookie.Path, cookie.Domain ) );
using ( var client = new HttpClient( handler ) )
...
}
Once that was fixed, I started getting 403 Forbidden errors. So I tracked that down and made a small change to the BasicAuthorizeAttribute class to properly support the [BasicAuthorize] attribute when no role is specified.
Here is the modified code:
private bool isAuthorized( string username )
{
// if there are no roles, we're good!
if ( this.Roles == "" )
return true;
bool authorized = false;
var roles = (SimpleRoleProvider)System.Web.Security.Roles.Provider;
authorized = roles.IsUserInRole( username, this.Roles );
return authorized;
}
With that change basic authentication by passing in the forms cookie works!
Now to get non-web client apps working and then refactor the Web App as recommended.
I hope this helps someone in the future!