Autorização com PassKeys

· Recursos

WebAuthn (Web Autenticação) is um W3C standard that enables secure, passwordless, e phishing-resistant autenticação using public-key cryptography. It's widely used com passkeys para improve security e user experience. No entanto, authenticating users com WebAuthn is just o primeiro passo — after bem-sucedido autenticação, you often precisa authorize their actions across multiple API endpoints.

Neste artigo, we'll cover como:

1. Entendendo o Fluxo de Autenticação WebAuthn

WebAuthn revolves around public-key cryptography e credentials stored securely em o cliente (e.g., passkeys no browser ou device). The autenticação flow generally involves these steps:

Passo 1: Initiate Autenticação Passo 2: Client-Side Credential Assertion Passo 3: Server-Side Verification

At this point, you have confirmed who o usuário is, but you still need um way para authorize access para your APIs. 

2. Retornando um Token Bearer após sucesso no WebAuthn

If you want that after um bem-sucedido autenticação o servidor sends um token Bearer that será usado para abrir um novo websocket ou HTTP conexão, pass o parâmetro token = true. Exemplo:

{
"username": "alice@example.com", "token": true
}

After um bem-sucedido Autenticação, o servidor will send um response like this:

{
"verified": "ok",
  "authentication": {
    "token": "C760C1C39E3D4E829693A13F18F5CFDE537B516336FC48F7BAB0276176F9E6DE"
  }
}


The event OnWebAuthnUnauthorized is chamado when um request is not authorized e será disconnected, aqui você pode configure which endpoints require WebAuthn Autenticação e which not.

Why Use um Token Bearer?

3. Usando o Token Bearer para Autorização de API

Once you have um novo token, just send um autorização header com isto token Bearer. Você pode usar o CustomHeaders property do TsgcHTTP1Client para configure o Token Bearer. Exemplo:

procedure GetHTTPRequest(const aURL: string; const aToken: string): string;
var
  oHTTP: TsgcHTTP1Client;
begin
  oHTTP := TsgcHTTP1Client.Create(nil);
  Try
    oHTTP.Request.CustomHeaders.AddValue('Authorization', 'Bearer ' + aToken);
    result := oHTTP.Get(aURL);
  Finally
    oHTTP.Free;
  End;
end; 

4. Visão Geral do Fluxo Completo

Aqui's o completo high-level sequence: