diff --git a/src/Server/Program.cs b/src/Server/Program.cs index 3a125d0..f2356cd 100644 --- a/src/Server/Program.cs +++ b/src/Server/Program.cs @@ -14,11 +14,13 @@ using FluentValidation.AspNetCore; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Identity.UI.Services; +using Microsoft.AspNetCore.Rewrite; using Microsoft.Extensions.Options; using Serilog; using Serilog.Context; using Serilog.Events; using System.IdentityModel.Tokens.Jwt; +using System.Net; using System.Reflection; using System.Security.Claims; @@ -136,13 +138,14 @@ }); } - app.UseHttpsRedirection(); + app.UseRewriter(new RewriteOptions() + .AddRedirectToWww() + .AddRedirectToHttps((int)HttpStatusCode.TemporaryRedirect)); app.UseBlazorFrameworkFiles(); app.UseStaticFiles(); app.UseRouting(); - app.UseCors(); app.UseIdentityServer(); app.UseAuthentication(); diff --git a/src/Tests/RedirectTests.cs b/src/Tests/RedirectTests.cs new file mode 100644 index 0000000..e5ae971 --- /dev/null +++ b/src/Tests/RedirectTests.cs @@ -0,0 +1,38 @@ +using Microsoft.AspNetCore.Mvc.Testing; + +namespace DynamoLeagueBlazor.Tests; + +public class RedirectTests +{ + [Fact] + public async Task GivenAnyRequest_WhenIsHttp_ThenIsRedirectedToHttps() + { + var webApplicationFactory = new WebApplicationFactory(); + + var client = webApplicationFactory.CreateClient(new WebApplicationFactoryClientOptions + { + AllowAutoRedirect = false, + BaseAddress = new Uri("http://www.test.com") + }); + + var response = await client.GetAsync(string.Empty); + + response.Headers.Location!.Scheme.Should().Be("https"); + } + + [Fact] + public async Task GivenAnyRequest_WhenIsNotWww_ThenIsRedirectedToWww() + { + var webApplicationFactory = new WebApplicationFactory(); + + var client = webApplicationFactory.CreateClient(new WebApplicationFactoryClientOptions + { + AllowAutoRedirect = false, + BaseAddress = new Uri("https://test.com") + }); + + var response = await client.GetAsync(string.Empty); + + response.Headers.Location!.AbsoluteUri.Should().Contain("www"); + } +}