Source file oauth2_client.ml
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
open Lwt.Infix
open Cohttp_lwt_unix
module Uri = struct
include Uri
let to_yojson uri = `String (Uri.to_string uri)
let of_yojson = function
| `String s -> Ok (Uri.of_string s)
| _ -> Error "expected string for Uri.t"
end
type flow_type =
| AuthorizationCode
| ClientCredentials
| DeviceCode
| RefreshToken
type token_auth_method =
| Basic
| Body
let token_auth_method_to_yojson = function
| Basic -> `String "basic"
| Body -> `String "body"
let token_auth_method_of_yojson = function
| `String "basic" -> Ok Basic
| `String "body" -> Ok Body
| `String _ -> Ok Basic
| _ -> Error "expected `String for token_auth_method"
type pkce_style =
| No_Pkce
| Plain
| S256
let pkce_style_to_yojson = function
| No_Pkce -> `String ""
| Plain -> `String "plain"
| S256 -> `String "s256"
let pkce_style_of_yojson = function
| `String "plain" -> Ok Plain
| `String "s256" -> Ok S256
| `String _ -> Ok No_Pkce
| _ -> Error "expected `String for pkce_style"
type authorization_code_config = {
authorization_endpoint: Uri.t;
client_id: string;
client_secret: string option;
pkce: (pkce_style [@default No_Pkce]);
pkce_verifier: (string option [@default None]);
redirect_uri: Uri.t;
scope: string list;
token_auth_method: (token_auth_method [@default Basic]);
token_endpoint: Uri.t;
} [@@deriving yojson]
type client_credentials_config = {
client_id: string;
client_secret: string;
scope: string list;
token_auth_method: (token_auth_method [@default Basic]);
token_endpoint: Uri.t;
} [@@deriving yojson]
type device_code_config = {
client_id: string;
device_authorization_endpoint: Uri.t;
token_endpoint: Uri.t;
scope: string list;
} [@@deriving yojson]
type refresh_token_config = {
client_id: string;
client_secret: string;
token_endpoint: Uri.t;
refresh_token: string;
scope: string list option;
token_auth_method: (token_auth_method [@default Basic]);
} [@@deriving yojson]
type config =
| AuthorizationCodeConfig of authorization_code_config
| ClientCredentialsConfig of client_credentials_config
| DeviceCodeConfig of device_code_config
| RefreshTokenConfig of refresh_token_config
[@@deriving yojson]
type token_response = {
access_token: string;
token_type: string;
expires_in: (int option [@default None]);
refresh_token: (string option [@default None]);
scope: (string option [@default None]);
} [@@deriving yojson]
type token_error_code =
| Invalid_Request
| Invalid_Client
| Invalid_Grant
| Unauthorized_Client
| Unsupported_Grant_Type
| Invalid_Scope
| Invalid_Token
let token_error_code_to_yojson = function
| Invalid_Request -> `String "invalid_request"
| Invalid_Client -> `String "invalid_client"
| Invalid_Grant -> `String "invalid_grant"
| Unauthorized_Client -> `String "unauthorized_client"
| Unsupported_Grant_Type -> `String "unsupported_grant_type"
| Invalid_Scope -> `String "invalid_scope"
| Invalid_Token -> `String "invalid_token"
let token_error_code_of_yojson = function
| `String "invalid_request" -> Ok Invalid_Request
| `String "invalid_client" -> Ok Invalid_Client
| `String "invalid_grant" -> Ok Invalid_Grant
| `String "unauthorized_client" -> Ok Unauthorized_Client
| `String "unsupported_grant_type" -> Ok Unsupported_Grant_Type
| `String "invalid_scope" -> Ok Invalid_Scope
| `String "invalid_token" -> Ok Invalid_Token
| `String _ -> Ok Invalid_Request
| _ -> Error "expected string for error code"
type token_error = {
error: token_error_code;
error_description: string;
error_uri: (Uri.t option [@default None]);
} [@@deriving yojson]
type device_code_response = {
device_code: string;
user_code: string;
verification_uri: Uri.t;
verification_uri_complete: Uri.t option;
expires_in: int;
interval: int;
} [@@deriving yojson]
module DefaultInMemoryStorage = struct
type value = string * config
let ttl = 3600.0
end
module type OAUTH2_CLIENT =
sig
val get_authorization_url : config:config -> ((Uri.t * string * string), string) result
val exchange_code_for_token : string -> string -> (token_response, string) result Lwt.t
val get_client_credentials_token : config:config -> (token_response, string) result Lwt.t
val refresh_token : config:config -> (token_response, string) result Lwt.t
end
module OAuth2Client (Storage : Storage.STORAGE_UNIT with type value = (string * config)) : OAUTH2_CLIENT = struct
let get_authorization_url ~config =
match config with
| AuthorizationCodeConfig ac_config ->
let state = Utils.generate_state () in
let verifier = (match ac_config.pkce_verifier with
| Some verifier_str -> verifier_str
| None -> Utils.generate_code_verifier ()) in
let params = [
("response_type", "code");
("client_id", ac_config.client_id);
("redirect_uri", Uri.to_string ac_config.redirect_uri);
("scope", String.concat " " ac_config.scope);
("state", state);
] @ (
match ac_config.pkce with
| S256 -> [ ("code_challenge", Utils.generate_code_challenge verifier) ; ("code_challenge_method", "S256") ]
| Plain -> [ ("code_challenge", verifier) ; ("code_challenge_method", "plain") ]
| No_Pkce -> []
) in
Storage.update state ( verifier, config );
let url = Uri.add_query_params' ac_config.authorization_endpoint params in
Ok (url, state, verifier)
| _ -> Error "Authorization URL only available for Authorization Code flow"
let exchange_code_for_token state code =
match Storage.get state with
| Some ((verifier, stored_config), _expires) -> begin
Storage.remove state;
match stored_config with
| AuthorizationCodeConfig config -> begin
let params = (
match config.token_auth_method with
| Basic -> [
("grant_type", "authorization_code");
("client_id", config.client_id);
("code", code);
("redirect_uri", Uri.to_string config.redirect_uri);
]
| Body -> [
("grant_type", "authorization_code");
("client_id", config.client_id);
("code", code);
("redirect_uri", Uri.to_string config.redirect_uri);
] @ (
match config.client_secret with
| Some secret -> [
("client_secret", secret);
]
| None -> []
)
) @ (
match config.pkce with
| No_Pkce -> []
| _ -> [ ("code_verifier", verifier) ]
) in
let body = Utils.form_encode params in
let = (
match config.token_auth_method with
| Basic ->
Cohttp.Header.of_list ([
("Content-Type", "application/x-www-form-urlencoded") ;
] @ (
match config.client_secret with
| Some secret -> [
("Authorization", "Basic " ^ (Base64.encode_string (config.client_id ^ ":" ^ secret)))
]
| None -> []
))
| Body -> Cohttp.Header.init_with "Content-Type" "application/x-www-form-urlencoded"
) in
Client.post ~headers ~body config.token_endpoint
>>= fun (_, body) -> Cohttp_lwt.Body.to_string body
>>= fun body_str ->
let json = Yojson.Safe.from_string body_str in
match token_response_of_yojson json with
| Ok token -> begin
Lwt.return (Ok token)
end
| Error _ -> begin
match token_error_of_yojson json with
| Ok error -> begin
print_endline error.error_description;
Lwt.return (Error error.error_description)
end
| Error e -> begin
print_endline e;
Lwt.return (Error e)
end
end
end
| _ -> Lwt.return (Error "Code exchange only available for Authorization Code flow")
end
| None -> Lwt.return (Error "State value did not match a known session")
let get_client_credentials_token ~config =
match config with
| ClientCredentialsConfig cc_config -> begin
let params = (
match cc_config.token_auth_method with
| Basic -> [
("grant_type", "client_credentials");
("scope", String.concat " " cc_config.scope);
]
| Body -> [
("grant_type", "client_credentials");
("client_id", cc_config.client_id);
("client_secret", cc_config.client_secret);
("scope", String.concat " " cc_config.scope);
]
) in
let body = Utils.form_encode params in
let = (
match cc_config.token_auth_method with
| Basic -> Cohttp.Header.of_list [
("Content-Type", "application/x-www-form-urlencoded") ;
("Authorization", "Basic " ^ (Base64.encode_string (cc_config.client_id ^ ":" ^ cc_config.client_secret)))
]
| Body -> Cohttp.Header.init_with "Content-Type" "application/x-www-form-urlencoded"
) in
Client.post ~headers ~body cc_config.token_endpoint
>>= fun (_, body) -> Cohttp_lwt.Body.to_string body
>>= fun body_str ->
let json = Yojson.Safe.from_string body_str in
match token_response_of_yojson json with
| Ok token -> Lwt.return (Ok token)
| Error _ -> begin
match token_error_of_yojson json with
| Ok error -> begin
print_endline error.error_description;
Lwt.return (Error error.error_description)
end
| Error e -> begin
print_endline e;
Lwt.return (Error e)
end
end
end
| _ -> Lwt.return (Error "Client credentials token only available for Client Credentials flow")
let refresh_token ~config =
match config with
| RefreshTokenConfig refresh_config -> begin
let params = (
[
("grant_type", "refresh_token");
("refresh_token", refresh_config.refresh_token);
]
) @ (
match refresh_config.token_auth_method with
| Basic -> []
| Body -> [
("client_id", refresh_config.client_id);
("client_secret", refresh_config.client_secret);
]
) @ (match refresh_config.scope with
| Some scopes -> [("scope", String.concat " " scopes)]
| None -> []) in
let body = Utils.form_encode params in
let = (
match refresh_config.token_auth_method with
| Basic ->
Cohttp.Header.of_list [
("Content-Type", "application/x-www-form-urlencoded") ;
("Authorization", "Basic " ^ (Base64.encode_string (refresh_config.client_id ^ ":" ^ refresh_config.client_secret)))
]
| Body -> Cohttp.Header.init_with "Content-Type" "application/x-www-form-urlencoded"
) in
Client.post ~headers ~body refresh_config.token_endpoint
>>= fun (_, body) ->
Cohttp_lwt.Body.to_string body
>>= fun body_str ->
let json = Yojson.Safe.from_string body_str in
match token_response_of_yojson json with
| Ok token -> Lwt.return (Ok token)
| Error _ -> begin
match token_error_of_yojson json with
| Ok error -> begin
print_endline error.error_description;
Lwt.return (Error error.error_description)
end
| Error e -> begin
print_endline e;
Lwt.return (Error e)
end
end
end
| _ -> Lwt.return (Error "Refresh token only available for Refresh Token flow")
end