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

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.

Related

ASP.NET Core - Serve both API and SPA React from different port

It is possible to serve both an API and a Single Page Application (SPA) React/Redux from different ports in ASP.NET Core. I found some post here ASP.NET Core - Serve both API and SPA from the same port that asks for serving from the same port, I would like to serve them on different ports because I would like to implement Azure B2C Authentication(so my spa can safely communicate with web api). I generated a boiler plate that includes react spa with .net web api but it is in one solution by default. Not sure if I should generate .net core web api and react app in a separate projects but when I run the application it serves both spa and webapi on the port that is configured in launchSettings.json for web api. In Startup.cs i have
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/build";
});
app.UseSpaStaticFiles();
app.UseSpa(spa =>
{
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
I tried to add "homepage": "https://localhost:3000",
to package.json of react.app I also tried to add spa.Options.DefaultPage = "https://localhost:3000"
I also tried spa.UseProxyToSpaDevelopmentServer("https://localhost:3000");
But none of that works. Is there something like a Nuget package or maybe some extra trick with configuration or should I give up on the boiler plate and create 2 independent projects(1 create-react-app and then generate a default web api project). Thanks
Different from the template for ASP.NET Core with React.js, React.js and Redux is using .net core3.1 so it doesn't have .env file. In that file you can set the running port of your project.
According to the MS document, I think React.js and Redux project is using middleware to compile the functions code first then put them to the static web page and display it. The following code do this part of job:
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
When you start the project in VS, you can see the port number in the browser, which is the running port of the whole project. So you think the API and SPA are running on the same port. From my perspective, API is using middleware to invoke SPA.
You can use command line code npm start in the ClientApp File to run the SPA as an independent project, it will run it on the default port 3000. Here is the screenshot of my test:

Deploy ASP.NET core 7 Web API with React front end

I wrote an ASP.NET Core 7 web API backend and standalone Javascript React front end. I can deploy the backend to IIS successfully and it works fine through postman. However when I try to deploy the react front end using the method described in this tutorial https://learn.microsoft.com/en-us/visualstudio/javascript/tutorial-asp-net-core-with-react?view=vs-2022
my visual studio just freaks out and crashes. I am trying to figure out how to deploy the front end manually without using the visual studio publish feature.
This is my project setup:
[1]: https://i.stack.imgur.com/cApdk.png
And this is the IIS side where the WEB API backend is currently published:
[2]: https://i.stack.imgur.com/GtJ9O.png
Do I need to create a separate site for the frontend or can I deploy it to the same site as the backend? How can I build the frontend and manually deploy to the IIS?
For the site to work properly, you should build the frontend part in production mode, i.e. use the command npm run build instead of npm run start.
And then move the resulting files to the wwwroot folder inside your NET7 project.
Additionally, you should add static files using the AddStaticFiles method.
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-7.0
Also remember to set the ports correctly, because you can have different ones in the development and production environment, you will do it in launchsetting.json
You just need to change your Program.cs file like below, the you could publish webapi project directly. Every step mentioned in the official document must be completed, and finally add the following code.
namespace WebApplication1
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
else
{
app.UseDefaultFiles();
//app.UseStaticFiles();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
//app.MapControllers();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
// Add this line
endpoints.MapFallbackToFile("/index.html");
});
app.Run();
}
}
}
Test Result

CORS policy is allowed in app.py but still not working

The front-end app is built on ReactJs and development server is running on http://localhost:3000. The back-end API is built with Flask 2.0.2 and is running on http://localhost:5000
In app.py file, the CORS has been allowed as mentioned in the documentation like:
CORS(app, resources={r"*": {"origins": "*"}})
When I try to submit the login form I still get the following error:
if you Enables CORS on your backend api , it should work.
I don't think this is an issue with your react frontend application.
cors is a security measure put in by browsers.
You could bypass the Cross-Origin-Policy with chrome extension but it's not advisable -
Try this on your backend API:
Ensure you have flask cors installed
create a configuration dictionary like this
api_v1_cors_config = {
"origins": ["http://localhost:5000"]
}
You can then set a global cors for your app like this
CORS(app, resources={"/api/v1/*": api_v1_cors_config})
// this would allow all methods, origins

IdentityServer4 works only with HTTPS

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).

Getting Failed to load resource: the server responded with a status of 404 (Not Found) when pushing Angular app to cloud foundry

I am able to access the client server in Angular 5 from localhost:4200 with Cross-Origin concept but when I am deploying the app using ng build to Pivotal Cloud Foundry, getting error Failed to load resource: the server responded with a status of 404 (Not Found).
Not able to figure out the exact issue.
I am using package.config.json as -
{
"/api": {
"target": "https://benifit.cfapps.io/api",
"pathRewrite": {
"^/api": ""
},
"changeOrigin": true
}
}
Also, I am using cf push -b staticfile_buildpack portal-app for pushing my app to PCF. Please suggest where and what I am missing
You are referring to the proxy config file from angular-cli dev server. This file is only used for local development, to avoid cross-origin requests. You cannot use this proxy, after the app is deployed.
So in your case the Angular app will directly query your backend underneath the following path /api. So you have to ensure the api is available at the same host (in cloud foundry). When the api is only available under benifit.cfapps.io/api, you have to change the base path for your HTTP queries in the app and also take care to enable cross-origin requests on the api side.

Resources