Skip to content

Commit

Permalink
Upgrade .Net 8
Browse files Browse the repository at this point in the history
  • Loading branch information
phongnguyend committed Nov 1, 2024
1 parent 9fdd78a commit bba4af7
Show file tree
Hide file tree
Showing 5 changed files with 134 additions and 122 deletions.
25 changes: 13 additions & 12 deletions src/UIs/bff/ReverseProxy.Yarp/ConfigurationOptions/AppSettings.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
namespace ReverseProxy.Yarp.ConfigurationOptions
namespace ReverseProxy.Yarp.ConfigurationOptions;

public class AppSettings
{
public class AppSettings
{
public OpenIdConnect? OpenIdConnect { get; set; }
}
public OpenIdConnect? OpenIdConnect { get; set; }

public string? FrontendHostingMode { get; set; }
}

public class OpenIdConnect
{
public string? Authority { get; set; }
public class OpenIdConnect
{
public string? Authority { get; set; }

public string? ClientId { get; set; }
public string? ClientId { get; set; }

public string? ClientSecret { get; set; }
public string? ClientSecret { get; set; }

public bool RequireHttpsMetadata { get; set; }
}
public bool RequireHttpsMetadata { get; set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,60 +4,59 @@
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Mvc;

namespace ReverseProxy.Yarp.Controllers
namespace ReverseProxy.Yarp.Controllers;

public class AuthenticationController : ControllerBase
{
public class AuthenticationController : ControllerBase
private readonly IAntiforgery _forgeryService;

public AuthenticationController(IAntiforgery forgeryService)
{
private readonly IAntiforgery _forgeryService;
_forgeryService = forgeryService;
}

public AuthenticationController(IAntiforgery forgeryService)
[HttpGet("/login")]
public async Task LoginAsync(string returnUrl)
{
if (HttpContext.User.Identity?.IsAuthenticated ?? false)
{
_forgeryService = forgeryService;
Response.Redirect(Url.Content("~/").ToString());
}

[HttpGet("/login")]
public async Task LoginAsync(string returnUrl)
else
{
if (HttpContext.User.Identity?.IsAuthenticated ?? false)
{
Response.Redirect(Url.Content("~/").ToString());
}
else
await HttpContext.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme, new AuthenticationProperties
{
await HttpContext.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme, new AuthenticationProperties
{
RedirectUri = Url.IsLocalUrl(returnUrl) ? returnUrl : "/"
});
}
RedirectUri = Url.IsLocalUrl(returnUrl) ? returnUrl : "/"
});
}
}

[HttpGet("/logout")]
public async Task LogoutAsync()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);
}
[HttpGet("/logout")]
public async Task LogoutAsync()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);
}

[HttpGet("/userinfor")]
public IActionResult UserInfor()
[HttpGet("/userinfor")]
public IActionResult UserInfor()
{
if (HttpContext.User.Identity?.IsAuthenticated ?? false)
{
if (HttpContext.User.Identity?.IsAuthenticated ?? false)
{
var tokens = _forgeryService.GetAndStoreTokens(HttpContext);
HttpContext.Response.Cookies.Append("PHONG-XSRF-TOKEN", tokens.RequestToken!, new CookieOptions { HttpOnly = false });
var tokens = _forgeryService.GetAndStoreTokens(HttpContext);
HttpContext.Response.Cookies.Append("PHONG-XSRF-TOKEN", tokens.RequestToken!, new CookieOptions { HttpOnly = false });

return Ok(new
{
Id = "",
FirstName = "Phong",
LastName = "Nguyen",
Timestamp = DateTimeOffset.Now
});
}
else
return Ok(new
{
return Unauthorized();
}
Id = "",
FirstName = "Phong",
LastName = "Nguyen",
Timestamp = DateTimeOffset.Now
});
}
else
{
return Unauthorized();
}
}
}
139 changes: 73 additions & 66 deletions src/UIs/bff/ReverseProxy.Yarp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,92 +8,99 @@
using System.Net.Http.Headers;
using Yarp.ReverseProxy.Transforms;

namespace Practical.ReverseProxy.Yarp
namespace ReverseProxy.Yarp;

