sgcIndy XOAuth2 Delphi

· Componenti

Da sgcIndy 2024.5.0 è supportato il meccanismo di autenticazione XOAuth2. Il meccanismo SASL XOAUTH2 è utilizzato con i comandi IMAP AUTHENTICATE, POP AUTH e SMTP AUTH. Questo meccanismo consente l'uso di Access Token OAuth 2.0 per autenticarsi, ad esempio, a un account Gmail di un utente.

TIdSASLXOAuth2

TIdSASLXOAuth2 ha l'evento OnAuthenticate che viene chiamato prima dell'autorizzazione. L'evento ha 2 parametri:


Se vuoi inviare un'email usando il componente TIdSMTP, aggiungi il componente TIdSASLXOAuth2 come nuovo SASLMechanism.
xOAuth2 := TIdSASLXOAUTH2.Create(nil);
smtp := TIdSMTP.Create(nil);
...
smtp.AuthType := satSASL;
smtp.SASLMechanisms.Clear;
smtp.SASLMechanisms.Add.SASL := xoauth2; 

Dopo aver configurato i componenti SMTP e XOAuth2, invia un'email tramite il componente SMTP: quando è richiesta l'autorizzazione viene chiamato l'evento OnAuthenticate. Imposta qui Username e Access Token.

procedure OnXOAuth2Authenticate(Sender: TObject; var Username,
    Token: string);
begin
  Token := 'OAuth2 Access Token';
  Username := 'your mail account';
end; 

Client OAuth2

L'Access Token OAuth2 può essere ottenuto usando TsgcHTTP_OAuth2_Client della libreria sgcWebSockets.

Qui sotto trovi un esempio di come configurare il client OAuth2 per ottenere un Access Token OAuth2 dal tuo account utente Google.

  OAuth2 := TsgcHTTP_OAuth2_Client.Create(nil);
  OAuth2.OnAfterAccessToken := OnOAuth2AfterAccessTokenEvent;
  OAuth2.OAuth2Options.GrantType := auth2CodePKCE;
  OAuth2.LocalServerOptions.IP := '127.0.0.1';
  OAuth2.LocalServerOptions.Port := 0;
  OAuth2.AuthorizationServerOptions.AuthURL := 'https://accounts.google.com/o/oauth2/auth';
  OAuth2.AuthorizationServerOptions.TokenURL := 'https://accounts.google.com/o/oauth2/token';
  OAuth2.AuthorizationServerOptions.Scope.Text := 'https://mail.google.com/';
  OAuth2.OAuth2Options.ClientId := '<your oauth2 client id>';
  OAuth2.OAuth2Options.ClientSecret := '<your oauth2 client secret>';
  OAuth2.Start;
procedure OnOAuth2AfterAccessTokenEvent(Sender: TObject; const
    Access_Token, Token_Type, Expires_In, Refresh_Token, Scope, RawParams:
    String; var Handled: Boolean);
begin
  ShowMessage(Access_Token);
end; 

Demo XOAuth2 Delphi

Qui sotto trovi una demo che mostra il componente XOAuth2 con il client OAuth2 della libreria sgcWebSockets per inviare un'email tramite il protocollo SMTP. Seleziona la scheda XOAuth2 per usare questo tipo di autenticazione e compila i campi: 

  1. Username
  2. OAuth2 Client Id
  3. OAuth2 Client Secret
  4. Indirizzo a cui inviare l'email
});