-
Notifications
You must be signed in to change notification settings - Fork 21
/
REST.Authenticator.EnhancedOAuth.pas
212 lines (178 loc) · 6.29 KB
/
REST.Authenticator.EnhancedOAuth.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
unit REST.Authenticator.EnhancedOAuth;
interface
uses
System.SysUtils
, REST.Authenticator.OAuth
;
type
TEnhancedOAuth2Authenticator = class (TOAuth2Authenticator)
private
procedure RequestAccessToken;
public
IDToken : string;
procedure ChangeAuthCodeToAccesToken;
procedure RefreshAccessTokenIfRequired;
function AuthorizationRequestURI: string;
end;
implementation
uses
System.NetEncoding
, System.Net.URLClient
, System.DateUtils
, Dialogs
, IdSASL.Oauth.XOAUTH2
, IdSASL.Oauth.OAuth2Bearer
, REST.Client
, REST.Consts
, REST.Types
;
const
SClientIDNeeded = 'An ClientID is needed before a token can be requested';
SRefreshTokenNeeded = 'An Refresh Token is needed before an Access Token can be requested';
function TEnhancedOAuth2Authenticator.AuthorizationRequestURI: string;
var
uri : TURI;
begin
uri := TURI.Create(AuthorizationEndpoint);
uri.AddParameter('response_type', OAuth2ResponseTypeToString(ResponseType));
if ClientID <> '' then
uri.AddParameter('client_id', ClientID);
if RedirectionEndpoint <> '' then
uri.AddParameter('redirect_uri', RedirectionEndpoint);
if Scope <> '' then
uri.AddParameter('scope', Scope);
if LocalState <> '' then
uri.AddParameter('state', LocalState);
Result := uri.ToString;
end;
procedure TEnhancedOAuth2Authenticator.RefreshAccessTokenIfRequired;
begin
if AccessTokenExpiry < now then
begin
RequestAccessToken;
end;
end;
procedure TEnhancedOAuth2Authenticator.RequestAccessToken;
var
LClient: TRestClient;
LRequest: TRESTRequest;
paramBody: TRESTRequestParameter;
LToken: string;
LIntValue: int64;
url : TURI;
begin
// we do need an clientid here, because we want
// to send it to the servce and exchange the code into an
// access-token.
if ClientID = '' then
raise EOAuth2Exception.Create(SClientIDNeeded);
if RefreshToken = '' then
raise EOAuth2Exception.Create(SRefreshTokenNeeded);
LClient := TRestClient.Create(AccessTokenEndpoint);
try
LRequest := TRESTRequest.Create(LClient); // The LClient now "owns" the Request and will free it.
LRequest.Method := TRESTRequestMethod.rmPOST;
url := TURI.Create('http://localhost');
url.AddParameter('grant_type', 'refresh_token');
url.AddParameter('refresh_token', RefreshToken);
url.AddParameter('client_id', ClientID);
if not ClientSecret.IsEmpty then
url.AddParameter('client_secret', ClientSecret);
paramBody := LRequest.Params.AddItem;
paramBody.Value := url.Query;
paramBody.Kind := pkREQUESTBODY;
paramBody.Options := [poDoNotEncode];
paramBody.ContentType := TRESTContentType.ctAPPLICATION_X_WWW_FORM_URLENCODED;
LRequest.Execute;
if LRequest.Response.GetSimpleValue('access_token', LToken) then
AccessToken := LToken;
if LRequest.Response.GetSimpleValue('refresh_token', LToken) then
RefreshToken := LToken;
if LRequest.Response.GetSimpleValue('id_token', LToken) then
IDToken := LToken;
// detect token-type. this is important for how using it later
if LRequest.Response.GetSimpleValue('token_type', LToken) then
TokenType := OAuth2TokenTypeFromString(LToken);
// if provided by the service, the field "expires_in" contains
// the number of seconds an access-token will be valid
if LRequest.Response.GetSimpleValue('expires_in', LToken) then
begin
LIntValue := StrToIntdef(LToken, -1);
if (LIntValue > -1) then
AccessTokenExpiry := IncSecond(Now, LIntValue)
else
AccessTokenExpiry := 0.0;
end;
// an authentication-code may only be used once.
// if we succeeded here and got an access-token, then
// we do clear the auth-code as is is not valid anymore
// and also not needed anymore.
if (AccessToken <> '') then
begin
AuthCode := '';
end;
finally
LClient.DisposeOf;
end;
end;
// This function is basically a copy of the ancestor... but is need so we can also get the id_token value.
procedure TEnhancedOAuth2Authenticator.ChangeAuthCodeToAccesToken;
var
LClient: TRestClient;
LRequest: TRESTRequest;
paramBody : TRESTRequestParameter;
LToken: string;
LIntValue: int64;
url : TURI;
begin
// we do need an authorization-code here, because we want
// to send it to the servce and exchange the code into an
// access-token.
if AuthCode = '' then
raise EOAuth2Exception.Create(SAuthorizationCodeNeeded);
LClient := TRestClient.Create(AccessTokenEndpoint);
try
LRequest := TRESTRequest.Create(LClient); // The LClient now "owns" the Request and will free it.
LRequest.Method := TRESTRequestMethod.rmPOST;
url := TURI.Create('http://localhost');
url.AddParameter('grant_type', 'authorization_code');
url.AddParameter('code', AuthCode);
url.AddParameter('client_id', ClientID);
url.AddParameter('client_secret', ClientSecret);
url.AddParameter('redirect_uri', RedirectionEndpoint);
paramBody := LRequest.Params.AddItem;
paramBody.Value := url.Query;
paramBody.Kind := pkREQUESTBODY;
paramBody.Options := [poDoNotEncode];
paramBody.ContentType := TRESTContentType.ctAPPLICATION_X_WWW_FORM_URLENCODED;
LRequest.Execute;
if LRequest.Response.GetSimpleValue('access_token', LToken) then
AccessToken := LToken;
if LRequest.Response.GetSimpleValue('refresh_token', LToken) then
RefreshToken := LToken;
if LRequest.Response.GetSimpleValue('id_token', LToken) then
IDToken := LToken;
// detect token-type. this is important for how using it later
if LRequest.Response.GetSimpleValue('token_type', LToken) then
TokenType := OAuth2TokenTypeFromString(LToken);
// if provided by the service, the field "expires_in" contains
// the number of seconds an access-token will be valid
if LRequest.Response.GetSimpleValue('expires_in', LToken) then
begin
LIntValue := StrToIntdef(LToken, -1);
if (LIntValue > -1) then
AccessTokenExpiry := IncSecond(Now, LIntValue)
else
AccessTokenExpiry := 0.0;
end;
// an authentication-code may only be used once.
// if we succeeded here and got an access-token, then
// we do clear the auth-code as is is not valid anymore
// and also not needed anymore.
if (AccessToken <> '') then
AuthCode := '';
finally
LClient.DisposeOf;
end;
end;
end.