-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathuOAuth2Client.pas
430 lines (392 loc) · 12.8 KB
/
uOAuth2Client.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
{
Simple OAuth2 client
(C) 2016, Stefan Ascher
}
unit uOAuth2Client;
{$IFDEF FPC}
{$mode objfpc}
{$H+}
{$ENDIF}
{
Tested with https://github.com/bshaffer/oauth2-server-php
Limitations:
* Only the password GrantType (i.e. user credentials) is supported.
* Server must return JSON
* Refresh token must be returned with the access token
}
interface
uses
SysUtils, Classes, uOAuth2Token, uOAuth2HttpClient, uOAuth2Config;
type
TOAuth2GrantType = (
gtPassword, // Username, Password
gtAuthCode, // AuthCode
gtClientCredentials // ClientId, ClientSecret
);
TAccessTokenLoc = (atlUnknown, atlHeader, atlFormfield);
TOAuth2Client = class
private
FAccessTokenLoc: TAccessTokenLoc;
FUserName: string;
FPassWord: string;
FClientId: string;
FClientSecret: string;
FSite: string;
FScope: string;
FRedirectUri: string;
FAuthCode: string;
FHttpClient: TOAuth2HttpClient;
FAccessToken: TOAuth2Token;
FGrantType: TOAuth2GrantType;
FConfig: TOAuth2Config;
procedure RefreshAccessToken(AToken: TOAuth2Token);
function GetAccessToken: TOAuth2Token;
procedure SetAccessToken(Value: TOAuth2Token);
procedure SetUserName(Value: string);
procedure SetPassWord(Value: string);
procedure SetClientId(Value: string);
procedure SetClientSecret(Value: string);
procedure SetSite(Value: string);
procedure SetGrantType(Value: TOAuth2GrantType);
public
constructor Create(AClient: TOAuth2HttpClient); overload;
constructor Create(AConfig: TOAuth2Config; AClient: TOAuth2HttpClient); overload;
destructor Destroy; override;
function Get(const APath: string): TOAuth2Response;
function Post(const APath: string; AFormFields: TStringList): TOAuth2Response;
procedure InvalidateToken;
property UserName: string read FUserName write SetUserName;
property PassWord: string read FPassWord write SetPassWord;
property ClientId: string read FClientId write SetClientId;
property ClientSecret: string read FClientSecret write SetClientSecret;
property Site: string read FSite write SetSite;
property GrantType: TOAuth2GrantType read FGrantType write SetGrantType default gtPassword;
property AccessToken: TOAuth2Token read FAccessToken write SetAccessToken;
property RedirectUri: string read FRedirectUri write FRedirectUri;
// for GrantType = gtAuthCode
property AuthCode: string read FAuthCode write FAuthCode;
property Config: TOAuth2Config read FConfig write FConfig;
end;
implementation
uses
uOAuth2Consts, uOAuth2Tools, uJson;
const
GRANT_TYPE_STRINGS: array[TOAuth2GrantType] of string = (
'password',
'authorization_code',
'client_credentials'
);
constructor TOAuth2Client.Create(AClient: TOAuth2HttpClient);
begin
inherited Create;
FHttpClient := AClient;
FAccessToken := nil;
FConfig := DEF_OATUH2_CONFIG;
FGrantType := gtPassword;
FAccessTokenLoc := atlUnknown;
end;
constructor TOAuth2Client.Create(AConfig: TOAuth2Config; AClient: TOAuth2HttpClient);
begin
inherited Create;
FHttpClient := AClient;
FAccessToken := nil;
FConfig := AConfig;
FGrantType := gtPassword;
FAccessTokenLoc := atlUnknown;
end;
destructor TOAuth2Client.Destroy;
begin
if Assigned(FAccessToken) then
FAccessToken.Free;
inherited;
end;
procedure TOAuth2Client.InvalidateToken;
begin
if Assigned(FAccessToken) then
FreeAndNil(FAccessToken);
end;
procedure TOAuth2Client.SetAccessToken(Value: TOAuth2Token);
begin
if FAccessToken <> Value then begin
if Assigned(FAccessToken) then
FAccessToken.Free;
FAccessToken := Value;
end;
end;
procedure TOAuth2Client.SetUserName(Value: string);
begin
if FUserName <> Value then begin
FUserName := Value;
InvalidateToken;
end;
end;
procedure TOAuth2Client.SetPassWord(Value: string);
begin
if FPassWord <> Value then begin
FPassWord := Value;
InvalidateToken;
end;
end;
procedure TOAuth2Client.SetClientId(Value: string);
begin
if FClientId <> Value then begin
FClientId := Value;
InvalidateToken;
end;
end;
procedure TOAuth2Client.SetClientSecret(Value: string);
begin
if FClientSecret <> Value then begin
FClientSecret := Value;
InvalidateToken;
end;
end;
procedure TOAuth2Client.SetSite(Value: string);
begin
if FSite <> Value then begin
FSite := Value;
FAccessTokenLoc := atlUnknown;
InvalidateToken;
end;
end;
procedure TOAuth2Client.SetGrantType(Value: TOAuth2GrantType);
begin
if FGrantType <> Value then begin
FGrantType := Value;
InvalidateToken;
end;
end;
function TOAuth2Client.GetAccessToken: TOAuth2Token;
var
response: TOAuth2Response;
url: string;
json: TJson;
val: TJsonValue;
begin
FHttpClient.ClearHeader;
FHttpClient.ClearFormFields;
FHttpClient.AddFormField(OAUTH2_GRANT_TYPE, GRANT_TYPE_STRINGS[FGrantType]);
if (FGrantType = gtPassword) then begin
FHttpClient.AddFormField(OAUTH2_USERNAME, FUserName);
FHttpClient.AddFormField(OAUTH2_PASSWORD, FPassWord);
end else if (FGrantType = gtAuthCode) then begin
if FAuthCode = '' then
raise Exception.Create('Missing auth code for authorization_code grant type');
FHttpClient.AddFormField(OAUTH2_CODE, FAuthCode);
FHttpClient.AddFormField(OAUTH2_REDIRECT_URI, FRedirectUri);
end;
if FClientId <> '' then
FHttpClient.AddFormField(OAUTH2_CLIENT_ID, FClientId)
else if FGrantType = gtClientCredentials then
raise Exception.Create('Missing Client ID for client credentials grant type');
if FClientSecret <> '' then
FHttpClient.AddFormField(OAUTH2_CLIENT_SECRET, FClientSecret)
else if FGrantType = gtClientCredentials then
raise Exception.Create('Missing Client Secret for client credentials grant type');
if FScope <> '' then
FHttpClient.AddFormField(OAUTH2_SCOPE, FScope);
if Pos('://', FConfig.TokenEndPoint) = 0 then
url := FSite + FConfig.TokenEndPoint
else
// Token endpoint seems to be an abolute URL
url := FConfig.TokenEndPoint;
response := FHttpClient.Post(url);
if response.Code <> HTTP_OK then begin
raise Exception.CreateFmt('Server returned %d: %s', [response.Code, response.Body]);
end;
if not IsJson(response.ContentType) then
raise Exception.CreateFmt('JSON required, got %s', [response.ContentType]);
Result := TOAuth2Token.Create;
json := TJson.Create;
try
json.Parse(response.Body);
val := json.GetValue(OATUH2_ACCESS_TOKEN);
if val.Kind = JVKString then begin
Result.AccessToken := string(json.Output.Strings[val.Index]);
end;
val := json.GetValue(OAUTH2_REFRESH_TOKEN);
if val.Kind = JVKString then begin
Result.RefreshToken := string(json.Output.Strings[val.Index]);
end;
val := json.GetValue(OAUTH2_EXPIRES_IN);
if val.Kind = JVKNumber then begin
Result.ExpiresIn := Trunc(json.Output.Numbers[val.Index]);
end;
val := json.GetValue(OAUTH2_TOKEN_TYPE);
if val.Kind = JVKString then begin
Result.TokenType := string(json.Output.Strings[val.Index]);
end;
val := json.GetValue(OAUTH2_SCOPE);
if val.Kind = JVKString then begin
FScope := string(json.Output.Strings[val.Index]);
end;
finally
json.Free;
end;
end;
procedure TOAuth2Client.RefreshAccessToken(AToken: TOAuth2Token);
var
url: string;
response: TOAuth2Response;
json: TJson;
val: TJsonValue;
begin
if AToken.RefreshToken = '' then
raise Exception.Create('No Refresh token');
FHttpClient.ClearHeader;
FHttpClient.ClearFormFields;
FHttpClient.AddFormField(OAUTH2_GRANT_TYPE, OAUTH2_REFRESH_TOKEN);
FHttpClient.AddFormField(OAUTH2_REFRESH_TOKEN, AToken.RefreshToken);
if FClientId <> '' then
FHttpClient.AddFormField(OAUTH2_CLIENT_ID, FClientId);
if FClientSecret <> '' then
FHttpClient.AddFormField(OAUTH2_CLIENT_SECRET, FClientSecret);
if Pos('://', FConfig.TokenEndPoint) = 0 then
url := FSite + FConfig.TokenEndPoint
else
// Token endpoint seems to be an abolute URL
url := FConfig.TokenEndPoint;
response := FHttpClient.Post(url);
if response.Code <> HTTP_OK then begin
raise Exception.CreateFmt('Server returned %d: %s', [response.Code, response.Body]);
end;
if not IsJson(response.ContentType) then
raise Exception.CreateFmt('JSON required, got %s', [response.ContentType]);
json := TJson.Create;
try
json.Parse(response.Body);
val := json.GetValue(OATUH2_ACCESS_TOKEN);
if val.Kind = JVKString then begin
AToken.AccessToken := string(json.Output.Strings[val.Index]);
end;
val := json.GetValue(OAUTH2_REFRESH_TOKEN);
if val.Kind = JVKString then begin
AToken.RefreshToken := string(json.Output.Strings[val.Index]);
end;
val := json.GetValue(OAUTH2_EXPIRES_IN);
if val.Kind = JVKNumber then begin
AToken.ExpiresIn := Trunc(json.Output.Numbers[val.Index]);
end;
val := json.GetValue(OAUTH2_TOKEN_TYPE);
if val.Kind = JVKString then begin
AToken.TokenType := string(json.Output.Strings[val.Index]);
end;
val := json.GetValue(OAUTH2_MACKEY);
if val.Kind = JVKString then begin
AToken.MacKey := string(json.Output.Strings[val.Index]);
end;
val := json.GetValue(OAUTH2_MAXALGORITHM);
if val.Kind = JVKString then begin
AToken.MacAlgorithm := string(json.Output.Strings[val.Index]);
end;
val := json.GetValue(OAUTH2_SCOPE);
if val.Kind = JVKString then begin
FScope := string(json.Output.Strings[val.Index]);
end;
finally
json.Free;
end;
end;
function TOAuth2Client.Get(const APath: string): TOAuth2Response;
var
url: string;
urlp: TUrlParts;
begin
if not Assigned(FAccessToken) then
FAccessToken := GetAccessToken;
if FAccessToken.IsExpired then begin
if FAccessToken.RefreshToken <> '' then
RefreshAccessToken(FAccessToken)
else begin
// no refreh token -> get a new access token
FAccessToken.Free;
FAccessToken := GetAccessToken;
end;
end;
FHttpClient.ClearHeader;
FHttpClient.ClearFormFields;
url := FSite + APath;
urlp := ParseUrl(url);
Result.Code := 0;
case FAccessTokenLoc of
atlUnknown:
begin
FHttpClient.AddHeader(OAUTH2_AUTHORIZATION, FAccessToken.GetAuthHeader('GET', urlp));
Result := FHttpClient.Get(url);
if IsAccessDenied(Result.Code) then begin
// Maybe passing access token as formfield helps
FHttpClient.RemoveHeader(OAUTH2_AUTHORIZATION);
FHttpClient.AddFormField(OATUH2_ACCESS_TOKEN, FAccessToken.AccessToken);
Result := FHttpClient.Get(url);
if not IsAccessDenied(Result.Code) then
FAccessTokenLoc := atlFormfield;
end else
FAccessTokenLoc := atlHeader;
end;
atlHeader:
begin
FHttpClient.AddHeader(OAUTH2_AUTHORIZATION, FAccessToken.GetAuthHeader('GET', urlp));
Result := FHttpClient.Get(url);
end;
atlFormfield:
begin
FHttpClient.AddFormField(OATUH2_ACCESS_TOKEN, FAccessToken.AccessToken);
Result := FHttpClient.Get(url);
end;
end;
if Result.Code <> HTTP_OK then begin
raise Exception.CreateFmt('Server returned %d: %s', [Result.Code, Result.Body]);
end;
end;
function TOAuth2Client.Post(const APath: string; AFormFields: TStringList): TOAuth2Response;
var
url: string;
urlp: TUrlParts;
i: integer;
key, value: string;
begin
if not Assigned(FAccessToken) then
FAccessToken := GetAccessToken;
if FAccessToken.IsExpired then
RefreshAccessToken(FAccessToken);
FHttpClient.ClearHeader;
FHttpClient.ClearFormFields;
for i := 0 to AFormFields.Count - 1 do begin
key := AFormFields.Names[i];
value := AFormFields.Values[key];
FHttpClient.AddFormField(key, value);
end;
url := FSite + APath;
urlp := ParseUrl(url);
Result.Code := 0;
case FAccessTokenLoc of
atlUnknown:
begin
FHttpClient.AddHeader(OAUTH2_AUTHORIZATION, FAccessToken.GetAuthHeader('GET', urlp));
Result := FHttpClient.Post(url);
if IsAccessDenied(Result.Code) then begin
// Maybe passing access token as formfield helps
FHttpClient.RemoveHeader(OAUTH2_AUTHORIZATION);
FHttpClient.AddFormField(OATUH2_ACCESS_TOKEN, FAccessToken.AccessToken);
Result := FHttpClient.Post(url);
if not IsAccessDenied(Result.Code) then
FAccessTokenLoc := atlFormfield;
end else
FAccessTokenLoc := atlHeader;
end;
atlHeader:
begin
FHttpClient.AddHeader(OAUTH2_AUTHORIZATION, FAccessToken.GetAuthHeader('GET', urlp));
Result := FHttpClient.Post(url);
end;
atlFormfield:
begin
FHttpClient.AddFormField(OATUH2_ACCESS_TOKEN, FAccessToken.AccessToken);
Result := FHttpClient.Post(url);
end;
end;
if Result.Code <> HTTP_OK then begin
raise Exception.CreateFmt('Server returned %d: %s', [Result.Code, Result.Body]);
end;
end;
end.