|
| 1 | +import { inject, Injectable } from '@angular/core'; |
| 2 | +import { environment } from '../../../../environments/environment'; |
| 3 | +import { KeycloakService } from './keycloak.service'; |
| 4 | + |
| 5 | +/** |
| 6 | + * In-app WebAuthn via Keycloak realm extension (same flow as ba-test-keycloak {@code public/app.js}): |
| 7 | + * register: {@code /passkey/challenge} + {@code /passkey/save}; sign-in: {@code /passkey/get-credential-id} + {@code /passkey/authenticate}. |
| 8 | + */ |
| 9 | +@Injectable({ providedIn: 'root' }) |
| 10 | +export class PasskeyExtensionService { |
| 11 | + private readonly keycloakService = inject(KeycloakService); |
| 12 | + |
| 13 | + private passkeyBaseUrl(): string { |
| 14 | + const base = environment.keycloak.url.replace(/\/$/, ''); |
| 15 | + const realm = encodeURIComponent(environment.keycloak.realm); |
| 16 | + return `${base}/realms/${realm}/passkey`; |
| 17 | + } |
| 18 | + |
| 19 | + private getUrl(path: string): string { |
| 20 | + const p = path.replace(/^\/+/, ''); |
| 21 | + return `${this.passkeyBaseUrl()}/${p}`; |
| 22 | + } |
| 23 | + |
| 24 | + private base64UrlToUint8Array(value: string): Uint8Array { |
| 25 | + const base64 = value.replace(/-/g, '+').replace(/_/g, '/'); |
| 26 | + const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4); |
| 27 | + return Uint8Array.from(atob(padded), (c) => c.charCodeAt(0)); |
| 28 | + } |
| 29 | + |
| 30 | + private bufferToBase64Url(buffer: ArrayBuffer): string { |
| 31 | + const bytes = new Uint8Array(buffer); |
| 32 | + let binary = ''; |
| 33 | + for (let i = 0; i < bytes.length; i += 1) { |
| 34 | + binary += String.fromCharCode(bytes[i]); |
| 35 | + } |
| 36 | + return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, ''); |
| 37 | + } |
| 38 | + |
| 39 | + private async readJsonBody<T>(response: Response): Promise<T | undefined> { |
| 40 | + const contentType = response.headers.get('content-type') ?? ''; |
| 41 | + if (!contentType.toLowerCase().includes('application/json')) { |
| 42 | + return undefined; |
| 43 | + } |
| 44 | + try { |
| 45 | + return (await response.json()) as T; |
| 46 | + } catch { |
| 47 | + return undefined; |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + /** |
| 52 | + * Register a new passkey for the current user (must already be logged in). |
| 53 | + */ |
| 54 | + async registerPasskeyInBrowser(): Promise<void> { |
| 55 | + const kc = this.keycloakService.keycloak; |
| 56 | + if (!kc.authenticated || !kc.token) { |
| 57 | + throw new Error('You must be signed in to register a passkey.'); |
| 58 | + } |
| 59 | + |
| 60 | + await kc.updateToken(60); |
| 61 | + const token = kc.token; |
| 62 | + if (!token) { |
| 63 | + throw new Error('No access token available.'); |
| 64 | + } |
| 65 | + |
| 66 | + const parsed = kc.tokenParsed as Record<string, unknown> | undefined; |
| 67 | + const accountId = String(parsed?.['sub'] ?? parsed?.['preferred_username'] ?? ''); |
| 68 | + const accountName = String(parsed?.['preferred_username'] ?? parsed?.['email'] ?? ''); |
| 69 | + const displayName = String(parsed?.['name'] ?? ([parsed?.['given_name'], parsed?.['family_name']].filter(Boolean).join(' ') || accountName || 'User')); |
| 70 | + |
| 71 | + if (!accountId || !accountName) { |
| 72 | + throw new Error('Missing user identity in token for passkey registration.'); |
| 73 | + } |
| 74 | + |
| 75 | + const challengeRes = await fetch(this.getUrl('challenge'), { credentials: 'include' }); |
| 76 | + if (!challengeRes.ok) { |
| 77 | + throw new Error(`Failed to get WebAuthn challenge (${challengeRes.status})`); |
| 78 | + } |
| 79 | + const { challenge } = (await challengeRes.json()) as { challenge: string }; |
| 80 | + if (!challenge) { |
| 81 | + throw new Error('Invalid challenge response from Keycloak'); |
| 82 | + } |
| 83 | + |
| 84 | + const userIdBytes = new TextEncoder().encode(accountId).slice(0, 64); |
| 85 | + |
| 86 | + const credential = (await navigator.credentials.create({ |
| 87 | + publicKey: { |
| 88 | + challenge: this.base64UrlToUint8Array(challenge) as BufferSource, |
| 89 | + rp: { name: 'Module Management', id: window.location.hostname }, |
| 90 | + user: { id: userIdBytes, name: accountName, displayName }, |
| 91 | + pubKeyCredParams: [{ type: 'public-key', alg: -7 }], |
| 92 | + authenticatorSelection: { userVerification: 'preferred', residentKey: 'required' }, |
| 93 | + attestation: 'none' |
| 94 | + } |
| 95 | + })) as PublicKeyCredential | null; |
| 96 | + |
| 97 | + if (!credential?.response) { |
| 98 | + throw new Error('Passkey creation was cancelled or failed.'); |
| 99 | + } |
| 100 | + |
| 101 | + const response = credential.response as AuthenticatorAttestationResponse; |
| 102 | + const savePayload = { |
| 103 | + credentialId: this.bufferToBase64Url(credential.rawId), |
| 104 | + rawId: this.bufferToBase64Url(credential.rawId), |
| 105 | + clientDataJSON: this.bufferToBase64Url(response.clientDataJSON), |
| 106 | + attestationObject: this.bufferToBase64Url(response.attestationObject), |
| 107 | + challenge |
| 108 | + }; |
| 109 | + |
| 110 | + const saveRes = await fetch(this.getUrl('save'), { |
| 111 | + method: 'POST', |
| 112 | + credentials: 'include', |
| 113 | + headers: { |
| 114 | + 'Content-Type': 'application/json', |
| 115 | + Authorization: `Bearer ${token}` |
| 116 | + }, |
| 117 | + body: JSON.stringify(savePayload) |
| 118 | + }); |
| 119 | + |
| 120 | + const saveText = await saveRes.text(); |
| 121 | + if (!saveRes.ok) { |
| 122 | + throw new Error(saveText || `Failed to store passkey (${saveRes.status})`); |
| 123 | + } |
| 124 | + |
| 125 | + await kc.updateToken(-1); |
| 126 | + } |
| 127 | + |
| 128 | + /** |
| 129 | + * Sign in with passkey only (no Keycloak UI redirect). |
| 130 | + * The extension endpoint sets the Keycloak login cookie; the SPA should then reload |
| 131 | + * and let keycloak-js initialize via check-sso. |
| 132 | + */ |
| 133 | + async signInWithPasskey(): Promise<void> { |
| 134 | + const optionsResponse = await fetch(this.getUrl('challenge'), { credentials: 'include' }); |
| 135 | + const res = await this.readJsonBody<{ challenge?: string; credentialId?: string; error?: string }>(optionsResponse); |
| 136 | + if (!optionsResponse.ok) { |
| 137 | + throw new Error(res?.error || `Failed to get passkey options (${optionsResponse.status})`); |
| 138 | + } |
| 139 | + if (!res?.challenge) { |
| 140 | + throw new Error('Invalid challenge response from server'); |
| 141 | + } |
| 142 | + |
| 143 | + const publicKey: PublicKeyCredentialRequestOptions = { |
| 144 | + challenge: this.base64UrlToUint8Array(res.challenge) as BufferSource, |
| 145 | + userVerification: 'preferred' |
| 146 | + }; |
| 147 | + if (res.credentialId) { |
| 148 | + publicKey.allowCredentials = [{ type: 'public-key', id: this.base64UrlToUint8Array(res.credentialId) as BufferSource }]; |
| 149 | + } |
| 150 | + |
| 151 | + const credential = (await navigator.credentials.get({ publicKey })) as PublicKeyCredential | null; |
| 152 | + if (!credential?.response) { |
| 153 | + throw new Error('Passkey sign-in was cancelled or failed.'); |
| 154 | + } |
| 155 | + |
| 156 | + const ar = credential.response as AuthenticatorAssertionResponse; |
| 157 | + const payload = { |
| 158 | + credentialId: this.bufferToBase64Url(credential.rawId), |
| 159 | + rawId: this.bufferToBase64Url(credential.rawId), |
| 160 | + clientDataJSON: this.bufferToBase64Url(ar.clientDataJSON), |
| 161 | + authenticatorData: this.bufferToBase64Url(ar.authenticatorData), |
| 162 | + signature: this.bufferToBase64Url(ar.signature), |
| 163 | + challenge: res.challenge |
| 164 | + }; |
| 165 | + |
| 166 | + const authRes = await fetch(this.getUrl('authenticate'), { |
| 167 | + method: 'POST', |
| 168 | + credentials: 'include', |
| 169 | + redirect: 'manual', |
| 170 | + headers: { 'Content-Type': 'application/json' }, |
| 171 | + body: JSON.stringify(payload) |
| 172 | + }); |
| 173 | + |
| 174 | + if (authRes.type === 'opaqueredirect') { |
| 175 | + return; |
| 176 | + } |
| 177 | + |
| 178 | + const authResult = await this.readJsonBody<{ error?: string }>(authRes); |
| 179 | + if (!authRes.ok) { |
| 180 | + throw new Error(authResult?.error || `Passkey authentication failed (${authRes.status})`); |
| 181 | + } |
| 182 | + } |
| 183 | +} |
0 commit comments