Swashbuckle Swagger Try It Out behind NGINX reverse proxy - asp.net-core

I'm trying to make the swaggerUI Try it out function to work behind NGINX reverse proxy.
I'm using ASP.net Core with the package Swashbuckle Swagger
Since I have multiple API I added a subdomain to my nginx config.
When I use try it out it sends the request to
http://{server-ip-address}/api/myendpoint
instead of
http://{server-ip-address}/myapi/api/myendpoint
My goal is to add the myapi to the address of Try it out function.
I'm not sure if I should edit my NGINX config or my ASP.net core configuration.
Thanks for your help!

You can try in Startup.cs:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseSwagger(opt =>
{
opt.PreSerializeFilters.Add((swagger, httpReq) =>
{
var serverUrl = $"http://{httpReq.Host}/myapi/api/myendpoint";
swagger.Servers = new List<OpenApiServer>{new() { Url = serverUrl }};
});
});

Related

How to Redirect HTTP to HTTPs in ASP.NET Core?

I want to redirect a HTTP request to HTTPS. How can I do in .Net Core 2.0?
I tried to add the below code in the startup.cs file but this is not working. Can any one help me for this?
services.AddHttpsRedirection(options =>
{
options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
options.HttpsPort = 443;
});
Details about the code:
When I run my project first time, the Configure() and AddHttpsRedirection() gets called.
Then after I change https to http only after that it's not working means its not call any function from stratup.cs
I did this code and try to redirect to https, but page is just loading, it's not redirecting, Even worse, I am not able to call AddHttpsRedirection function.
I have a .NET Core 2.1 project and I use the following:
Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider services)
{
...
app.UseHttpsRedirection();
...
}

AspNetCore Swagger/Swashbuckle and Virtual Directories

I'm struggling with getting the configuration for Swagger/Swashbuckle correct in an Asp.Net core 2.0 web api. I've followed the examples, which all work brilliantly when working at the root folder/localhost. As many others have pointed out, I too am seeing different behavior when working in a virtual folder on the server. I've examined this question - IIS site within virtual directory Swagger UI end point which is similar, but the solution provided there is not working.
My startup.cs file has the following block for configuring services:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddSwaggerGen(c =>
{
c.DescribeAllEnumsAsStrings();
c.IncludeXmlComments(string.Format(#"{0}\EmployeeService.xml", System.AppDomain.CurrentDomain.BaseDirectory));
c.SwaggerDoc("v1", new Info
{
Version = "v1",
Title = "Employee Service"
});
});
...
}
And my Configure method looks like this:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Employee Service API");
});
app.UseMvc();
}
I've tried this with and without adding the RoutePrefix to the SwaggerUI section.
As I mentioned, I'm running .Net Core 2.0.3, I have the Nuget package Swashbuckle.AspNetCore 2.3.0 referenced.
What I get in the app regardless of what I do with the path is a 404 on the /swagger/v1/swagger.json file when I try to access {server}/{virtualdirectory}/swagger. The UI loads, but it won't load the json file, as it always tries to find it at server root.
Can someone point me in the right direction?
You must check your [http] route , dont use [routes] before http`s tag.
you must add a api route on the top and remove all routes before them Http:
[Route("api/[controller]")]
public class asteriskAPI:Controller
{ ........
}
and like this:
[HttpGet]
public ActionResult<List<ast_cel>> GetAll()
{
...
}
You need to change your app.UseSwaggerUI method to this
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("./swagger/v1/swagger.json", "Employee Service API");
});
Note the period.
Source: https://learn.microsoft.com/en-us/samples/aspnet/aspnetcore.docs/getstarted-swashbuckle-aspnetcore/

Asp.Net Core middleware pathstring startswithsegments issue

Have a Asp.NET Core 2.0 application and I would like to map any path that does not start with /api to just reexecute to the root path. I added the below but doesn't seem to work:
app.MapWhen(
c => !c.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase),
a => a.UseStatusCodePagesWithReExecute("/")
);
Not using MapWhen() and just using app.UseStatusCodePagesWithReExecute("/") works for all paths not root. Just want to add filtering for all paths not root and not /api. Any ideas on how to do this?
Branched pipeline does not work correctly here because you have not added MVC middleware after status code page middleware. Here is the correct pipeline setup:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.MapWhen(
c => !c.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase),
a =>
{
a.UseStatusCodePagesWithReExecute("/");
a.UseMvc();
});
app.UseMvc();
}
Note that middleware order matters here, you should add status code page middleware before MVC.
However using conditional pipeline seems like overkill here. You could achieve your goal with URL Rewriting Middleware:
var options = new RewriteOptions()
.AddRewrite(#"^(?!/api)", "/", skipRemainingRules: true);
app.UseRewriter(options);
app.UseMvc();

ASP.Net Core SignalR simple host - 404 error

I am wanting to have 1 simple console app host that is solely for self-hosting the SignalR component.
I have created an "Empty Web Application" using the template. I have created a very simple StartUp file that does not contain anything like MVC etc as it is not needed. However I am getting a 404 not found error from the browser when attempting to negotiate.
The Startup file is as follows:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddSignalR();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials());
app.UseSignalR(routes =>
{
routes.MapHub<Masterhub>("masterhub");
});
}
}
As you can see, it is very basic, but as I don't want any MVC/Web API functionality, I didn't include all of that setup. There is setup for CORS and SignalR, that is all.
Is what I am attempting to do possible?
It turns out that the JavaScript file I was using from the web client to connect to the self-hosted SignalR Console Application, was the old full .Net version, and not the new version you can get from NPM.

AspNet Core Identity - cookie not getting set in production

I have a .NET Core 2 web app and I want to use ASP.NET Identity to authenticate my users. On .NET Core 1.x, my code was working fine.
I migrated to .NET Core 2, and authentication works when running locally in Visual Studio. But when I deploy to a live environment, authentication stops working: the authentication cookie isn't being set in production.
My Startup.cs code looks like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentity<AppUser, RavenDB.IdentityRole>()
.AddDefaultTokenProviders();
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
app.UseAuthentication();
}
To sign in, my code looks like this:
public async Task<ActionResult> SignIn(...)
{
var user = ...; // Load the User from the database.
await this.signInManager.SignInAsync(user, isPersistent: true);
...
}
This code works locally: the ASP.NET Identity auth cookie is set. However, when I deploy this to production enviro in Azure, the cookie never gets set.
What am I missing?
I solved the problem. It boiled down to HTTPS: it appears that signInManager.SignInAsync(...) sets a cookie that is HTTPS-only. I was publishing to a non-HTTPS site initially for testing.
Once I published to an HTTPS site, the cookie started working again.
The reason it was working locally was that I was running in HTTPS locally.
Had same problem with Chrome 60+. Cookie did not want to set on HTTP site or even HTTPS and Cordova.
options.Cookie.SameSite = SameSiteMode.None;
https://github.com/aspnet/Docs/blob/master/aspnetcore/security/authentication/cookie.md
Changing from default value (Lax) to None fixed it for me.
I had similar issue. In the startup.cs file, I had to change
app.UseCookiePolicy(new CookiePolicyOptions
{
Secure = CookieSecurePolicy.Always
});
to
app.UseCookiePolicy(new CookiePolicyOptions
{
Secure = CookieSecurePolicy.SameAsRequest
});
This allowed cookie authentication to work on both http and https.