IdentityServer4 works only with HTTPS - identityserver4

I'm migrating from Identity Server 3 to 4.
I'm having trouble running Identity Server 4 without HTTPS in local development environment.
With HTTPS - everything works fine. Without it the user is not authenticated and just redirected
to the login page. The cookie is not set.
I know Identity Server 3 used to have the RequireSsl option that is now gone.
I've searched the docs for hours but came with nothing.
I'm on IdentityServer4 4.1.1 and AspNet Core 3.1
My Startup.cs looks like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentityServer()
.AddInMemoryClients(Clients.Get())
.AddInMemoryIdentityResources(Configs.Resources.GetIdentityResources())
.AddInMemoryApiResources(Configs.Resources.GetApiResources())
.AddInMemoryApiScopes(Configs.Resources.GetApiScopes())
.AddTestUsers(Users.Get())
..AddDeveloperSigningCredential();
services.AddControllersWithViews();
services.AddMvc(options => options.EnableEndpointRouting = false);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseIdentityServer();
app.UseAuthorization();
app.UseEndpoints(endpoints => endpoints.MapControllers());
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
What am I missing?

I guess, you try it in Chrome. When you open dev console (F12) most likely you find the warnings that SameSite=None cookie must be secure.
If my above guess is right, there could two possible causes: you use customized CookieAuthenticationOptions where you explicitly set options.Cookie.SameSite = SameSiteMode.None (looking at your startup you don't), or the default one is not good for your configuration.
You can tweak it like below:
services.AddIdentityServer(options =>
{
options.Authentication.CookieSameSiteMode = SameSiteMode.Lax;
})
Will work on localhost, will block silent refresh for clients hosted beyond your IdSrv's root domain. So you have to choose whether you prefer Lax for production, or just for home playground (but in general None it not recommended anywhere).

Related

How to troubleshoot local SQL connections in a Blazor App from Visual Studio 2019

Learning Visual Studio 2019, C#, and SQL on my local PC. Having trouble connecting to the local SQL databases and making sure that my app opens up in my local browser.
Now an app that has previously worked fine gives me a 404 error. I cannot figure out why this is happening. In general I would like to have a tool or some other checklists to see why the server is throwing the error.
Would love to have some advice on best ways to do this.
=================
I should have added code and better explanation initially.
I am rebuilding an app. Started with a fresh Blazor server app project, and started moving things over from the old app. I was eventually able to compile the new app and then launched it and originally got an SQL error.
Now I can get the app to launch a browser window (tried both Chrome and Edge) but nothing displays at all, it just looks like it is loading. There is nothing I can see in the console or in output. No errors. When I debug everything seems fine, the code never hangs on any line. Nothing ever errors out.
I can rebuild again but I want to figure out how to troubleshoot issues like this.
Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Wire_Desk.Data;
using Syncfusion.Blazor;
namespace Wire_Desk
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton<WeatherForecastService>();
services.AddSyncfusionBlazor();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// 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();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}
}
Program.cs
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace Wire_Desk
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
I don't know what more code I should include. When I debug once I get through the program file and step into, there are no more code to step through, although this was also true with a small sample app.
I am stumped.

ASP.NET Core: SPA bundle is requested over http not https

