Skip to content

Commit

Permalink
Integration towards production server.
Browse files Browse the repository at this point in the history
  • Loading branch information
KristofferStrube committed Dec 27, 2023
1 parent e8d139b commit 2109638
Show file tree
Hide file tree
Showing 18 changed files with 482 additions and 98 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,8 @@
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\KristofferStrube.Blazor.WebAuthentication\KristofferStrube.Blazor.WebAuthentication.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -1,23 +1,133 @@
using Microsoft.AspNetCore.Http.HttpResults;
using KristofferStrube.Blazor.WebAuthentication.JSONRepresentations;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using System.Security.Cryptography;

namespace KristofferStrube.Blazor.WebAuthentication.API;

public static class WebAuthenticationAPI
{
public static Dictionary<string, byte[]> Challenges = [];

public static Dictionary<string, List<byte[]>> Credentials = [];

public static Dictionary<string, (COSEAlgorithm algorithm, byte[] key)> PublicKeys = [];

public static IEndpointRouteBuilder MapWebAuthenticationAPI(this IEndpointRouteBuilder builder)
{
RouteGroupBuilder group = builder
.MapGroup("WebAuthentication");

_ = group.MapGet("Register/{userName}", Register)
_ = group.MapGet("RegisterChallenge/{userName}", RegisterChallenge)
.WithName("Register Challenge");

_ = group.MapPost("Register/{userName}", Register)
.WithName("Register");

_ = group.MapGet("ValidateChallenge/{userName}", ValidateChallenge)
.WithName("Validate Challenge");

_ = group.MapPost("Validate/{userName}", Validate)
.WithName("Validate");

return builder;
}

public static Ok<byte[]> Register(string userName)

public static Ok<byte[]> RegisterChallenge(string userName)
{
byte[] challenge = RandomNumberGenerator.GetBytes(32);
Challenges[userName] = challenge;
return TypedResults.Ok(challenge);
}

public static Ok<bool> Register(string userName, [FromBody] RegistrationResponseJSON registration)
{
if (Credentials.TryGetValue(userName, out List<byte[]>? credentialList))
{
credentialList.Add(Convert.FromBase64String(registration.RawId));
}
else
{
Credentials[userName] = [Convert.FromBase64String(registration.RawId)];
}
PublicKeys[registration.RawId] = ((COSEAlgorithm)registration.Response.PublicKeyAlgorithm, Convert.FromBase64String(registration.Response.PublicKey));
return TypedResults.Ok(true);
}

public static Ok<ValidateCredentials> ValidateChallenge(string userName)
{
if (!Credentials.TryGetValue(userName, out List<byte[]>? credentialList))
{
return TypedResults.Ok<ValidateCredentials>(new([], []));
}
byte[] challenge = RandomNumberGenerator.GetBytes(32);
Challenges[userName] = challenge;
return TypedResults.Ok<ValidateCredentials>(new (challenge, credentialList));
}

public class ValidateCredentials(byte[] challenge, List<byte[]> credentials)
{
public byte[] Challenge { get; set; } = challenge;
public List<byte[]> Credentials { get; set; } = credentials;
}

public static Ok<bool> Validate(string userName, [FromBody] AuthenticationResponseJSON authentication)
{
if (!PublicKeys.TryGetValue(authentication.RawId, out (COSEAlgorithm algorithm, byte[] key) publicKey))
{
return TypedResults.Ok(false);
}

return TypedResults.Ok(VerifySignature(publicKey.algorithm, publicKey.key, authentication.Response.AuthenticatorData, authentication.Response.ClientDataJSON, authentication.Response.Signature));
}

public static bool VerifySignature(COSEAlgorithm publicKeyAlgorithm, byte[] publicKey, string authenticatorData, string clientData, string signature)
{
return TypedResults.Ok(RandomNumberGenerator.GetBytes(32));
if (publicKeyAlgorithm is COSEAlgorithm.ES256)
{
var dsa = ECDsa.Create(new ECParameters
{
Curve = ECCurve.NamedCurves.nistP256,
Q = new()
{
X = publicKey.Take(32).ToArray(),
Y = publicKey.Skip(32).ToArray()
}
});

var Hash = SHA256.Create();

byte[] hashedClientData = Hash.ComputeHash(Convert.FromBase64String(clientData));

bool result = dsa.VerifyData(Convert.FromBase64String(authenticatorData).Concat(hashedClientData).ToArray(), Convert.FromBase64String(signature), HashAlgorithmName.SHA256);

return result;
}
else if (publicKeyAlgorithm is COSEAlgorithm.RS256)
{
using var rsa = new RSACryptoServiceProvider();

try
{
rsa.ImportSubjectPublicKeyInfo(publicKey, out _);

var Hash = SHA256.Create();

byte[] hashedClientData = Hash.ComputeHash(Convert.FromBase64String(clientData));

bool result = rsa.VerifyData(Convert.FromBase64String(authenticatorData).Concat(hashedClientData).ToArray(), Convert.FromBase64String(signature), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);

return result;
}
catch (CryptographicException)
{
return false;
}
finally
{
rsa.PersistKeyInCsp = false;
}
}
return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,48 +12,47 @@
return;
}

<p>Here you can try create a credential from your device's native identification mechanism.</p>
<p>
Here you can try to register some credentials and validate them.
<br />
<small>If you have registered some credentials for a username within 20 minutes then you can still validate it even after having refreshed this page as it is the server that remembers credentials.</small>
</p>

<button class="btn btn-success" @onclick="CreateCredential">Create Credentials</button>
<label for="username">Username</label>
<input id="username" @bind=username />
<br />
<br />
<button class="btn btn-success" @onclick="CreateCredential">Register</button>

<br />
@if (publicKey is not null)
{
<b>Registered a user! 🎊</b>
<br/>
<b>Public Key: </b> @string.Join(", ", publicKey.Select(b => $"{b:X2}"))
<br />
}
@if (challenge is not null)
{
<br />
<b>Challenge: </b> @string.Join(", ", challenge.Select(b => $"{b:X2}"))
<br />
}
<br />
@if (credential is not null)
<button class="btn btn-primary" @onclick="GetCredential">Validate Credentials</button>

@if (validated is { } success)
{
<b>Type: </b> @type
<br />
<b>Id: </b> @id
<br />
@if (challenge is not null)
{
<b>Challenge: </b> @string.Join(", ", challenge.Select(b => $"{b:X2}"))
<br />
}
@if (publicKey is not null)
{
<b>Public Key: </b> @string.Join(", ", publicKey.Select(b => $"{b:X2}"))
<br />
}
<br />
<button class="btn btn-primary" @onclick="GetCredential">Request Credentials from Id</button>

@if (successfulGettingCredential is {} success)
{
<br />
<br />
<div class="rounded p-2 text-white @(success ? "bg-success": "bg-danger")">
@(success ? "You logged in and validated your credentials" : errorMessage ?? "You were not successful in logging on.")
</div>
@if (signature is not null)
{
<b>Signature: </b> @string.Join(", ", signature.Select(b => $"{b:X2}"))
;
<br />
}
}
<br />
<br />
<div class="rounded p-2 text-white @(success ? "bg-success": "bg-danger")">
@(success ? "You logged in and validated your credentials" : errorMessage ?? "You were not successful in logging on.")
</div>
}
else if (errorMessage is not null)
{
<br />
<br />
<div class="rounded p-2 text-white bg-danger">@errorMessage</div>
}

Original file line number Diff line number Diff line change
@@ -1,26 +1,24 @@
using KristofferStrube.Blazor.CredentialManagement;
using KristofferStrube.Blazor.WebIDL;
using KristofferStrube.Blazor.WebAuthentication.JSONRepresentations;
using KristofferStrube.Blazor.WebIDL.Exceptions;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using System.Security.Cryptography;
using System.Text;
using static KristofferStrube.Blazor.WebAuthentication.WasmExample.WebAuthenticationClient;

namespace KristofferStrube.Blazor.WebAuthentication.WasmExample.Pages;

public partial class Index : ComponentBase
{
private bool isSupported = false;
private string username = "";
private CredentialsContainer container = default!;
private PublicKeyCredential? credential;
private PublicKeyCredential? validatedCredential;
private bool? successfulGettingCredential = null;
private string? type;
private string? id;
private bool? validated = null;
private string? errorMessage;
private byte[]? challenge;
private byte[]? publicKey;
private byte[]? signature;

[Inject]
public required IJSRuntime JSRuntime { get; set; }
Expand All @@ -38,8 +36,7 @@ protected override async Task OnInitializedAsync()
private async Task CreateCredential()
{
byte[] userId = Encoding.ASCII.GetBytes("bob");
//challenge = await WebAuthenticationClient.Register("bob");
challenge = RandomNumberGenerator.GetBytes(32);
challenge = await WebAuthenticationClient.RegisterChallenge("bob");
CredentialCreationOptions options = new()
{
PublicKey = new PublicKeyCredentialCreationOptions()
Expand Down Expand Up @@ -79,43 +76,52 @@ private async Task CreateCredential()
{
credential = await container.CreateAsync(options) is { } c ? new PublicKeyCredential(c) : null;

AuthenticatorResponse registrationResponse = await credential.GetResponseAsync();
if (registrationResponse is AuthenticatorAttestationResponse { } registration)
if (credential is not null)
{
IJSObjectReference rawBuffer = await registration.GetPublicKeyAsync();
IJSObjectReference uint8ArrayFromBuffer = await (await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./_content/KristofferStrube.Blazor.WebIDL/KristofferStrube.Blazor.WebIDL.js")).InvokeAsync<IJSObjectReference>("constructUint8Array", rawBuffer);
Uint8Array uint8Array = await Uint8Array.CreateAsync(JSRuntime, uint8ArrayFromBuffer);
publicKey = await uint8Array.GetByteArrayAsync();
PublicKeyCredentialJSON registrationResponse = await credential.ToJSONAsync();
if (registrationResponse is RegistrationResponseJSON { } registration)
{
await WebAuthenticationClient.Register("bob", registration);
publicKey = registration.Response.PublicKey is not null ? Convert.FromBase64String(registration.Response.PublicKey) : null;
}
}

errorMessage = null;
}
catch (DOMException exception)
{
errorMessage = $"{exception.Name}: \"{exception.Message}\"";
credential = null;
}
if (credential is not null)
{
type = await credential.GetTypeAsync();
id = await credential.GetIdAsync();
}
}

private async Task GetCredential()
{
byte[] challenge = RandomNumberGenerator.GetBytes(32);
ValidateCredentials? setup = await WebAuthenticationClient.ValidateChallenge("bob");
if (setup is not { Challenge: { Length: > 0 } challenge, Credentials: { Count: > 0 } credentials })
{
errorMessage = "The user was not previously registered.";
return;
}
this.challenge = challenge;

List<PublicKeyCredentialDescriptor> allowCredentials = new(credentials.Count);
foreach (byte[] credential in credentials)
{
allowCredentials.Add(new PublicKeyCredentialDescriptor()
{
Type = PublicKeyCredentialType.PublicKey,
Id = await JSRuntime.InvokeAsync<IJSObjectReference>("buffer", credential)
});
}

CredentialRequestOptions options = new()
{
PublicKey = new PublicKeyCredentialRequestOptions()
{
Challenge = challenge,
Timeout = 360000,
AllowCredentials = [
new PublicKeyCredentialDescriptor()
{
Type = PublicKeyCredentialType.PublicKey,
Id = await credential!.GetRawIdAsync()
}
]
AllowCredentials = allowCredentials.ToArray()
}
};

Expand All @@ -125,25 +131,21 @@ private async Task GetCredential()

if (validatedCredential is not null)
{
AuthenticatorResponse registrationResponse = await validatedCredential.GetResponseAsync();
if (registrationResponse is AuthenticatorAssertionResponse { } validation)
PublicKeyCredentialJSON authenticationResponse = await validatedCredential.ToJSONAsync();
if (authenticationResponse is AuthenticationResponseJSON { } authentication)
{
IJSObjectReference rawBuffer = await validation.GetSignatureAsync();
IJSObjectReference uint8ArrayFromBuffer = await (await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./_content/KristofferStrube.Blazor.WebIDL/KristofferStrube.Blazor.WebIDL.js")).InvokeAsync<IJSObjectReference>("constructUint8Array", rawBuffer);
Uint8Array uint8Array = await Uint8Array.CreateAsync(JSRuntime, uint8ArrayFromBuffer);
signature = await uint8Array.GetByteArrayAsync();
validated = await WebAuthenticationClient.Validate("bob", authentication);
}
}


errorMessage = null;
}
catch (DOMException exception)
{
errorMessage = $"{exception.Name}: \"{exception.Message}\"";
validatedCredential = null;
validated = false;
}

successfulGettingCredential = validatedCredential is not null;
}

}

0 comments on commit 2109638

Please sign in to comment.