I want to set up multiple webapps in my domain. I am using VS2022 solution with multiple projects and shared class libraries to keep things together.
I would prefer that if I log in into the app, and navigate to any of the others, I would also be logged in into that app automatically, and off course logging out, the same effect.
At the moment, I can log into app 1, go to app 2 and log in there, but when I return to app 1 I am logged out.
Currently in my startup I have the following
services.ConfigureApplicationCookie(options =>
{
options.Cookie.Name = "AspNet.SharedCookie";
options.Cookie.Path = "/";
options.Cookie.Domain = "localhost"; // "*.example.com";
options.Cookie.SameSite = SameSiteMode.Lax;
});
services.AddAuthentication("AspNet.SharedCookie");
Identity platform is Microsoft.Identity from sql server. I dont think there is any issue there as I am succesfully loggin in/out everywhere.
services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = false)
.AddRoles<IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();
My apps running currently localhost:1000, localhost:2000, localhost:3000 etc but this would eventually become app1.example.com, app2.example.com etc.
The AspNet.SharedCookie is available on all sites, but obviously changes based on the current app.
I even though changing the app Id but I dont think thats a good idea, besides, had no effect.
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>aspnet-DEV.app1-USE THIS SAME ID IN ALL APPS</UserSecretsId>
</PropertyGroup>
How do I get this right to keep all apps standard with there own log in identity, but switching apps should keep that login info?
Thanks for your sharing, and I solve the issue by adding the code below.
services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(#"c:\temp-keys")).SetApplicationName("testapp");
Test Result:
My Code
Related
I am using both Google and Facebook authentication mechanisms in my .NET 7.0 app and they both work fine locally. When deployed in my DEV environment I am getting exceptions when coming back from Google/Facebook. So the challenge works correctly, I am able to authenticate at their side but the callback fails, saying:
Exception: The oauth state was missing or invalid.
Unknown location
I am being redirected to https://my.website.com/signin-google with the state in a querystring parameter. This is the expected behavior as I did not configure an explicit callback path and by default it's set to signin-google and signin-facebook. But somehow it seems like the RemoteAuthenticationHandler does not think this matches the callback path so it's not handling the request? Or would the issue be in the OAuthHandler.HandleRemoteAuthenticateAsync? Maybe when unprotecting the state data? But then why would this work locally?
My setup:
services.AddAuthentication()
.AddGoogle("google", options =>
{
options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
options.ClientId = AppSettings.Instance.GoogleClientId;
options.ClientSecret = AppSettings.Instance.GoogleClientSecret;
})
.AddFacebook("facebook", options =>
{
options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
options.AppId = AppSettings.Instance.FacebookAppId;
options.AppSecret = AppSettings.Instance.FacebookAppSecret;
});
Edit: Could this possibly be linked to the fact I am using 2 servers in my DEV environment and that it uses something machine-related to unprotect the state so it does not work when I land on the other machine?
It turns out this was due to the fact I am now deploying the application on multiple distributed servers, accessed via a load balancer.
This article here helped me to understand how data protection works in ASP.NET Core.
By default key-rotation system is used and the keys are generated by the machine and persisted to %LOCALAPPDATA%\ASP.NET\DataProtection-Keys. So of course this does not work anymore when you scale up your applications.
So instead I decided to store the data protection keys in a shared database so all machines will use the same key:
Add reference to Nuget Microsoft.AspNetCore.DataProtection.EntityFrameworkCore.
Create a DbContext that inherits from IDataProtectionKeyContext
Register your DbContext
Setup your data protection to use the DbContext as:
builder.Services.AddDataProtection()
.PersistKeysToDbContext<DataProtectionKeyContext>();
I am developing an application to be hosted in the Azure App Services environment which consists of a front-end Web App, a back-end Web API and a SQL Database (using Azure SQL). The front-end Web App is a Razor Pages app. We are trying to use the Microsoft Identity Platform (via Microsoft.Identity.Web and Microsoft.Identity.Web.UI libraries) to acquire an access token for the API when needed.
It works perfectly well the first time, but once a token has been acquired and cached - if the application is restarted it fails with this error:
IDW10502: An MsalUiRequiredException was thrown due to a challenge for the user. See https://aka.ms/ms-id-web/ca_incremental-consent.
No account or login hint was passed to the AcquireTokenSilent call.
Startup configuration is (I've tried various variants of this):
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedMemoryCache();
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.Unspecified;
options.HandleSameSiteCookieCompatibility();
});
services.AddOptions();
services.AddMicrosoftIdentityWebAppAuthentication(Configuration)
.EnableTokenAcquisitionToCallDownstreamApi(new string[] { Configuration["Api:Scopes"] })
.AddInMemoryTokenCaches();
services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
}).AddMicrosoftIdentityUI();
services.AddRazorPages().AddRazorRuntimeCompilation().AddMvcOptions(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
services.AddMvc();
//Other stuff...
}
I have tried for many days trying to find either a resolution workaround for this. I can catch the
error, but there is no action we can take programmatically that seems to clear the problem (the ITokenAcquisition interface does not offer the option to force an interactive login).
I have found that it is ONLY a problem in a Razor Pages application - a controller-based MVC Web App with almost identical startup code does not exhibit the problem.
I have also found that, by creating a controller-based test MVC Web App and configuring it with the same client id, tenant id etc. as the app we're having problems with, then starting it up (within the Visual Studio development environment) as soon as the main app gets the problem, I can clear the error condition reliably every time. However this is obviously not a viable long-term solution.
I have searched for this problem on every major technical forum and seen a number of similar sorts of issues raised, but none provides a solution to this precise problem.
To replicate:
Create an ASP.NET Core 3.1 Web API.
Create an ASP.NET Core 3.1 Razor Pages Web App that calls the API.
Register both with Azure Active Directory and configure the App to request a token to access the API (as per various MS documents).
Run - if everything is set up correctly the login screen will appear and all will work correctly.
Stop the Web App, wait a couple of minutes and re-start. The error above will now appear.
I have raised a Microsoft support request for it - has anybody else come across this and found a solution for it?
I have finally got to the bottom of this, largely thanks to this: https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/issues/216#issuecomment-560150172
To summarise - for anyone else having this issue:
On the first invocation of the web app you are not signed in, and so get redirected to the Microsoft Identity Platform login, which logs you in and issues an access token.
The access token is stored in the In-Memory token cache through the callback.
All then works as expected because the token is in the cache.
When you stop, and then re-start the web app within a reasonably short time, it uses the authentication cookies to pick up the still-current login, and so it does not access the Identity Platform and you do NOT get an access token.
When you ask for a token the cache is empty - so it throws the MsalUiRequiredException.
What isn't really made clear in any of the documentation is that this is supposed to happen - and that exception is picked up by the "AuthorizeForScopes" attribute but only if you allow the exception to fall all the way through and don't try to handle it.
The other issue is that in a Razor Pages app the normal AuthorizeForScopes attribute has to go above the model class definition for every page - and if you miss one it may trigger the above problem.
The solution proposed by "jasonshave" in the linked article solves that problem by replacing the attribute with a filter - so it will apply to all pages.
Maybe I'm a bit old-school, but the idea of using an unhandled exception as part of a planned program control flow doesn't sit right with me - at the very least it should be made clear that that's the intention. Anyway - problem now solved.
I was trying to remove HTTPS to test some caching features and my authentication stopped working. I read that when using Identity authentication will stop working without HTTP, even a custom authentication cookie with an authentication scheme won't work either.
After I comment these 2 lines my app won't work anymore.
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
app.UseHttpsRedirection();
The use of HTTPS is not mandatory, the application is to be used on our intranet and I have used Identity just to manage users. What options do I have right now?
even with all this, when I try to login it redirects me back to login page, and this using a custom authentication cookie not indentity.
services.AddAuthentication().AddCookie(AuthenticationSchemes.Production, options =>
{
options.ExpireTimeSpan = TimeSpan.FromHours(8);
options.LoginPath = new PathString("/Login");
options.LogoutPath = new PathString("/Logout");
options.Cookie.HttpOnly = true;
options.AccessDeniedPath = new PathString("/AccessDenied");
options.SlidingExpiration = true;
options.Cookie.Name = "NoPaper.Production";
options.ExpireTimeSpan = TimeSpan.FromHours(8);
});
UPDATE
It seems the only solution that worked was to create a new project without https and just copy everything from the other and install nuget packages and it worked.
Please explain more detail about the Authentication not working, is there any error? Try to use F12 developer tools to check it. And please make sure you are not using the ex
As far as I know, when we create dotnet core application via Visual Studio, if we select the Individual User Accounts(using Identity), it will generally force the usage of https for best practice reasons.
In this scenario, to disable HTTPS, we could refer to the following steps:
remove the UseHttpsRedirection from the Startup.cs:
app.UseHsts();
app.UseHttpsRedirection();
Right click the project, and click the Properties, in the Debug tab, unchecked the Enable SSL option. Then, the application will be launched using HTTP requests.
If you are not using the Visual Studio, you could also removing the SSL references in the launchSettings.json file:
Besides, please make sure you are not using the external authentication services in your application. I have created new dotnet core application and use above method to disable HTTPS, and then, I could use Identity to register a new user and login.
Our authentication system is currently seeing many "Correlation failed" errors for some users trying to connect via Google Sign In. We're using Identity Server 4 / ASP.NET identity with .NET Core 2.2. Obviously, we can't reproduce.
Though we tried to understand every aspect of what we were implementing and deploying, the whole authentication flow and the many configuration possibilities of ASP.NET Identity and IS4 still hold mystery to us. We've tried to pinpoint the true cause of those "correlation failed" errors, but cannot be sure. We do have data protection in place that prevents issues with load balancing and multiple instances. We're almost certain it's not related to HTTP vs HTTPS. But foremost, it looks like this error is more frequent lately, though we don't see what change could have triggered this.
One thing we realized, and we're not sure of the impact, is that the Google authentication is configured without an explicit SignInScheme:
services.AddAuthentication()
.AddGoogle(options =>
{
var section = Configuration.GetSection("ExternalLogin:Google");
options.ClientId = section.GetValue<string>("ClientId");
options.ClientSecret = section.GetValue<string>("ClientSecret");
});
Documentation about IS4 seems to indicate we should have set this in the first place:
options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
On the other hand, articles like this one say that this scheme gets replaced by ASP.NET Identity.
Because ASP.NET Identity also changes the default authentication scheme, any instances of IdentityServerConstants.DefaultCookieAuthenticationScheme and IdentityServerConstants.ExternalCookieAuthenticationScheme, should be changed to IdentityConstants.Application and IdentityConstants.ExternalScheme respectively.
This just adds to our overall confusion, and we're not sure if it means changes to the external login callback as well.
Can we add that simple SignInScheme line to the Google options without impacting other users which still can connect with Google Sign In without any issue? Does it have a chance to fix the correlation errors we see? Otherwise, where should we look?
We have an ASP Core 2.0 App working nicely with Azure AD on the private network. However, we've been playing around with the Azure Application Gateway, investigating the possibility of allowing access to the app from outside for remote workers etc.
We have registered the app on the Gateway, and, once logged in with Azure AD, the anonymous front page is accessible via ourapp.msappproxy.net. However, when signing in (again?) in the app, the client is redirected back to intervalServer/signin-oidc which fails as it is not accessible externally.
While I doubt this is any part of the solution, I have tried overriding the redirect "CallbackPath": "/signin-oidc", to absolute path ourapp.msappproxy.net/signin-oidc but I can't seem to work out how. Changing the reply URL in Azure Portal doesn't help either (although I doubted it would, this is just for verification right?).
I can't seem to find any guidance on this on this particular scenario, so that would be welcome. Otherwise, I'm left pondering the following:
1, If I could change the redirect to ourapp.msappproxy.net/signin-oidc, would that solve the sign in issue?
2, Do I even need an additional sign in step, or should I be changing the app to accept AzureAppProxyUserSessionCookie or AzureAppProxyAccessCookie? (If that's even an option?)
Thanks to rfcdejong in the comments for putting me on track. In our case I was able use Azure AD with the Azure Application Gateway by overriding OnRedirectToIdentityProvider event and supplying the proxy url in ConfigureServices
services.AddAuthentication(...)
.AddOpenIdConnect(options =>
{
options.ClientId = Configuration["Authentication:AzureAD:ClientId"];
options.Authority = Configuration["Authentication:AzureAd:Authority"];
options.CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"];
if (IsProduction) // So that I can use the original redirect to localhost in development
{
Task RedirectToIdentityProvider(RedirectContext ctx)
{
ctx.ProtocolMessage.RedirectUri = "https://ourapp.msappproxy.net/signin-oidc";
return Task.FromResult(0);
}
options.Events = new OpenIdConnectEvents
{
OnRedirectToIdentityProvider = RedirectToIdentityProvider
};
}
})
The return URI needs to be configured to match for the app in Azure Portal.
Users also need to be assigned, but the internal app is now available anywhere without requiring direct access to the server.