Mise en place de l'authentification Keycloak
This commit is contained in:
@@ -2,13 +2,57 @@ using ChessCubing.App;
|
||||
using ChessCubing.App.Services;
|
||||
using Microsoft.AspNetCore.Components.Web;
|
||||
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
|
||||
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
|
||||
|
||||
var builder = WebAssemblyHostBuilder.CreateDefault(args);
|
||||
builder.RootComponents.Add<App>("#app");
|
||||
builder.RootComponents.Add<HeadOutlet>("head::after");
|
||||
|
||||
var keycloakAuthority = builder.Configuration["Keycloak:Authority"] ?? "/auth/realms/chesscubing";
|
||||
var keycloakClientId = builder.Configuration["Keycloak:ClientId"] ?? "chesscubing-web";
|
||||
var keycloakResponseType = builder.Configuration["Keycloak:ResponseType"] ?? "code";
|
||||
var postLogoutRedirectUri = builder.Configuration["Keycloak:PostLogoutRedirectUri"] ?? "/";
|
||||
var defaultScopes = builder.Configuration
|
||||
.GetSection("Keycloak:DefaultScopes")
|
||||
.GetChildren()
|
||||
.Select(child => child.Value)
|
||||
.Where(value => !string.IsNullOrWhiteSpace(value))
|
||||
.Cast<string>()
|
||||
.ToArray();
|
||||
|
||||
builder.Services.AddScoped(_ => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
|
||||
builder.Services
|
||||
.AddOidcAuthentication(options =>
|
||||
{
|
||||
options.ProviderOptions.Authority = ResolveUri(builder.HostEnvironment.BaseAddress, keycloakAuthority);
|
||||
options.ProviderOptions.ClientId = keycloakClientId;
|
||||
options.ProviderOptions.ResponseType = keycloakResponseType;
|
||||
options.ProviderOptions.RedirectUri = ResolveUri(builder.HostEnvironment.BaseAddress, "authentication/login-callback");
|
||||
options.ProviderOptions.PostLogoutRedirectUri = ResolveUri(builder.HostEnvironment.BaseAddress, postLogoutRedirectUri);
|
||||
|
||||
options.ProviderOptions.DefaultScopes.Clear();
|
||||
foreach (var scope in defaultScopes.Length == 0 ? ["openid", "profile", "email"] : defaultScopes)
|
||||
{
|
||||
options.ProviderOptions.DefaultScopes.Add(scope);
|
||||
}
|
||||
|
||||
options.UserOptions.NameClaim = "preferred_username";
|
||||
options.UserOptions.RoleClaim = "role";
|
||||
})
|
||||
.AddAccountClaimsPrincipalFactory<KeycloakAccountFactory>();
|
||||
|
||||
builder.Services.AddScoped<BrowserBridge>();
|
||||
builder.Services.AddScoped<UserSession>();
|
||||
builder.Services.AddScoped<MatchStore>();
|
||||
|
||||
await builder.Build().RunAsync();
|
||||
|
||||
static string ResolveUri(string baseAddress, string value)
|
||||
{
|
||||
if (Uri.TryCreate(value, UriKind.Absolute, out var absoluteUri))
|
||||
{
|
||||
return absoluteUri.ToString();
|
||||
}
|
||||
|
||||
return new Uri(new Uri(baseAddress), value).ToString();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user