-
Notifications
You must be signed in to change notification settings - Fork 145
Expand file tree
/
Copy pathAuthAPI.java
More file actions
1456 lines (1340 loc) · 64 KB
/
AuthAPI.java
File metadata and controls
1456 lines (1340 loc) · 64 KB
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.auth0.client.auth;
import static com.auth0.json.ObjectMapperProvider.getMapper;
import com.auth0.json.auth.*;
import com.auth0.net.*;
import com.auth0.net.client.Auth0HttpClient;
import com.auth0.net.client.DefaultHttpClient;
import com.auth0.net.client.HttpMethod;
import com.auth0.utils.Asserts;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import okhttp3.HttpUrl;
import org.jetbrains.annotations.TestOnly;
/**
* Class that provides an implementation of of the Authentication and Authorization API methods defined by the
* <a href="https://auth0.com/docs/api/authentication">Auth0 Authentication API</a>.
* Instances are created using the {@link Builder}. If you are also using the {@link ManagementAPI}, it is recommended
* to configure each with the same {@link DefaultHttpClient} to enable both API clients to share the same Http client.
* <p>
* To use with a confidential client, instantiate an instance with a client secret:
* <pre>
* {@code
* AuthAPI auth = AuthAPI.newBuilder("{DOMAIN}", "{CLIENT-ID}", "{CLIENT-SECRET}").build();
* }
* </pre>
* <p>
* To use with a public client, or when only using APIs that do not require a client secret:
* <pre>
* {@code
* AuthAPI auth = AuthAPI.newBuilder("{DOMAIN}", "{CLIENT-ID}").build();
* }
* </pre>
* Operations that always require a client secret will throw a {@code InvalidStateException} if the client is not created
* with a secret.
*/
@SuppressWarnings("WeakerAccess")
public class AuthAPI {
private static final String KEY_CLIENT_ID = "client_id";
private static final String KEY_CLIENT_SECRET = "client_secret";
private static final String KEY_GRANT_TYPE = "grant_type";
private static final String KEY_USERNAME = "username";
private static final String KEY_PASSWORD = "password";
private static final String KEY_AUDIENCE = "audience";
private static final String KEY_EMAIL = "email";
private static final String KEY_CONNECTION = "connection";
private static final String KEY_TOKEN = "token";
private static final String KEY_REFRESH_TOKEN = "refresh_token";
private static final String KEY_OTP = "otp";
private static final String KEY_REALM = "realm";
private static final String KEY_MFA_TOKEN = "mfa_token";
private static final String KEY_CLIENT_ASSERTION = "client_assertion";
private static final String KEY_CLIENT_ASSERTION_TYPE = "client_assertion_type";
private static final String PATH_OAUTH = "oauth";
private static final String PATH_TOKEN = "token";
private static final String PATH_DBCONNECTIONS = "dbconnections";
private static final String PATH_REVOKE = "revoke";
private static final String PATH_PASSWORDLESS = "passwordless";
private static final String PATH_START = "start";
private static final String KEY_ORGANIZATION = "organization";
private static final String KEY_PHONE_NUMBER = "phone_number";
private final Auth0HttpClient client;
private final String clientId;
private final String clientSecret;
private final ClientAssertionSigner clientAssertionSigner;
private final HttpUrl baseUrl;
/**
* Initialize a new {@link Builder} to configure and create an instance. Use this to construct an instance
* with a client secret when using a confidential client (Regular Web Application).
* @param domain the tenant's domain. Must be a non-null valid HTTPS URL.
* @param clientId the application's client ID.
* @param clientSecret the applications client secret.
* @return a Builder for further configuration.
*/
public static Builder newBuilder(String domain, String clientId, String clientSecret) {
return new Builder(domain, clientId).withClientSecret(clientSecret);
}
/**
* Initialize a new {@link Builder} to configure and create an instance. Use this to construct an instance
* with a client assertion signer used in place of a client secret when calling token APIs.
*
* @param domain the tenant's domain. Must be a non-null valid HTTPS URL.
* @param clientId the application's client ID.
* @param clientAssertionSigner the {@code ClientAssertionSigner} used to create the signed client assertion.
* @return a Builder for further configuration.
*/
public static Builder newBuilder(String domain, String clientId, ClientAssertionSigner clientAssertionSigner) {
return new Builder(domain, clientId).withClientAssertionSigner(clientAssertionSigner);
}
/**
* Initialize a new {@link Builder} to configure and create an instance. Use this to construct an instance
* <strong>without</strong> a client secret (for example, when only using APIs that do not require a secret).
* @param domain the tenant's domain. Must be a non-null valid HTTPS URL.
* @param clientId the application's client ID.
* @return a Builder for further configuration.
*/
public static Builder newBuilder(String domain, String clientId) {
return new Builder(domain, clientId);
}
private AuthAPI(
String domain,
String clientId,
String clientSecret,
ClientAssertionSigner clientAssertionSigner,
Auth0HttpClient httpClient) {
Asserts.assertNotNull(domain, "domain");
Asserts.assertNotNull(clientId, "client id");
Asserts.assertNotNull(httpClient, "Http client");
this.baseUrl = createBaseUrl(domain);
if (baseUrl == null) {
throw new IllegalArgumentException("The domain had an invalid format and couldn't be parsed as an URL.");
}
this.clientId = clientId;
this.clientSecret = clientSecret;
this.clientAssertionSigner = clientAssertionSigner;
this.client = httpClient;
}
@TestOnly
Auth0HttpClient getHttpClient() {
return this.client;
}
@TestOnly
HttpUrl getBaseUrl() {
return baseUrl;
}
private HttpUrl createBaseUrl(String domain) {
String url = domain;
if (!domain.startsWith("https://") && !domain.startsWith("http://")) {
url = "https://" + domain;
}
return HttpUrl.parse(url);
}
/**
* Creates an instance of the {@link AuthorizeUrlBuilder} with the given redirect url.
* i.e.:
* <pre>
* {@code
* String url = authAPI.authorizeUrl("https://me.auth0.com/callback")
* .withConnection("facebook")
* .withAudience("https://api.me.auth0.com/users")
* .withScope("openid contacts")
* .withState("my-custom-state")
* .build();
* }
* </pre>
*
* @param redirectUri the URL to redirect to after authorization has been granted by the user. Your Auth0 application
* must have this URL as one of its Allowed Callback URLs. Must be a valid non-encoded URL.
* @return a new instance of the {@link AuthorizeUrlBuilder} to configure.
*/
public AuthorizeUrlBuilder authorizeUrl(String redirectUri) {
Asserts.assertValidUrl(redirectUri, "redirect uri");
return AuthorizeUrlBuilder.newInstance(baseUrl, clientId, redirectUri);
}
public Request<BackChannelAuthorizeResponse> authorizeBackChannel(
String scope, String bindingMessage, Map<String, Object> loginHint) {
return authorizeBackChannel(scope, bindingMessage, loginHint, null, null);
}
public Request<BackChannelAuthorizeResponse> authorizeBackChannel(
String scope,
String bindingMessage,
Map<String, Object> loginHint,
String audience,
Integer requestExpiry) {
Asserts.assertNotNull(scope, "scope");
Asserts.assertNotNull(bindingMessage, "binding message");
Asserts.assertNotNull(loginHint, "login hint");
String url = baseUrl.newBuilder().addPathSegment("bc-authorize").build().toString();
FormBodyRequest<BackChannelAuthorizeResponse> request = new FormBodyRequest<>(
client, null, url, HttpMethod.POST, new TypeReference<BackChannelAuthorizeResponse>() {});
request.addParameter(KEY_CLIENT_ID, clientId);
addClientAuthentication(request, false);
request.addParameter("scope", scope);
request.addParameter("binding_message", bindingMessage);
if (Objects.nonNull(audience)) {
request.addParameter(KEY_AUDIENCE, audience);
}
if (Objects.nonNull(requestExpiry)) {
request.addParameter("requested_expiry", requestExpiry);
}
try {
String loginHintJson = getMapper().writeValueAsString(loginHint);
request.addParameter("login_hint", loginHintJson);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException("'loginHint' must be a map that can be serialized to JSON", e);
}
return request;
}
public Request<BackChannelTokenResponse> getBackChannelLoginStatus(String authReqId, String grantType) {
Asserts.assertNotNull(authReqId, "auth req id");
Asserts.assertNotNull(grantType, "grant type");
String url = getTokenUrl();
FormBodyRequest<BackChannelTokenResponse> request = new FormBodyRequest<>(
client, null, url, HttpMethod.POST, new TypeReference<BackChannelTokenResponse>() {});
request.addParameter(KEY_CLIENT_ID, clientId);
addClientAuthentication(request, false);
request.addParameter("auth_req_id", authReqId);
request.addParameter(KEY_GRANT_TYPE, grantType);
return request;
}
/**
* Builds an authorization URL for Pushed Authorization Requests (PAR)
* @param requestUri the {@code request_uri} parameter from a successful pushed authorization request.
* @see AuthAPI#pushedAuthorizationRequest(String, String, Map)
* @see <a href="https://www.rfc-editor.org/rfc/rfc9126.html">RFC 9126</a>
* @return the {@code request_uri} from a successful pushed authorization request.
*/
public String authorizeUrlWithPAR(String requestUri) {
Asserts.assertNotNull(requestUri, "request uri");
return baseUrl.newBuilder()
.addPathSegment("authorize")
.addQueryParameter("client_id", clientId)
.addQueryParameter("request_uri", requestUri)
.build()
.toString();
}
/**
* Builds an authorization URL for JWT-Secured Authorization Request (JAR)
* @param request the {@code request} parameter value. As specified, it must be a signed JWT and contain claims representing the authorization parameters.
* @see AuthAPI#pushedAuthorizationRequestWithJAR(String)
* @see <a href="https://auth0.com/docs/get-started/authentication-and-authorization-flow/authorization-code-flow/authorization-code-flow-with-jar">Authorization Code Flow with JWT-Secured Authorization Requests (JAR)</a>
* @see <a href="https://datatracker.ietf.org/doc/html/rfc9101">RFC 9101</a>
* @return the authorization URL to redirect users to for authentication.
*/
public String authorizeUrlWithJAR(String request) {
Asserts.assertNotNull(request, "request");
return baseUrl.newBuilder()
.addPathSegment("authorize")
.addQueryParameter("client_id", clientId)
.addQueryParameter("request", request)
.build()
.toString();
}
/**
* Builds a request to make a Pushed Authorization Request (PAR) to receive a {@code request_uri} to send to the {@code /authorize} endpoint.
* @param redirectUri the URL to redirect to after authorization has been granted by the user. Your Auth0 application
* must have this URL as one of its Allowed Callback URLs. Must be a valid non-encoded URL.
* @param responseType the response type to set. Must not be null.
* @param params an optional map of key/value pairs representing any additional parameters to send on the request.
* @see <a href="https://www.rfc-editor.org/rfc/rfc9126.html">RFC 9126</a>
* @return a request to execute.
*/
public Request<PushedAuthorizationResponse> pushedAuthorizationRequest(
String redirectUri, String responseType, Map<String, String> params) {
return pushedAuthorizationRequest(redirectUri, responseType, params, null);
}
/**
* Builds a request to make a Pushed Authorization Request (PAR) to receive a {@code request_uri} to send to the {@code /authorize} endpoint.
* @param redirectUri the URL to redirect to after authorization has been granted by the user. Your Auth0 application
* must have this URL as one of its Allowed Callback URLs. Must be a valid non-encoded URL.
* @param responseType the response type to set. Must not be null.
* @param params an optional map of key/value pairs representing any additional parameters to send on the request.
* @param authorizationDetails A list of maps representing the value of the (optional) {@code authorization_details} parameter, used to perform Rich Authorization Requests. The list will be serialized to JSON and sent on the request.
* @see #pushedAuthorizationRequest(String, String, Map, List)
* @see <a href="https://www.rfc-editor.org/rfc/rfc9126.html">RFC 9126</a>
* @see <a href="https://datatracker.ietf.org/doc/html/rfc9396">RFC 9396</a>
* @see <a href="https://auth0.com/docs/get-started/authentication-and-authorization-flow/authorization-code-flow/authorization-code-flow-with-rar">Authorization Code Flow with Rich Authorization Requests (RAR)</a>
* @return a request to execute.
*/
public Request<PushedAuthorizationResponse> pushedAuthorizationRequest(
String redirectUri,
String responseType,
Map<String, String> params,
List<Map<String, Object>> authorizationDetails) {
Asserts.assertValidUrl(redirectUri, "redirect uri");
Asserts.assertNotNull(responseType, "response type");
String url = baseUrl.newBuilder().addPathSegments("oauth/par").build().toString();
FormBodyRequest<PushedAuthorizationResponse> request = new FormBodyRequest<>(
client, null, url, HttpMethod.POST, new TypeReference<PushedAuthorizationResponse>() {});
request.addParameter("client_id", clientId);
request.addParameter("redirect_uri", redirectUri);
request.addParameter("response_type", responseType);
if (Objects.nonNull(this.clientSecret)) {
request.addParameter("client_secret", clientSecret);
}
if (params != null) {
params.forEach(request::addParameter);
}
try {
if (Objects.nonNull(authorizationDetails)) {
String authDetailsJson = getMapper().writeValueAsString(authorizationDetails);
request.addParameter("authorization_details", authDetailsJson);
}
} catch (JsonProcessingException e) {
throw new IllegalArgumentException(
"'authorizationDetails' must be a list that can be serialized to JSON", e);
}
return request;
}
/**
* Builds a request to make a Pushed Authorization Request (PAR) with JWT-Secured Authorization Requests (JAR), to receive a {@code request_uri} to send to the {@code /authorize} endpoint.
* @param request The signed JWT containing the authorization parameters as claims.
* @see #pushedAuthorizationRequestWithJAR(String, List)
* @see <a href="https://auth0.com/docs/get-started/authentication-and-authorization-flow/authorization-code-flow/authorization-code-flow-with-par-and-jar">Authorization Code Flow with PAR and JAR</a>
* @see <a href="https://datatracker.ietf.org/doc/html/rfc9101">RFC 9101</a>
* @see <a href="https://www.rfc-editor.org/rfc/rfc9126.html">RFC 9126</a>
* @return a request to execute.
*/
public Request<PushedAuthorizationResponse> pushedAuthorizationRequestWithJAR(String request) {
return pushedAuthorizationRequestWithJAR(request, null);
}
/**
* Builds a request to make a Pushed Authorization Request (PAR) with JWT-Secured Authorization Requests (JAR), to receive a {@code request_uri} to send to the {@code /authorize} endpoint.
* @param request The signed JWT containing the authorization parameters as claims.
* @param authorizationDetails A list of maps representing the value of the (optional) {@code authorization_details} parameter, used to perform Rich Authorization Requests. The list will be serialized to JSON and sent on the request.
* @see #pushedAuthorizationRequestWithJAR(String)
* @see <a href="https://auth0.com/docs/get-started/authentication-and-authorization-flow/authorization-code-flow/authorization-code-flow-with-par-and-jar">Authorization Code Flow with PAR and JAR</a>
* @see <a href="https://auth0.com/docs/get-started/authentication-and-authorization-flow/authorization-code-flow/authorization-code-flow-with-rar">Authorization Code Flow with Rich Authorization Requests (RAR)</a>
* @see <a href="https://datatracker.ietf.org/doc/html/rfc9101">RFC 9101</a>
* @see <a href="https://www.rfc-editor.org/rfc/rfc9126.html">RFC 9126</a>
* @see <a href="https://datatracker.ietf.org/doc/html/rfc9396">RFC 9396</a>
* @return a request to execute.
*/
public Request<PushedAuthorizationResponse> pushedAuthorizationRequestWithJAR(
String request, List<Map<String, Object>> authorizationDetails) {
Asserts.assertNotNull(request, "request");
String url = baseUrl.newBuilder().addPathSegments("oauth/par").build().toString();
FormBodyRequest<PushedAuthorizationResponse> req = new FormBodyRequest<>(
client, null, url, HttpMethod.POST, new TypeReference<PushedAuthorizationResponse>() {});
req.addParameter("client_id", clientId);
req.addParameter("request", request);
if (Objects.nonNull(this.clientSecret)) {
req.addParameter("client_secret", clientSecret);
}
try {
if (Objects.nonNull(authorizationDetails)) {
String authDetailsJson = getMapper().writeValueAsString(authorizationDetails);
req.addParameter("authorization_details", authDetailsJson);
}
} catch (JsonProcessingException e) {
throw new IllegalArgumentException(
"'authorizationDetails' must be a list that can be serialized to JSON", e);
}
return req;
}
/**
* Creates an instance of the {@link LogoutUrlBuilder} with the given return-to url.
* i.e.:
* <pre>
* {@code
* String url = authAPI.logoutUrl("https://me.auth0.com/home", true)
* .useFederated(true)
* .withAccessToken("A9CvPwFojaBIA9CvI");
* }
* </pre>
*
* @param returnToUrl the URL the user should be navigated to upon logout. Must be a valid non-encoded URL.
* @param setClientId whether the client_id value must be set or not. If {@code true}, the {@code returnToUrl} must
* be included in your Auth0 Application's Allowed Logout URLs list. If {@code false}, the
* {@code returnToUrl} must be included in your Auth0's Allowed Logout URLs at the Tenant level.
* @return a new instance of the {@link LogoutUrlBuilder} to configure.
*/
public LogoutUrlBuilder logoutUrl(String returnToUrl, boolean setClientId) {
Asserts.assertValidUrl(returnToUrl, "return to url");
return LogoutUrlBuilder.newInstance(baseUrl, clientId, returnToUrl, setClientId);
}
/**
* Request the user information related to the access token.
* i.e.:
* <pre>
* {@code
* try {
* UserInfo result = authAPI.userInfo("A9CvPwFojaBIA9CvI").execute().getBody();
* } catch (Auth0Exception e) {
* //Something happened
* }
* }
* </pre>
*
* @see <a href="https://auth0.com/docs/api/authentication#get-user-info">Get User Info API docs</a>
* @param accessToken a valid access token belonging to an API signed with RS256 algorithm and containing the scope 'openid'.
* @return a Request to execute.
*/
public Request<UserInfo> userInfo(String accessToken) {
Asserts.assertNotNull(accessToken, "access token");
String url = baseUrl.newBuilder().addPathSegment("userinfo").build().toString();
BaseRequest<UserInfo> request =
new BaseRequest<>(client, null, url, HttpMethod.GET, new TypeReference<UserInfo>() {});
request.addHeader("Authorization", "Bearer " + accessToken);
return request;
}
/**
* Request a password reset for the given email and database connection, using the client ID configured for this client instance.
* The response will always be successful even if there's no user associated to the given email for that database connection.
* i.e.:
* <pre>
* {@code
* try {
* authAPI.resetPassword("[email protected]", "db-connection").execute().getBody();
* } catch (Auth0Exception e) {
* //Something happened
* }
* }
* </pre>
*
* @see <a href="https://auth0.com/docs/api/authentication#change-password">Change Password API docs</a>
* @param email the email associated to the database user.
* @param connection the database connection where the user was created.
* @return a Request to execute.
*/
public Request<Void> resetPassword(String email, String connection) {
return resetPassword(this.clientId, email, connection);
}
/**
* Request a password reset for the given client ID, email, and database connection. The response will always be successful even if
* there's no user associated to the given email for that database connection.
* i.e.:
* <pre>
* {@code
* try {
* authAPI.resetPassword("CLIENT-ID", "[email protected]", "db-connection").execute().getBody();
* } catch (Auth0Exception e) {
* //Something happened
* }
* }
* </pre>
*
* @see <a href="https://auth0.com/docs/api/authentication#change-password">Change Password API docs</a>
* @param clientId the client ID of your client.
* @param email the email associated to the database user.
* @param connection the database connection where the user was created.
* @return a Request to execute.
*/
public Request<Void> resetPassword(String clientId, String email, String connection) {
return resetPassword(clientId, email, connection, null);
}
/**
* Request a password reset for the given client ID, email, database connection and organization ID. The response will always be successful even if
* there's no user associated to the given email for that database connection.
* i.e.:
* <pre>
* {@code
* try {
* authAPI.resetPassword("CLIENT-ID", "[email protected]", "db-connection", "ORGANIZATION-ID").execute().getBody();
* } catch (Auth0Exception e) {
* //Something happened
* }
* }
* </pre>
*
* @see <a href="https://auth0.com/docs/api/authentication#change-password">Change Password API docs</a>
* @param clientId the client ID of your client.
* @param email the email associated to the database user.
* @param connection the database connection where the user was created.
* @param organization the organization ID where the user was created.
* @return a Request to execute.
*/
public Request<Void> resetPassword(String clientId, String email, String connection, String organization) {
Asserts.assertNotNull(email, "email");
Asserts.assertNotNull(connection, "connection");
String url = baseUrl.newBuilder()
.addPathSegment(PATH_DBCONNECTIONS)
.addPathSegment("change_password")
.build()
.toString();
VoidRequest request = new VoidRequest(client, null, url, HttpMethod.POST);
request.addParameter(KEY_CLIENT_ID, clientId);
request.addParameter(KEY_EMAIL, email);
request.addParameter(KEY_CONNECTION, connection);
request.addParameter(KEY_ORGANIZATION, organization);
return request;
}
/**
* Creates a sign up request with the given credentials, phone number and database connection.
* "Requires Username" option must be turned on in the Connection's configuration first.
* i.e.:
* <pre>
* {@code
* try {
* Map<String, String> fields = new HashMap<String, String>();
* fields.put("age", "25);
* fields.put("city", "Buenos Aires");
* authAPI.signUp("[email protected]", "myself", new char[]{'s','e','c','r','e','t'}, "db-connection", "1234567890")
* .setCustomFields(fields)
* .execute();
* } catch (Auth0Exception e) {
* //Something happened
* }
* }
* </pre>
*
* @see <a href="https://auth0.com/docs/api/authentication#signup">Signup API docs</a>
* @param email the desired user's email.
* @param username the desired user's username.
* @param password the desired user's password.
* @param connection the database connection where the user is going to be created.
* @param phoneNumber the desired users's phone number.
* @return a Request to configure and execute.
*/
public SignUpRequest signUp(String email, String username, char[] password, String connection, String phoneNumber) {
Asserts.assertNotNull(phoneNumber, "phone number");
SignUpRequest request = this.signUp(email, username, password, connection);
request.addParameter(KEY_PHONE_NUMBER, phoneNumber);
return request;
}
/**
* Creates a sign up request with the given credentials and database connection.
* "Requires Username" option must be turned on in the Connection's configuration first.
* i.e.:
* <pre>
* {@code
* try {
* Map<String, String> fields = new HashMap<String, String>();
* fields.put("age", "25);
* fields.put("city", "Buenos Aires");
* authAPI.signUp("[email protected]", "myself", new char[]{'s','e','c','r','e','t'}, "db-connection")
* .setCustomFields(fields)
* .execute();
* } catch (Auth0Exception e) {
* //Something happened
* }
* }
* </pre>
*
* @see <a href="https://auth0.com/docs/api/authentication#signup">Signup API docs</a>
* @param email the desired user's email.
* @param username the desired user's username.
* @param password the desired user's password.
* @param connection the database connection where the user is going to be created.
* @return a Request to configure and execute.
*/
public SignUpRequest signUp(String email, String username, char[] password, String connection) {
Asserts.assertNotNull(username, "username");
SignUpRequest request = this.signUp(email, password, connection);
request.addParameter(KEY_USERNAME, username);
return request;
}
/**
* Creates a sign up request with the given credentials and database connection.
* <pre>
* {@code
* try {
* Map<String, String> fields = new HashMap<String, String>();
* fields.put("age", "25);
* fields.put("city", "Buenos Aires");
* authAPI.signUp("[email protected]", new char[]{'s','e','c','r','e','t'}, "db-connection")
* .setCustomFields(fields)
* .execute();
* } catch (Auth0Exception e) {
* //Something happened
* }
* }
* </pre>
*
* @see <a href="https://auth0.com/docs/api/authentication#signup">Signup API docs</a>
* @param email the desired user's email.
* @param password the desired user's password.
* @param connection the database connection where the user is going to be created.
* @return a Request to configure and execute.
*/
public SignUpRequest signUp(String email, char[] password, String connection) {
Asserts.assertNotNull(email, "email");
Asserts.assertNotNull(password, "password");
Asserts.assertNotNull(connection, "connection");
String url = baseUrl.newBuilder()
.addPathSegment(PATH_DBCONNECTIONS)
.addPathSegment("signup")
.build()
.toString();
SignUpRequest request = new SignUpRequest(client, url);
request.addParameter(KEY_CLIENT_ID, clientId);
request.addParameter(KEY_EMAIL, email);
request.addParameter(KEY_PASSWORD, password);
request.addParameter(KEY_CONNECTION, connection);
return request;
}
/**
* Creates a log in request using the 'Password' grant and the given credentials.
* <strong>
* This flow should only be used from highly-trusted applications that cannot do redirects.
* If you can use redirect-based flows from your app, we recommend using the Authorization Code Flow instead.
* </strong>
* i.e.:
* <pre>
* {@code
* try {
* TokenHolder result = authAPI.login("[email protected]", new char[]{'s','e','c','r','e','t})
* .setScope("openid email nickname")
* .execute()
* .getBody();
* } catch (Auth0Exception e) {
* //Something happened
* }
* }
* </pre>
*
* @see <a href="https://auth0.com/docs/api/authentication#client-credentials-flow">Resource Owner Password API docs</a>.
* @param emailOrUsername the identity of the user.
* @param password the password of the user.
* @return a Request to configure and execute.
*/
public TokenRequest login(String emailOrUsername, char[] password) {
Asserts.assertNotNull(emailOrUsername, "email or username");
Asserts.assertNotNull(password, "password");
TokenRequest request = new TokenRequest(client, getTokenUrl());
request.addParameter(KEY_CLIENT_ID, clientId);
request.addParameter(KEY_GRANT_TYPE, "password");
request.addParameter(KEY_USERNAME, emailOrUsername);
request.addParameter(KEY_PASSWORD, password);
addClientAuthentication(request, true);
return request;
}
/**
* Creates a log in request using the 'Password Realm' grant and the given credentials.
* Default used realm and audience are defined in the "API Authorization Settings" in the account's advanced settings in the Auth0 Dashboard.
* <strong>
* This flow should only be used from highly-trusted applications that cannot do redirects.
* If you can use redirect-based flows from your app, we recommend using the Authorization Code Flow instead.
* </strong>
* <pre>
* {@code
* try {
* TokenHolder result = authAPI.login("[email protected]", new char[]{'s','e','c','r','e','t'}, "my-realm")
* .setAudience("https://myapi.me.auth0.com/users")
* .execute()
* .getBody();
* } catch (Auth0Exception e) {
* //Something happened
* }
* }
* </pre>
*
* @param emailOrUsername the identity of the user.
* @param password the password of the user.
* @param realm the realm to use.
* @return a Request to configure and execute.
* @see <a href="https://auth0.com/docs/api/authentication#client-credentials-flow">Resource Owner Password API docs</a>.
*/
public TokenRequest login(String emailOrUsername, char[] password, String realm) {
Asserts.assertNotNull(emailOrUsername, "email or username");
Asserts.assertNotNull(password, "password");
Asserts.assertNotNull(realm, "realm");
TokenRequest request = new TokenRequest(client, getTokenUrl());
request.addParameter(KEY_CLIENT_ID, clientId);
request.addParameter(KEY_GRANT_TYPE, "http://auth0.com/oauth/grant-type/password-realm");
request.addParameter(KEY_USERNAME, emailOrUsername);
request.addParameter(KEY_PASSWORD, password);
request.addParameter(KEY_REALM, realm);
addClientAuthentication(request, true);
return request;
}
/**
* Creates a login request using the Passwordless grant type.
* Confidential clients (Regular Web Apps) <strong>must</strong> have a client secret configured on this {@code AuthAPI} instance.
*
* <pre>
* {@code
* try {
* TokenHolder result = authAPI.exchangePasswordlessOtp("[email protected]", "email", new char[]{'c','o','d','e'})
* .execute()
* .getBody();
* } catch (Auth0Exception e) {
* // Something happened
* }
* }
* </pre>
*
* @param emailOrPhone The email or phone number of the user. Must not be null.
* @param realm The realm to use. Typically "email" or "sms", unless using a custom Passwordless connection. Must not be null.
* @param otp The one-time password used to authenticate using Passwordless connections. Must not be null.
*
* @return A request to configure and execute
*
* @see <a href="https://auth0.com/docs/connections/passwordless/reference/relevant-api-endpoints">Using Passwordless APIs</a>
* @see <a href="https://auth0.com/docs/api/authentication#authenticate-user">Passwordless Authenticate User API docs</a>
* @see AuthAPI#startPasswordlessEmailFlow(String, PasswordlessEmailType)
* @see AuthAPI#startPasswordlessSmsFlow(String)
*/
public TokenRequest exchangePasswordlessOtp(String emailOrPhone, String realm, char[] otp) {
Asserts.assertNotNull(emailOrPhone, "emailOrPhone");
Asserts.assertNotNull(realm, "realm");
Asserts.assertNotNull(otp, "otp");
TokenRequest request = new TokenRequest(client, getTokenUrl());
request.addParameter(KEY_CLIENT_ID, clientId);
request.addParameter(KEY_GRANT_TYPE, "http://auth0.com/oauth/grant-type/passwordless/otp");
request.addParameter(KEY_USERNAME, emailOrPhone);
request.addParameter(KEY_REALM, realm);
request.addParameter(KEY_OTP, otp);
addClientAuthentication(request, false);
return request;
}
/**
* Creates a request to get a Token for the given audience using the 'Client Credentials' grant.
* Default used realm is defined in the "API Authorization Settings" in the account's advanced settings in the Auth0 Dashboard.
* <strong>This operation requires that a client secret be configured for the {@code AuthAPI} client.</strong>
* <pre>
* {@code
* try {
* TokenHolder result = authAPI.requestToken("https://myapi.me.auth0.com/users")
* .setRealm("my-realm")
* .execute()
* .getBody();
* } catch (Auth0Exception e) {
* //Something happened
* }
* }
* </pre>
*
* @see <a href="https://auth0.com/docs/api/authentication#client-credentials-flow">Client Credentials Flow API docs</a>
* @param audience the audience of the API to request access to.
* @return a Request to configure and execute.
*/
public TokenRequest requestToken(String audience) {
return requestToken(audience, null);
}
/**
* Creates a request to get a Token for the given audience using the 'Client Credentials' grant.
* Default used realm is defined in the "API Authorization Settings" in the account's advanced settings in the Auth0 Dashboard.
* <strong>This operation requires that a client secret be configured for the {@code AuthAPI} client.</strong>
* <pre>
* {@code
* try {
* TokenHolder result = authAPI.requestToken("https://myapi.me.auth0.com/users", "org_123")
* .execute()
* .getBody();
* } catch (Auth0Exception e) {
* //Something happened
* }
* }
* </pre>
*
* @see <a href="https://auth0.com/docs/api/authentication#client-credentials-flow">Client Credentials Flow API docs</a>
* @param audience the audience of the API to request access to.
* @param org the organization name or ID to be included in the request.
* @return a Request to configure and execute.
*/
public TokenRequest requestToken(String audience, String org) {
Asserts.assertNotNull(audience, "audience");
TokenRequest request = new TokenRequest(client, getTokenUrl());
request.addParameter(KEY_CLIENT_ID, clientId);
request.addParameter(KEY_GRANT_TYPE, "client_credentials");
request.addParameter(KEY_AUDIENCE, audience);
if (org != null && !org.trim().isEmpty()) {
request.addParameter(KEY_ORGANIZATION, org);
}
addClientAuthentication(request, true);
return request;
}
/**
* Creates a request to revoke an existing Refresh Token.
* Confidential clients (Regular Web Apps) <strong>must</strong> have a client secret configured on this {@code AuthAPI} instance.
* <pre>
* {@code
* try {
* authAPI.revokeToken("ej2E8zNEzjrcSD2edjaE")
* .execute();
* } catch (Auth0Exception e) {
* //Something happened
* }
* }
* </pre>
*
* @see <a href="https://auth0.com/docs/api/authentication#revoke-refresh-token">Revoke refresh token API docs</a>
* @param refreshToken the refresh token to revoke.
* @return a Request to execute.
*/
public Request<Void> revokeToken(String refreshToken) {
Asserts.assertNotNull(refreshToken, "refresh token");
String url = baseUrl.newBuilder()
.addPathSegment(PATH_OAUTH)
.addPathSegment(PATH_REVOKE)
.build()
.toString();
VoidRequest request = new VoidRequest(client, null, url, HttpMethod.POST);
request.addParameter(KEY_CLIENT_ID, clientId);
request.addParameter(KEY_TOKEN, refreshToken);
addClientAuthentication(request, false);
return request;
}
/**
* Creates a request to renew the authentication and get fresh new credentials using a valid Refresh Token and the
* {@code refresh_token} grant.
* Confidential clients (Regular Web Apps) <strong>must</strong> have a client secret configured on this {@code AuthAPI} instance.
*
* <pre>
* {@code
* try {
* TokenHolder result = authAPI.renewAuth("ej2E8zNEzjrcSD2edjaE")
* .execute()
* .getBody();
* } catch (Auth0Exception e) {
* //Something happened
* }
* }
* </pre>
*
* @see <a href="https://auth0.com/docs/api/authentication#refresh-token">Refresh Token API docs</a>
* @param refreshToken the refresh token to use to get fresh new credentials.
* @return a Request to configure and execute.
*/
public TokenRequest renewAuth(String refreshToken) {
Asserts.assertNotNull(refreshToken, "refresh token");
TokenRequest request = new TokenRequest(client, getTokenUrl());
request.addParameter(KEY_CLIENT_ID, clientId);
request.addParameter(KEY_GRANT_TYPE, "refresh_token");
request.addParameter(KEY_REFRESH_TOKEN, refreshToken);
addClientAuthentication(request, false);
return request;
}
/**
* Creates a request to exchange the code obtained in the /authorize call using the 'Authorization Code' grant.
* This operation requires the {@code AuthAPI} instance to have a client secret configured.
* <pre>
* {@code
* try {
* TokenHolder result = authAPI.exchangeCode("SnWoFLMzApDskr", "https://me.auth0.com/callback")
* .setScope("openid name nickname")
* .execute()
* .getBody();
* } catch (Auth0Exception e) {
* //Something happened
* }
* }
* </pre>
*
* @see <a href="https://auth0.com/docs/api/authentication#authorization-code-flow">Authorization Code Flow API docs</a>
* @param code the authorization code received from the /authorize call.
* @param redirectUri the redirect uri sent on the /authorize call.
* @return a Request to configure and execute.
*/
public TokenRequest exchangeCode(String code, String redirectUri) {
return exchangeCode(code, redirectUri, true);
}
/**
* Creates a request to exchange the code obtained from the {@code /authorize} call using the Authorization Code
* with PKCE grant.
* Confidential clients (Regular Web Apps) <strong>must</strong> have a client secret configured on this {@code AuthAPI} instance.
* <pre>
* {@code
* AuthAPI auth = AuthAPI.newBuilder("DOMAIN", "CLIENT-ID", "CLIENT-SECRET").build();
*
* SecureRandom sr = new SecureRandom();
* byte[] code = new byte[32];
* sr.nextBytes(code);
* String verifier = Base64.getUrlEncoder().withoutPadding().encodeToString(code);
*
* byte[] bytes = verifier.getBytes("US-ASCII");
* MessageDigest md = MessageDigest.getInstance("SHA-256");
* md.update(bytes, 0, bytes.length);
* byte[] digest = md.digest();
* String challenge = Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
*
* // generate authorize URL with code challenge derived from verifier
* String url = auth.authorizeUrl("https://me.auth0.com/callback")
* .withCodeChallenge(challenge)
* .build();
*
* // on redirect, exchange code and verify challenge
* try {
* TokenHolder result = auth.exchangeCodeWithVerifier("CODE", verifier, "https://me.auth0.com/callback")
* .setScope("openid name nickname")
* .execute();
* } catch (Auth0Exception e) {
* // Something happened
* }
* }
* </pre>
*
* @param code the authorization code received from the {@code /authorize} call.
* @param verifier the cryptographically random key that was used to generate the {@code code_challenge} passed to
* {@code /authorize}
* @param redirectUri the redirect uri sent on the /authorize call.
* @return a Request to configure and execute.
*/
public TokenRequest exchangeCodeWithVerifier(String code, String verifier, String redirectUri) {
Asserts.assertNotNull(code, "code");
Asserts.assertNotNull(redirectUri, "redirect uri");
Asserts.assertNotNull(verifier, "verifier");
TokenRequest request = exchangeCode(code, redirectUri, false);
request.addParameter("code_verifier", verifier);
return request;
}
/**
* Create a request to send an email containing a link or a code to begin authentication with Passwordless connections.
* Confidential clients (Regular Web Apps) <strong>must</strong> have a client secret configured on this {@code AuthAPI} instance.
* <pre>
* {@code
* try {
* PasswordlessEmailResponse result = authAPI.startPasswordlessEmailFlow("[email protected]", PasswordlessEmailType.CODE)
* .execute()
* .getBody();
* } catch (Auth0Exception e) {
* // Something happened
* }
* }
* </pre>
*
* @param email the email address to send the code or link to. Must not be null.
* @param type the type of the passwordless email request. Must not be null.
*
* @return a Request to configure and execute.
*
* @see <a href="https://auth0.com/docs/connections/passwordless/guides/email-otp">Passwordless Authentication with Email documentation</a>
* @see <a href="https://auth0.com/docs/api/authentication#get-code-or-link">Get code or link API reference documentation</a>
*/
public BaseRequest<PasswordlessEmailResponse> startPasswordlessEmailFlow(String email, PasswordlessEmailType type) {
Asserts.assertNotNull(email, "email");
Asserts.assertNotNull(type, "type");
String url = baseUrl.newBuilder()
.addPathSegment(PATH_PASSWORDLESS)
.addPathSegment(PATH_START)
.build()
.toString();
BaseRequest<PasswordlessEmailResponse> request = new BaseRequest<>(
client, null, url, HttpMethod.POST, new TypeReference<PasswordlessEmailResponse>() {});
request.addParameter(KEY_CLIENT_ID, clientId);
request.addParameter(KEY_CONNECTION, "email");
request.addParameter(KEY_EMAIL, email);
request.addParameter("send", type.getType());
addClientAuthentication(request, false);
return request;
}
/**
* Create a request to send a text message containing a code to begin authentication with Passwordless connections.
* Confidential clients (Regular Web Apps) <strong>must</strong> have a client secret configured on this {@code AuthAPI} instance.
* <pre>
* {@code
* try {
* PasswordlessSmsResponse result = authAPI.startPasswordlessSmsFlow("+16511234567")
* .execute()
* .getBody();
* } catch (Auth0Exception e) {
* // Something happened
* }
* }
* </pre>