如何移除ASP.NET Razor应用的HTTPS授权访问限制?
Hey there! Let's work through this issue you're hitting with your Blazor app behind an AWS ALB. The root cause here is that even though you've turned off HTTPS redirection, ASP.NET Core's authorization system still sees incoming HTTP requests (from the ALB) as untrusted—since the ALB handles SSL termination and forwards HTTP traffic to your container. Here's how to fix this step by step:
1. Configure Forwarded Headers to Recognize the ALB
First, you need to tell ASP.NET Core it's behind a reverse proxy (the ALB) and trust the forwarded headers that confirm the original request was HTTPS.
In your Startup.cs, add this to the ConfigureServices method:
services.AddForwardedHeaders(options => { // Forward protocol (HTTP/HTTPS) and client IP from the ALB options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; // For production, add your ALB's IP address here to restrict trusted proxies // options.KnownProxies.Add(IPAddress.Parse("your-alb-ip-address")); // Alternatively, trust your VPC's CIDR range if you don't know the exact ALB IP // options.KnownNetworks.Add(new IPNetwork(IPAddress.Parse("10.0.0.0"), 8)); });
Then, in the Configure method, place this before any other middleware like UseAuthentication or UseAuthorization:
app.UseForwardedHeaders();
2. Disable HSTS (No Longer Needed with ALB)
Since the ALB handles all HTTPS enforcement, your containerized app doesn't need HSTS. Comment out or remove the app.UseHsts(); line in the non-development block:
else { app.UseExceptionHandler("/Error"); // app.UseHsts(); // Remove or comment this line }
3. Remove HTTPS Requirements from Authorization Policies
Check if any of your authorization policies explicitly require HTTPS. Look for this in ConfigureServices:
services.AddAuthorization(options => { options.FallbackPolicy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .RequireHttpsMetadata() // This forces HTTPS for auth data—delete it! .Build(); });
Delete the RequireHttpsMetadata() line—this setting blocks auth data over HTTP, which breaks the ALB-to-container connection.
4. Adjust Cookie Security Settings (If Using Cookie Auth)
If your app uses cookie-based authentication (like ASP.NET Core Identity), update the cookie policy to match the original request's security level:
services.AddCookie(options => { // Replace CookieSecurePolicy.Always with SameAsRequest options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; });
This ensures cookies work correctly with the ALB's HTTPS termination, while still keeping them secure for end users.
After applying these changes, your Blazor app will correctly recognize that the original user request was over HTTPS (even though traffic to the container is HTTP), and the AuthorizedAccess page should load without the "not authorized" error.
内容的提问来源于stack exchange,提问作者nmyster