I have this configuration for SPA in .NET Core web server (Startup.cs)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
// ...
app.UseHttpsRedirection();
// ...
}
I have enabled the HTTPS configuration for the debugging.
If I remove the app.UseHttpsRedirection(); and disabled the https debugging, it works. But if I enable the `HTTPS this error shows up when loading the SPA bundle:
GET https://localhost:44355/static/js/0.chunk.js net::ERR_HTTP2_PROTOCOL_ERROR 200
It was fine before, I do not know what the cause of this. I suppose the application is requesting the bundle over HTTP and not HTTPS.
I tried to uninstall and reinstall the IIS Express, but the problem still persists. I do not know what the cause of this, please help.

Any Suggestions for getting ASP.NET Core + React Running on Elastic Beanstalk

I'm trying to get an ASP.NET Core with ReactJS application deployed to Amazon's Elastic Beanstalk. I've been using this tutorial to help me get started. I can deploy the tutorial (using the dotnet new web template) project just fine. However, when I publish a ASP.NET Core + React project (using dotnet new react template), I get the following exception when trying to access the application:
InvalidOperationException: The SPA default page middleware could not return the default page '/index.html' because it was not found, and no other middleware handled the request.
Your application is running in Production mode, so make sure it has been published, or that you have built your SPA manually. Alternatively you may wish to switch to the Development environment.
This only occurs when I try to access ClientApp/ React components. When I access an API endpoint, there is no problem.
Additionally, this does not occur when running locally. Running locally works fine.
To reproduce this error, I've executed the following:
dotnet new react -o test-react/
dotnet publish test-react/ -o site/
cd site/
zip ../deploy.zip *
Finally, I manually import deploy.zip into AWS Elastic Beanstalk.
This is the Startup.cs file for that project.
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/build";
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// 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();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
}
}
For reference, I am targeting .NET Core 3.1. Any ideas on how to solve this problem? I believe I've tried everything suggested on this GitHub issue. Any help would be greatly appreciated.
This question seems similar but is obviously for Angular and not React:
deploy Angular/Asp.Net Core 2.1 app to AWS: 500 error
It turns out that my deploy.zip package wasn't being created recursively so files in subdirectories were missing. Instead of doing,
zip ../deploy.zip *
I did,
zip -r ../deploy.zip *
which worked as intended. Silly me.

How to enable Cors in ASP.NET Web Api

I'm learning Angular 2. This is my service that's supposed to pull data from an ASP.NET Web api application.
#Injectable()
export class ExpenseService {
private _expUrl = "http://localhost:65400/api/expenses";
constructor(private _http: Http){}
getExpenses(): Observable<IExpense[]> {
return this._http.get(this._expUrl)
.map((response: Response) => <IExpense[]>response.json())
.do(data => console.log('ALL: ' + JSON.stringify(data)))
.catch(this.handleError)
}
//more here...
}
The above code is working fine in Microsoft Edge. However, in Chrome and FireFox, I'm getting the following error:
XMLHttpRequest cannot load http://localhost:65400/api/expenses.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:3000' is therefore not allowed
I've enabled CORS in my web api as suggested by many posts.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
//...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
//...
app.UseCors(builder =>
builder.WithOrigins("http://localhost:3000/"));
}
That didn't change the outcome. I'm still getting the same error in Chrome and FireFox while Edge is working just fine.
Thanks for helping
CORS is something that are enforced by the client, supported by the server.
CORS is there to help you as a user. It restrict the possibility for a client, like javascript on host google.com, to call a service on mydomain.com. This is a cross-domain call, which Chrome and FireFox does not allow. (Would assume that Edge also supported this). If you are hosting a service and client on some host and port, CORS is not used.
A service must define which host from a cross-domain is allowed. This can either be from all or from a specific host.
To allow access from all host do the following:
Configuration
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
}
Controller
[EnableCors("AllowSpecificOrigin")]
public class TestController : ApiController
If your service is a public service, be aware of the consequences.
You can read more here: https://learn.microsoft.com/en-us/aspnet/core/security/cors

Angular $http.get call to web api

I have two web applications running. App1 is an angular SPA and App2 is an MVC web api written in c#. I am executing both applications from Visual Studio 2015, running debug in IIS Express.
My angular code (App1) is trying to call an api controller in App2 using the following (debug) code:
$http.get('https://localhost:12345/api/values').then(function (response) {
alert(response.data);
}, function (err) {
alert(err);
}).catch(function (e) {
console.log("error", e);
throw e;
}) .finally(function () {
console.log("This finally block");
});
I always hit the "alert(err);" line - it never successfully executes and err has nothing useful in it to indicate what the problem could be.
In Postman (addin for Chrome), I can confirm the call I'm trying to make to App2 works fine. What am I doing wrong? Could this be an issue with CORS?
Thanks in advance!
You either experiencing CORS/SAME ORIGIN POLICY issue that some information about it in angular js can be found here: How to enable CORS in AngularJs.
this is how you handle it in server site in your case: http://docs.asp.net/projects/mvc/en/latest/security/cors-policy.html#cors-policy
or you better open the developer tools in console tab and bring us some more information about what happened in your code.
Ok the problem I had was in the web api (MVC 6 - ASP.net 5) in that I had to allow the requests from my angular web site. The startup.cs file had the following added:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddCors();
StartupInitialize(services);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseIISPlatformHandler();
app.UseStaticFiles();
app.UseCors(builder => builder.WithOrigins("http://localhost:12345/"));
app.UseMvc();
antiForgery = (IAntiforgery)app.ApplicationServices.GetService(typeof(IAntiforgery));
}

Resources