sgcIndy XOAuth2 Delphi

· 컴포넌트

sgcIndy 2024.5.0부터 XOAuth2 인증 메커니즘이 지원돼요. SASL XOAUTH2 메커니즘은 IMAP AUTHENTICATE, POP AUTH, SMTP AUTH 명령에 사용해요. 이 메커니즘을 사용하면 예를 들어 Gmail 계정 인증에 OAuth 2.0 액세스 토큰을 사용할 수 있어요.

TIdSASLXOAuth2

TIdSASLXOAuth2에는 권한 부여 전에 호출되는 OnAuthenticate 이벤트가 있어요. 이 이벤트에는 두 가지 매개변수가 있어요:


TIdSMTP 컴포넌트를 사용해 이메일을 보내려면 TIdSASLXOAuth2 컴포넌트를 새로운 SASLMechanism으로 추가하면 돼요.
xOAuth2 := TIdSASLXOAUTH2.Create(nil);
smtp := TIdSMTP.Create(nil);
...
smtp.AuthType := satSASL;
smtp.SASLMechanisms.Clear;
smtp.SASLMechanisms.Add.SASL := xoauth2; 

SMTP 및 XOAuth2 컴포넌트를 설정한 후 SMTP 컴포넌트를 사용해 이메일을 보내면 권한 부여가 필요할 때 OnAuthenticate 이벤트가 호출돼요. 여기에서 Username과 Access Token을 설정하면 돼요.

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

OAuth2 클라이언트

OAuth2 액세스 토큰은 sgcWebSockets 라이브러리의 TsgcHTTP_OAuth2_Client를 사용해 얻을 수 있어요.

아래에서 Google 사용자 계정에서 OAuth2 액세스 토큰을 얻기 위해 OAuth2 클라이언트를 설정하는 예제를 확인할 수 있어요.

  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; 

Delphi XOAuth2 데모

다음 데모는 sgcWebSockets 라이브러리의 OAuth2 클라이언트와 XOAuth2 컴포넌트를 함께 사용해 SMTP 프로토콜로 이메일을 보내는 방법을 보여줘요. XOAuth2 탭을 선택해 이 인증 방식을 사용하고 아래 필드를 입력하세요: 

  1. Username
  2. OAuth2 Client Id
  3. OAuth2 Client Secret
  4. Address to send the email
});