프로젝트에서 OAuth2.0 적용을 위해 인디 컴포넌트 만으로 인증 프로세스를 구현해보았습니다.
- OAuth2.0 공식 문서 참조.
- 로그인과 같은 사용자인증을 위한 Redirect 등의 기능은 제외.
1. 토큰 발급받기
procedure GetToken;
var
http: TIdHTTP;
sResponse: string;
objTokenInfo: TJSONObject;
begin
http := TIdHTTP.Create(nil);
http.AllowCookies := True; http.HandleRedirects := True; http.HTTPOptions := [hoForceEncodeParams];
http.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(http);
try
sResponse := http.Get(
FOAuthURL +
'?client_id=' + FClient_ID +
'&client_secret=' + FSecurity_Code + '&grant_type=' + FGrant_Type );
if (http.ResponseCode = 200) and (sResponse <> '') then
begin
FStart_TokenTick := GetTickCount;
objTokenInfo := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(sResponse), 0) as TJSONObject;
if objTokenInfo.TryGetValue<string>('access_token', FAccess_Token) then Memo1.Lines.Add('[access_token] ' + FAccess_Token);
if objTokenInfo.TryGetValue<string>('token_type', FToken_Type) then Memo1.Lines.Add('[token_type] ' + FToken_Type);
if objTokenInfo.TryGetValue<Integer>('expires_in', FExpires_In) then Memo1.Lines.Add('[expires_in] ' + FExpires_In);
end;
finally
http.IOHandler.Free;
http.Free;
end;
end;
2. 발급받은 토큰으로 인증하기
procedure SendRequest;
var
http: TIdHTTP;
RequestStream: TStringStream; ResponseStream: TStringStream;
begin
http := TIdHTTP.Create(nil);
http.AllowCookies := True; http.HandleRedirects := True; http.HTTPOptions := [hoForceEncodeParams];
http.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(http);
RequestStream := TStringStream.Create('', TEncoding.UTF8); ResponseStream := TStringStream.Create('', TEncoding.UTF8);
..
try
..
//인증만료시간 체크하여 토큰 발급받기
if (GetTickCount - FStart_TokenTick) >= FExpires_In * 1000) then
GetToken;
..
http.Request.CustomHeaders.AddValue('Authorization', FToken_Type + ' ' + FAccess_Token);
http.Post(FURL, RequestStream, ResponseStream);
..
finally
http.IOHandler.Free;
http.Free;
end;
end;