Force HTTPS in route generation - ssl

How do I force ASP.NET Web.API to generate HTTPS links?
In my MVC app, I am generating urls in the views this way #Url.HttpRouteUrl("DefaultApi", new { controller = "People" })
But if the web app is accessed through HTTP, the links will use the HTTP schema. I want to force the HTTPS for the connections to the Web API.
I know there are examples of the RequireHttpsAttribute in internet, but those examples just refuse the connection if HTTPS is required and not provided, what is fine. What I want is that even if the app is accessed through HTTP, the links to the Web API be generated with the HTTPS schema.
Cheers.

You could use the RouteUrl method which allows you so specify the protocol and thus generate an absolute URL with this protocol:
#Url.RouteUrl(
"DefaultApi",
new { httproute = "", controller = "People" },
"https"
)
Notice the httproute = "" route value to indicate that we want to generate a route for a Web API controller and not MVC controller.

Related

.NET Core RedirectToAction not working correctly behind Nginx

I'm trying to deploy my web api behind nginx.
My web API is always start with http://<host>/api/<controllerName>
But I use Nginx reverse proxy to handling test and prod server request
The request to test server http://<host>/api/<controllerName>/<action> turn to http://<host>/test/api/<controllerName>/<action>
Everything is OK so far except I use RedirectToActionResult in some action. It still redirect to url to http://<host>/api/<controllerName>/<action> format. Is there any way I could adjust RedirectToActionResult to redirect with prefix like http://<host>/test/api/<controllerName>/<action>?
Or I have to modify the whole API server url with prefix path.
You can set ASPNETCORE_PATHBASE=/test in your Environment.
And in your Startup.cs, you can add below code.
var pathBase = Environment.GetEnvironmentVariable("ASPNETCORE_PATHBASE");
app.UsePathBase(new PathString(pathBase))
Related Post:
ASP.Net Core Reverse Proxy with different root

Blazor server side behind reverse proxy 404

I have a blazor server-side app hosted on IIS behind a reverse proxy (using ARR).
I have tried everything I can think of, but I keep getting 404 on
_framework/blazor.server.js
My base href is is set to "/subsite/":
<base href="/subsite/" />
and all my src values are relative like this:
<script src="_framework/blazor.server.js"></script>
<script src="_content/BlazorInputFile/inputfile.js"></script>
<script src="animations.js"></script>
Every other script ref loads fine, EVEN the _content data, but not the blazor.server.js.
I tried the old PathBase trick for MVC apps as well with no success:
if (!env.IsDevelopment()) {
app.Use((context, next) => {
context.Request.PathBase = new PathString("/subsite");
return next();
});
}
Can anyone tell me how to make Blazor realize where to put the blazor.server.js in a reverse proxy scenario?
Did you try the UsePathBase ?
app.UsePathBase("/subsite");
Here is my test result
Please check this article for more
https://www.billbogaiv.com/posts/net-core-hosted-on-subdirectories-in-nginx
From docs.
Rewrite URLs for correct routing
Routing requests for page components in a Blazor WebAssembly app isn't as straightforward as routing requests in a Blazor Server, hosted app. Consider a Blazor WebAssembly app with two components:
Main.razor – Loads at the root of the app and contains a link to the About component (href="About").
About.razor – About component.
When the app's default document is requested using the browser's address
bar (for example, https://www.contoso.com/):
The browser makes a request.
The default page is returned, which is usually index.html.
index.html bootstraps the app.
Blazor's router loads, and the Razor Main component is rendered.
In the Main page, selecting the link to the About component works on the client because the Blazor router stops the browser from making a request on the Internet to www.contoso.com for About and serves the rendered About component itself. All of the requests for internal endpoints within the Blazor WebAssembly app work the same way: Requests don't trigger browser-based requests to server-hosted resources on the Internet. The router handles the requests internally.
If a request is made using the browser's address bar for www.contoso.com/About, the request fails. No such resource exists on the app's Internet host, so a 404 - Not Found response is returned.
Because browsers make requests to Internet-based hosts for client-side pages, web servers and hosting services must rewrite all requests for resources not physically on the server to the index.html page. When index.html is returned, the app's Blazor router takes over and responds with the correct resource.
When deploying to an IIS server, you can use the URL Rewrite Module with the app's published web.config file. For more information, see the IIS section.
Maybe you could try to enable the forward proxy in IIS manager->server node->application request routing cache->proxy->enable.
If you only have one website, you could just add the website to ARR server farm and then it will create the routing rule automatically. It will be convenient to monitor the back-end server with health check.
Is this ARR warning causing my 404?

Need to make actionscript POST data over https

I have an application that was recently given an AWS certificate (and put in an ELB - classic I think).
The web application has a Flash movie that makes web calls (to same site URL) in order to fetch data using Zend Framework 1 models. The page in browser does not change.
When I request the site over https, all of the imported items have been changed over to https protocol, but when the Flash movie initializes, it makes non-secure requests over http.
It makes these non-secure requests when I load the site over http, or https.
The reason I mentioned the AWS ELB is because I was told that the ELB is doing some kind of redirect to port 80.
If I request the site over https, and immediately do print_r on $_SERVER array I am only seeing HTTPS as a REDIRECT key, and not seeing $_SERVER['HTTPS'] set, which I think is important.
In summary, the Flash movie, inside a Zend 1.12 site, is making POST requests over http, and I'd like it to make the same requests, but over https.
It is a very old Flash movie, and although I've opened the swf file with a decompiler, I do not know much about actionscript to see where (in the many code files) I'd be able to instruct the movie to call https instead of http.
My theory is that when the site is properly running as SSL/https that the flash movie may ?possibly? start making https calls since at the moment is "is" using the address bar URL, but there also could be that ELB redirect stuff happening that's gumming it up as well.
Update: I found (what appears to be) evidence that if https is detected in the URL it's given, that it will then make secure requests...
FILE: mx.rpc.remoting.RemoteObject
mx_internal function initEndpoint() : void
{
var chan:Channel = null;
if(endpoint != null)
{
if(endpoint.indexOf("https") == 0)
{
chan = new SecureAMFChannel(null,endpoint);
}
else
{
chan = new AMFChannel(null,endpoint);
}
channelSet = new ChannelSet();
channelSet.addChannel(chan);
}
}
Thanks,
Adam
I was able to restore the original/old unedited Flash SWF File, and instead modified the PHP Code that passes in a variable and value called "endpoint".
In the code sample I provided, it checks if endpoint has https in it (which I initially thought that it did).
I added code to modify the value of "endpoint" when HTTP_X_FORWARDED_PROTO was "https", sample below: (the $request->getBaseUrl() is from Zend Framework).
if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
$endpoint = sprintf(
'%s://%s%s',
$_SERVER['HTTP_X_FORWARDED_PROTO'],
$_SERVER['HTTP_HOST'],
$request->getBaseUrl()
);
} else {
// use existing (and working) value for endpoint
}
With that code in place, the FLASH movie loads in, and operates properly
whether site is loaded with http or with https