public class Program
{
public class Program
public static void Main(string[] args)
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;
var configuration = builder.Configuration;
var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;
var configuration = builder.Configuration;

var appSettings = new AppSettings();
configuration.Bind(appSettings);
var appSettings = new AppSettings();
configuration.Bind(appSettings);

// Add the reverse proxy to capability to the server
var proxyBuilder = builder.Services.AddReverseProxy();
// Add the reverse proxy to capability to the server
var proxyBuilder = builder.Services.AddReverseProxy();

// Initialize the reverse proxy from the "ReverseProxy" section of configuration
proxyBuilder.LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"))
.AddTransforms(transformBuilderContext =>
// Initialize the reverse proxy from the "ReverseProxy" section of configuration
proxyBuilder.LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"))
.AddTransforms(transformBuilderContext =>
{
transformBuilderContext.AddRequestTransform(async transformContext =>
{
transformBuilderContext.AddRequestTransform(async transformContext =>
{
var user = transformContext.HttpContext.User;
var token = await transformContext.HttpContext.GetTokenAsync(OpenIdConnectParameterNames.AccessToken);
transformContext.ProxyRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
});

var user = transformContext.HttpContext.User;
var token = await transformContext.HttpContext.GetTokenAsync(OpenIdConnectParameterNames.AccessToken);
transformContext.ProxyRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
});

services.AddControllers();
});

services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
services.AddControllers();

services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.AccessDeniedPath = "/Authorization/AccessDenied";
})
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.Authority = appSettings.OpenIdConnect?.Authority;
options.ClientId = appSettings.OpenIdConnect?.ClientId;
options.ClientSecret = appSettings.OpenIdConnect?.ClientSecret;
options.ResponseType = "code";
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("ClassifiedAds.WebAPI");
options.Scope.Add("offline_access");
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.RequireHttpsMetadata = appSettings.OpenIdConnect?.RequireHttpsMetadata ?? false;
});
services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");

services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.AccessDeniedPath = "/Authorization/AccessDenied";
})
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.Authority = appSettings.OpenIdConnect?.Authority;
options.ClientId = appSettings.OpenIdConnect?.ClientId;
options.ClientSecret = appSettings.OpenIdConnect?.ClientSecret;
options.ResponseType = "code";
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("ClassifiedAds.WebAPI");
options.Scope.Add("offline_access");
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.RequireHttpsMetadata = appSettings.OpenIdConnect?.RequireHttpsMetadata ?? false;
});

var app = builder.Build();
var app = builder.Build();

app.MapControllers();
app.MapControllers();

app.Use(async (context, next) =>
app.Use(async (context, next) =>
{
if (context.Request.Path.Value?.StartsWith("/api/", StringComparison.OrdinalIgnoreCase) ?? false)
{
if (context.Request.Path.Value?.StartsWith("/api/", StringComparison.OrdinalIgnoreCase) ?? false)
try
{
try
{
var antiForgeryService = context.RequestServices.GetRequiredService<IAntiforgery>();
await antiForgeryService.ValidateRequestAsync(context);
}
catch (AntiforgeryValidationException)
{
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return;
}
var antiForgeryService = context.RequestServices.GetRequiredService<IAntiforgery>();
await antiForgeryService.ValidateRequestAsync(context);
}
catch (AntiforgeryValidationException)
{
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return;
}
}

await next(context);
});
await next(context);
});

app.MapReverseProxy();
app.MapReverseProxy();

if (appSettings.FrontendHostingMode == "InProcess")
{
app.UseStaticFiles();
app.MapFallbackToFile("index.html");
}
else
{
app.MapForwarder("{**rest}", "http://localhost:3000");

app.Run();
}

app.Run();
}
}
10 changes: 7 additions & 3 deletions src/UIs/bff/ReverseProxy.Yarp/ReverseProxy.Yarp.csproj
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="7.0.9" />
<PackageReference Include="Yarp.ReverseProxy" Version="2.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="8.0.10" />
<PackageReference Include="Yarp.ReverseProxy" Version="2.2.0" />
</ItemGroup>

<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>

</Project>
1 change: 1 addition & 0 deletions src/UIs/bff/ReverseProxy.Yarp/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"ClientSecret": "secret",
"RequireHttpsMetadata": "true"
},
"FrontendHostingMode": "OutOfProcess", // "InProcess" or "OutOfProcess"
"ReverseProxy": {
"Routes": {
"route1": {
Expand Down

0 comments on commit bba4af7

Please sign in to comment.