From 204e3a11fa8fcce549a0de2db782f0d0c20b4966 Mon Sep 17 00:00:00 2001 From: vnugent Date: Sat, 19 Aug 2023 23:48:07 -0400 Subject: Accounts middleware development updates --- .../src/Endpoints/Auth0.cs | 177 --------------------- .../src/SocialEntryPoint.cs | 7 - .../src/SocialOauthBase.cs | 7 +- 3 files changed, 5 insertions(+), 186 deletions(-) delete mode 100644 plugins/VNLib.Plugins.Essentials.SocialOauth/src/Endpoints/Auth0.cs (limited to 'plugins/VNLib.Plugins.Essentials.SocialOauth/src') diff --git a/plugins/VNLib.Plugins.Essentials.SocialOauth/src/Endpoints/Auth0.cs b/plugins/VNLib.Plugins.Essentials.SocialOauth/src/Endpoints/Auth0.cs deleted file mode 100644 index 259e830..0000000 --- a/plugins/VNLib.Plugins.Essentials.SocialOauth/src/Endpoints/Auth0.cs +++ /dev/null @@ -1,177 +0,0 @@ -/* -* Copyright (c) 2023 Vaughn Nugent -* -* Library: VNLib -* Package: VNLib.Plugins.Essentials.SocialOauth -* File: Auth0.cs -* -* Auth0.cs is part of VNLib.Plugins.Essentials.SocialOauth which is part of the larger -* VNLib collection of libraries and utilities. -* -* VNLib.Plugins.Essentials.SocialOauth is free software: you can redistribute it and/or modify -* it under the terms of the GNU Affero General Public License as -* published by the Free Software Foundation, either version 3 of the -* License, or (at your option) any later version. -* -* VNLib.Plugins.Essentials.SocialOauth is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU Affero General Public License for more details. -* -* You should have received a copy of the GNU Affero General Public License -* along with this program. If not, see https://www.gnu.org/licenses/. -*/ - -using System; -using System.Linq; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using System.Collections.Generic; - -using RestSharp; - -using VNLib.Hashing; -using VNLib.Hashing.IdentityUtility; -using VNLib.Utils.Logging; -using VNLib.Plugins.Essentials.Accounts; -using VNLib.Plugins.Extensions.Loading; -using VNLib.Net.Rest.Client.Construction; - -namespace VNLib.Plugins.Essentials.SocialOauth.Endpoints -{ - - [ConfigurationName("auth0")] - internal sealed class Auth0 : SocialOauthBase - { - private readonly IAsyncLazy Auth0VerificationJwk; - - public Auth0(PluginBase plugin, IConfigScope config) : base(plugin, config) - { - string keyUrl = config["key_url"].GetString() ?? throw new KeyNotFoundException("Missing Auth0 'key_url' from config"); - - //Define the key endpoint - SiteAdapter.DefineSingleEndpoint() - .WithEndpoint() - .WithUrl(keyUrl) - .WithMethod(Method.Get) - .WithHeader("Accept", "application/json") - .OnResponse((r, res) => res.ThrowIfError()); - - //Get certificate on background thread - Auth0VerificationJwk = Task.Run(GetRsaCertificate).AsLazy(); - } - - private async Task GetRsaCertificate() - { - try - { - Log.Debug("Getting Auth0 signing keys"); - - //rent client from pool - RestResponse response = await SiteAdapter.ExecuteAsync(new GetKeyRequest()); - - //Get response as doc - using JsonDocument doc = JsonDocument.Parse(response.RawBytes); - - //Create a new jwk from each key element in the response - ReadOnlyJsonWebKey[] keys = doc.RootElement.GetProperty("keys") - .EnumerateArray() - .Select(static k => new ReadOnlyJsonWebKey(k)) - .ToArray(); - - Log.Debug("Found {count} Auth0 signing keys", keys.Length); - - return keys; - } - catch (Exception e) - { - Log.Error(e, "Failed to get Auth0 signing keys"); - throw; - } - } - - /* - * Auth0 uses the format "platoform|{user_id}" for the user id so it should match the - * external platofrm as github and discord endoints also - */ - - private static string GetUserIdFromPlatform(string userName) - { - return ManagedHash.ComputeHash(userName, HashAlg.SHA1, HashEncodingMode.Hexadecimal); - } - - - private static readonly Task EmptyLoginData = Task.FromResult(null); - - protected override Task GetLoginDataAsync(IOAuthAccessState clientAccess, CancellationToken cancellation) - { - //recover the identity token - using JsonWebToken jwt = JsonWebToken.Parse(clientAccess.IdToken); - - //Verify the token against the first signing key - if (!jwt.VerifyFromJwk(Auth0VerificationJwk.Value[0])) - { - return EmptyLoginData; - } - - using JsonDocument userData = jwt.GetPayload(); - - int iat = userData.RootElement.GetProperty("iat").GetInt32(); - int exp = userData.RootElement.GetProperty("exp").GetInt32(); - - string userId = userData.RootElement.GetProperty("sub").GetString() ?? throw new Exception("Missing sub in jwt"); - string audience = userData.RootElement.GetProperty("aud").GetString() ?? throw new Exception("Missing aud in jwt"); - string issuer = userData.RootElement.GetProperty("iss").GetString() ?? throw new Exception("Missing iss in jwt"); - - if(exp < DateTimeOffset.UtcNow.ToUnixTimeSeconds()) - { - //Expired - return EmptyLoginData; - } - - //Verify audience matches client id - if (!Config.ClientID.Value.Equals(audience, StringComparison.Ordinal)) - { - //Invalid audience - return EmptyLoginData; - } - - return Task.FromResult(new UserLoginData() - { - UserId = GetUserIdFromPlatform(userId) - }); - } - - /* - * Account data may be recovered from the identity token - * and it happens after a call to GetLoginData so - * we do not need to re-verify the token - */ - protected override Task GetAccountDataAsync(IOAuthAccessState clientAccess, CancellationToken cancellationToken) - { - using JsonWebToken jwt = JsonWebToken.Parse(clientAccess.IdToken); - - //verify signature - - using JsonDocument userData = jwt.GetPayload(); - - if (!userData.RootElement.GetProperty("email_verified").GetBoolean()) - { - return Task.FromResult(null); - } - - string fullName = userData.RootElement.GetProperty("name").GetString() ?? " "; - - return Task.FromResult(new AccountData() - { - EmailAddress = userData.RootElement.GetProperty("email").GetString(), - First = fullName.Split(' ').FirstOrDefault(), - Last = fullName.Split(' ').LastOrDefault(), - }); - } - - private sealed record class GetKeyRequest() - { } - } -} diff --git a/plugins/VNLib.Plugins.Essentials.SocialOauth/src/SocialEntryPoint.cs b/plugins/VNLib.Plugins.Essentials.SocialOauth/src/SocialEntryPoint.cs index 05152b2..83e45c8 100644 --- a/plugins/VNLib.Plugins.Essentials.SocialOauth/src/SocialEntryPoint.cs +++ b/plugins/VNLib.Plugins.Essentials.SocialOauth/src/SocialEntryPoint.cs @@ -51,13 +51,6 @@ namespace VNLib.Plugins.Essentials.SocialOauth this.Route(); Log.Information("Github social OAuth authentication loaded"); } - - if (this.HasConfigForType()) - { - //Add the auth0 login endpoint - this.Route(); - Log.Information("Auth0 social OAuth authentication loaded"); - } } diff --git a/plugins/VNLib.Plugins.Essentials.SocialOauth/src/SocialOauthBase.cs b/plugins/VNLib.Plugins.Essentials.SocialOauth/src/SocialOauthBase.cs index f36dc39..38281d4 100644 --- a/plugins/VNLib.Plugins.Essentials.SocialOauth/src/SocialOauthBase.cs +++ b/plugins/VNLib.Plugins.Essentials.SocialOauth/src/SocialOauthBase.cs @@ -146,6 +146,7 @@ namespace VNLib.Plugins.Essentials.SocialOauth return val; } + private static IValidator GetNonceValidator() { InlineValidator val = new(); @@ -281,7 +282,8 @@ namespace VNLib.Plugins.Essentials.SocialOauth protected override async ValueTask GetAsync(HttpEntity entity) { //Make sure state and code parameters are available - if (entity.QueryArgs.TryGetNonEmptyValue("state", out string? state) && entity.QueryArgs.TryGetNonEmptyValue("code", out string? code)) + if (entity.QueryArgs.TryGetNonEmptyValue("state", out string? state) + && entity.QueryArgs.TryGetNonEmptyValue("code", out string? code)) { //Disable refer headers when nonce is set entity.Server.Headers["Referrer-Policy"] = "no-referrer"; @@ -633,7 +635,8 @@ namespace VNLib.Plugins.Essentials.SocialOauth Secure = true, HttpOnly = true, ValidFor = Config.InitClaimValidFor, - SameSite = CookieSameSite.SameSite + SameSite = CookieSameSite.SameSite, + Path = this.Path }; entity.Server.SetCookie(in cookie); -- cgit