Can't turn off requirehttps in asp.net 5 MVC 6 site

I have an asp.net 5 MVC 6 site I am working on. I turned on require HTTPS like so:
services.AddMvc(options =>
{
options.Filters.Add(new RequireHttpsAttribute());
});
It worked great, and I have been working like this for a little while. Today I need to turn it off, so I commented out the options filter, but it is still requiring HTTPS.
I have not used the [RequireHttps] attribute on the controllers or actions themselves.
I have gone into the properties and unchecked "Enable SSL" and pasted the http url in the "Launch URL" box.
I have shutdown IIS Express and relaunched the site. It doesn't seem to matter what I do, it continues to try to redirect to HTTPS.
Is it possible IIS Express or Kestral has cached something I need to delete?
Anyone have any suggestions of what else could be forcing it to HTTPS?
The RequireHttpsAttribute implementation will send a permanent redirect response (301) back to browser:
// redirect to HTTPS version of page
filterContext.Result = new RedirectResult(newUrl, permanent: true);
This means that when you initially had the attribute enabled and requested a url like http://localhost:62058/, the server will respond with:
301 (Moved permanently)
Location: https://localhost:62058/
If you look at the definition of the 301 response code you will see that browsers will cache it by default:
The requested resource has been assigned a new permanent URI and any
future references to this resource SHOULD use one of the returned
URIs. Clients with link editing capabilities ought to automatically
re-link references to the Request-URI to one or more of the new
references returned by the server, where possible. This response is
cacheable unless indicated otherwise.
The new permanent URI SHOULD be given by the Location field in the
response. Unless the request method was HEAD, the entity of the
response SHOULD contain a short hypertext note with a hyperlink to the
new URI(s).
After you remove the RequireHttps filter, the browser will still use the cached response:
So all you need to do after removing the RequireHttps filter is rebuild and clear the browser cache!

Servicestack Swagger UI endpoint not behaving as expected with UseHttpsLinks

Using 4.0.31, my AppHost Configure method is declared like this:
public override void Configure(Funq.Container container)
{
HostConfig hc = new HostConfig()
{ HandlerFactoryPath = "api", UseHttpsLinks = true };
SetConfig(hc);
Plugins.Add(new CorsFeature());
Plugins.Add(new SwaggerFeature());
...
}
I was under the impression that this would set the url for swagger-ui to be the https version of ../api/resources, however I'm still getting the regular http endpoint in the swagger URL textbox, like:
http://example.com/myapp/api/resources
Our web servers are behind load-balancers that perform SSL offloading (and require SSL), so the URL should be:
https://example.com/myapp/api/resources
On a positive note, using 'UseHttpsLinks' actually allows swagger-ui to function once you fix the endpoint url. It didn't work at all without it!
I'm overriding the swagger url property using a replacement index.html via the Virtual File System as a hack -- since in the development, QA, and staging environments, the url property is pointing to production...(not so good)
Config.UseHttpsLinks has been expanded to also apply to the BaseUrl where it now changes http:// urls to https:// in this commit.
This change is available from v4.0.33+ that's now available on MyGet.