-
Notifications
You must be signed in to change notification settings - Fork 129
/
EXAMPLES.md
1217 lines (968 loc) · 39.3 KB
/
EXAMPLES.md
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
# Examples using Auth0.Android
- [Examples using Auth0.Android](#examples-using-auth0android)
- [Authenticate with any Auth0 connection](#authenticate-with-any-auth0-connection)
- [Specify audience](#specify-audience)
- [Specify scope](#specify-scope)
- [Specify Connection scope](#specify-connection-scope)
- [Specify Parameter](#specify-parameter)
- [Customize the Custom Tabs UI](#customize-the-custom-tabs-ui)
- [Changing the Return To URL scheme](#changing-the-return-to-url-scheme)
- [Trusted Web Activity](#trusted-web-activity-experimental)
- [Authentication API](#authentication-api)
- [Login with database connection](#login-with-database-connection)
- [Login using MFA with One Time Password code](#login-using-mfa-with-one-time-password-code)
- [Passwordless Login](#passwordless-login)
- [Step 1: Request the code](#step-1-request-the-code)
- [Step 2: Input the code](#step-2-input-the-code)
- [Sign Up with a database connection](#sign-up-with-a-database-connection)
- [Get user information](#get-user-information)
- [Credentials Manager](#credentials-manager)
- [Secure Credentials Manager](#secure-credentials-manager)
- [Usage](#usage)
- [Requiring Authentication](#requiring-authentication)
- [Handling Credentials Manager exceptions](#handling-credentials-manager-exceptions)
- [Bot Protection](#bot-protection)
- [Management API](#management-api)
- [Link users](#link-users)
- [Unlink users](#unlink-users)
- [Get User Profile](#get-user-profile)
- [Update User Metadata](#update-user-metadata)
- [Token Validation](#token-validation)
- [Organizations](#organizations)
- [Log in to an organization](#log-in-to-an-organization)
- [Accept user invitations](#accept-user-invitations)
- [Networking client customization](#networking-client-customization)
- [Timeout configuration](#timeout-configuration)
- [Logging configuration](#logging-configuration)
- [Set additional headers for all requests](#set-additional-headers-for-all-requests)
- [Advanced configuration](#advanced-configuration)
- [Unit testing with JUnit 4 or JUnit 5](#unit-testing-with-junit-4-or-junit-5)
- [Handling `Method getMainLooper in android.os.Looper not mocked` errors](#handling-method-getmainlooper-in-androidoslooper-not-mocked-errors)
- [Handling SSL errors](#handling-ssl-errors)
- [Proguard](#proguard)
## Authenticate with any Auth0 connection
The connection must first be enabled in the Auth0 dashboard for this Auth0 application.
```kotlin
WebAuthProvider.login(account)
.withConnection("twitter")
.start(this, callback)
```
## Specify audience
```kotlin
WebAuthProvider.login(account)
.withAudience("https://{YOUR_AUTH0_DOMAIN}/api/v2/")
.start(this, callback)
```
The sample above requests tokens with the audience required to call the [Management API](https://auth0.com/docs/api/management/v2) endpoints.
> Replace `{YOUR_AUTH0_DOMAIN}` with your actual Auth0 domain (i.e. `mytenant.auth0.com`). If you've set up the tenant to use "Custom Domains", use that value here.
## Specify scope
```kotlin
WebAuthProvider.login(account)
.withScope("openid profile email read:users")
.start(this, callback)
```
> The default scope used is `openid profile email`. Regardless of the scopes passed here, the `openid` scope is always enforced.
## Specify Connection scope
```kotlin
WebAuthProvider.login(account)
.withConnectionScope("email", "profile", "calendar:read")
.start(this, callback)
```
## Specify Parameter
To [prompt](https://auth0.com/docs/customize/universal-login-pages/customize-login-text-prompts#prompt-values) the user to login or to send custom parameters in the request, `.withParameters` method can be used.
```kotlin
WebAuthProvider.login(account)
.withParameters(mapOf("prompt" to "login", "custom" to "value"))
.start(this, callback)
```
## Customize the Custom Tabs UI
If the device where the app is running has a Custom Tabs compatible Browser, a Custom Tab will be preferred for the logout flow. You can customize the Page Title visibility, the Toolbar color, and the supported Browser applications by using the `CustomTabsOptions` class.
```kotlin
val ctOptions = CustomTabsOptions.newBuilder()
.withToolbarColor(R.color.ct_toolbar_color)
.showTitle(true)
.build()
WebAuthProvider.login(account)
.withCustomTabsOptions(ctOptions)
.start(this, callback)
```
<details>
<summary>Using Java</summary>
```java
CustomTabsOptions options = CustomTabsOptions.newBuilder()
.withToolbarColor(R.color.ct_toolbar_color)
.showTitle(true)
.build();
WebAuthProvider.login(account)
.withCustomTabsOptions(options)
.start(MainActivity.this, callback);
```
</details>
## Changing the Return To URL scheme
This configuration will probably match what you've done for the [authentication setup](#a-note-about-app-deep-linking).
```kotlin
WebAuthProvider.logout(account)
.withScheme("myapp")
.start(this, logoutCallback)
```
## Trusted Web Activity (Experimental)
> **Warning**
> Trusted Web Activity support in Auth0.Android is still experimental and can change in the future.
>
> Please test it thoroughly in all the targeted browsers and OS variants and let us know your feedback.
Trusted Web Activity is a feature provided by some browsers to provide a native look and feel to the custom tabs.
To use this feature, there are some additional steps you must take:
- We need the SHA256 fingerprints of the app’s signing certificate. To get this, you can run the following command on your APK
```shell
keytool -printcert -jarfile sample-debug.apk
```
- The fingerprint has to be updated in the [Auth0 Dashboard](https://manage.auth0.com/dashboard/eu/poovamraj/applications) under
Applications > *Specific Application* > Settings > Advanced Settings > Device Settings > Key Hashes
- App's package name has to be entered in the field above
Once the above prerequisites are met, you can call your login method as below to open your web authentication in Trusted Web Activity.
```kotlin
WebAuthProvider.login(account)
.withTrustedWebActivity()
.await(this)
```
## Authentication API
The client provides methods to authenticate the user against the Auth0 server.
Create a new instance by passing the account:
```kotlin
val authentication = AuthenticationAPIClient(account)
```
<details>
<summary>Using Java</summary>
```java
AuthenticationAPIClient authentication = new AuthenticationAPIClient(account);
```
</details>
**Note:** If your Auth0 account has the ["Bot Protection"](https://auth0.com/docs/anomaly-detection/bot-protection) feature enabled, your requests might be flagged for verification. Read how to handle this scenario on the [Bot Protection](#bot-protection) section.
### Login with database connection
```kotlin
authentication
.login("info@auth0.com", "a secret password", "my-database-connection")
.validateClaims() //mandatory
.start(object: Callback<Credentials, AuthenticationException> {
override fun onFailure(exception: AuthenticationException) { }
override fun onSuccess(credentials: Credentials) { }
})
```
<details>
<summary>Using coroutines</summary>
```kotlin
try {
val credentials = authentication
.login("info@auth0.com", "a secret password", "my-database-connection")
.validateClaims()
.await()
println(credentials)
} catch (e: AuthenticationException) {
e.printStacktrace()
}
```
</details>
<details>
<summary>Using Java</summary>
```java
authentication
.login("info@auth0.com", "a secret password", "my-database-connection")
.validateClaims() //mandatory
.start(new Callback<Credentials, AuthenticationException>() {
@Override
public void onSuccess(@Nullable Credentials payload) {
//Logged in!
}
@Override
public void onFailure(@NonNull AuthenticationException error) {
//Error!
}
});
```
</details>
> The default scope used is `openid profile email`. Regardless of the scopes set to the request, the `openid` scope is always enforced.
### Login using MFA with One Time Password code
This call requires the client to have the *MFA* Client Grant Type enabled. Check [this article](https://auth0.com/docs/clients/client-grant-types) to learn how to enable it.
When you sign in to a multifactor authentication enabled connection using the `login` method, you receive an error standing that MFA is required for that user along with an `mfa_token` value. Use this value to call `loginWithOTP` and complete the MFA flow passing the One Time Password from the enrolled MFA code generator app.
```kotlin
authentication
.loginWithOTP("the mfa token", "123456")
.validateClaims() //mandatory
.start(object: Callback<Credentials, AuthenticationException> {
override fun onFailure(exception: AuthenticationException) { }
override fun onSuccess(credentials: Credentials) { }
})
```
<details>
<summary>Using coroutines</summary>
```kotlin
try {
val credentials = authentication
.loginWithOTP("the mfa token", "123456")
.validateClaims()
.await()
println(credentials)
} catch (e: AuthenticationException) {
e.printStacktrace()
}
```
</details>
<details>
<summary>Using Java</summary>
```java
authentication
.loginWithOTP("the mfa token", "123456")
.validateClaims() //mandatory
.start(new Callback<Credentials, AuthenticationException>() {
@Override
public void onSuccess(@Nullable Credentials payload) {
//Logged in!
}
@Override
public void onFailure(@NonNull AuthenticationException error) {
//Error!
}
});
```
</details>
> The default scope used is `openid profile email`. Regardless of the scopes set to the request, the `openid` scope is always enforced.
### Passwordless Login
This feature requires your Application to have the *Passwordless OTP* enabled. See [this article](https://auth0.com/docs/clients/client-grant-types) to learn how to enable it.
Passwordless is a 2 step flow:
#### Step 1: Request the code
```kotlin
authentication
.passwordlessWithEmail("info@auth0.com", PasswordlessType.CODE, "my-passwordless-connection")
.start(object: Callback<Void, AuthenticationException> {
override fun onFailure(exception: AuthenticationException) { }
override fun onSuccess(result: Void?) { }
})
```
<details>
<summary>Using coroutines</summary>
```kotlin
try {
val result = authentication
.passwordlessWithEmail("info@auth0.com", PasswordlessType.CODE, "my-passwordless-connection")
.await()
println(result)
} catch (e: AuthenticationException) {
e.printStacktrace()
}
```
</details>
<details>
<summary>Using Java</summary>
```java
authentication
.passwordlessWithEmail("info@auth0.com", PasswordlessType.CODE, "my-passwordless-connection")
.start(new Callback<Void, AuthenticationException>() {
@Override
public void onSuccess(Void payload) {
//Code sent!
}
@Override
public void onFailure(@NonNull AuthenticationException error) {
//Error!
}
});
```
</details>
#### Step 2: Input the code
```kotlin
authentication
.loginWithEmail("info@auth0.com", "123456", "my-passwordless-connection")
.validateClaims() //mandatory
.start(object: Callback<Credentials, AuthenticationException> {
override fun onFailure(exception: AuthenticationException) { }
override fun onSuccess(credentials: Credentials) { }
})
```
<details>
<summary>Using coroutines</summary>
```kotlin
try {
val credentials = authentication
.loginWithEmail("info@auth0.com", "123456", "my-passwordless-connection")
.validateClaims()
.await()
println(credentials)
} catch (e: AuthenticationException) {
e.printStacktrace()
}
```
</details>
<details>
<summary>Using Java</summary>
```java
authentication
.loginWithEmail("info@auth0.com", "123456", "my-passwordless-connection")
.validateClaims() //mandatory
.start(new Callback<Credentials, AuthenticationException>() {
@Override
public void onSuccess(@Nullable Credentials payload) {
//Logged in!
}
@Override
public void onFailure(@NonNull AuthenticationException error) {
//Error!
}
});
```
</details>
> The default scope used is `openid profile email`. Regardless of the scopes set to the request, the `openid` scope is always enforced.
### Sign Up with a database connection
```kotlin
authentication
.signUp("info@auth0.com", "a secret password", "my-database-connection")
.validateClaims() //mandatory
.start(object: Callback<Credentials, AuthenticationException> {
override fun onFailure(exception: AuthenticationException) { }
override fun onSuccess(credentials: Credentials) { }
})
```
<details>
<summary>Using coroutines</summary>
```kotlin
try {
val credentials = authentication
.signUp("info@auth0.com", "a secret password", "my-database-connection")
.validateClaims()
.await()
println(credentials)
} catch (e: AuthenticationException) {
e.printStacktrace()
}
```
</details>
<details>
<summary>Using Java</summary>
```java
authentication
.signUp("info@auth0.com", "a secret password", "my-database-connection")
.validateClaims() //mandatory
.start(new Callback<Credentials, AuthenticationException>() {
@Override
public void onSuccess(@Nullable Credentials payload) {
//Signed Up & Logged in!
}
@Override
public void onFailure(@NonNull AuthenticationException error) {
//Error!
}
});
```
</details>
> The default scope used is `openid profile email`. Regardless of the scopes set to the request, the `openid` scope is always enforced.
### Get user information
```kotlin
authentication
.userInfo("user access_token")
.start(object: Callback<UserProfile, AuthenticationException> {
override fun onFailure(exception: AuthenticationException) { }
override fun onSuccess(profile: UserProfile) { }
})
```
<details>
<summary>Using coroutines</summary>
```kotlin
try {
val user = authentication
.userInfo("user access_token")
.await()
println(user)
} catch (e: AuthenticationException) {
e.printStacktrace()
}
```
</details>
<details>
<summary>Using Java</summary>
```java
authentication
.userInfo("user access_token")
.start(new Callback<UserProfile, AuthenticationException>() {
@Override
public void onSuccess(@Nullable UserProfile payload) {
//Got the profile!
}
@Override
public void onFailure(@NonNull AuthenticationException error) {
//Error!
}
});
```
</details>
## Credentials Manager
### Secure Credentials Manager
This version adds encryption to the data storage. Additionally, in those devices where a Secure Lock Screen has been configured it can require the user to authenticate before letting them obtain the stored credentials. The class is called `SecureCredentialsManager`.
#### Usage
The usage is similar to the previous version, with the slight difference that the manager now requires a valid android `Context` as shown below:
```kotlin
val authentication = AuthenticationAPIClient(account)
val storage = SharedPreferencesStorage(this)
val manager = SecureCredentialsManager(this, authentication, storage)
```
<details>
<summary>Using Java</summary>
```java
AuthenticationAPIClient authentication = new AuthenticationAPIClient(account);
Storage storage = new SharedPreferencesStorage(this);
SecureCredentialsManager manager = new SecureCredentialsManager(this, authentication, storage);
```
</details>
#### Requiring Authentication
You can require the user authentication to obtain credentials. This will make the manager prompt the user with the device's configured Lock Screen, which they must pass correctly in order to obtain the credentials. **This feature is only available on devices where the user has setup a secured Lock Screen** (PIN, Pattern, Password or Fingerprint).
To enable authentication you must call the `requireAuthentication` method passing a valid _Activity_ context, a request code that represents the authentication call, and the title and description to display in the Lock Screen. As seen in the snippet below, you can leave these last two parameters with `null` to use the system's default title and description. It's only safe to call this method before the Activity is started.
```kotlin
//You might want to define a constant with the Request Code
companion object {
const val AUTH_REQ_CODE = 111
}
manager.requireAuthentication(this, AUTH_REQ_CODE, null, null)
```
<details>
<summary>Using Java</summary>
```java
//You might want to define a constant with the Request Code
private static final int AUTH_REQ_CODE = 11;
manager.requireAuthentication(this, AUTH_REQ_CODE, null, null);
```
</details>
When the above conditions are met and the manager requires the user authentication, it will use the activity context to launch the Lock Screen activity and wait for its result. If your activity is a subclass of `ComponentActivity`, this will be handled automatically for you internally. Otherwise, your activity must override the `onActivityResult` method and pass the request code and result code to the manager's `checkAuthenticationResult` method to verify if this request was successful or not.
```kotlin
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (manager.checkAuthenticationResult(requestCode, resultCode)) {
return
}
super.onActivityResult(requestCode, resultCode, data)
}
```
<details>
<summary>Using Java</summary>
```java
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (manager.checkAuthenticationResult(requestCode, resultCode)) {
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
```
</details>
If the manager consumed the event, it will return true and later invoke the callback's `onSuccess` with the decrypted credentials.
### Handling Credentials Manager exceptions
In the event that something happened while trying to save or retrieve the credentials, a `CredentialsManagerException` will be thrown. These are some of the expected failure scenarios:
- Invalid Credentials format or values. e.g. when it's missing the `access_token`, the `id_token` or the `expires_at` values.
- Tokens have expired but no `refresh_token` is available to perform a refresh credentials request.
- Device's Lock Screen security settings have changed (e.g. the PIN code was changed). Even when `hasCredentials` returns true, the encryption keys will be deemed invalid and until `saveCredentials` is called again it won't be possible to decrypt any previously existing content, since they keys used back then are not the same as the new ones.
- Device is not compatible with some of the algorithms required by the `SecureCredentialsManager` class. This is considered a catastrophic event and might happen when the OEM has modified the Android ROM removing some of the officially included algorithms. Nevertheless, it can be checked in the exception instance itself by calling `isDeviceIncompatible`. By doing so you can decide the fallback for storing the credentials, such as using the regular `CredentialsManager`.
## Bot Protection
If you are using the [Bot Protection](https://auth0.com/docs/anomaly-detection/bot-protection) feature and performing database login/signup via the Authentication API, you need to handle the `AuthenticationException#isVerificationRequired()` error. It indicates that the request was flagged as suspicious and an additional verification step is necessary to log the user in. That verification step is web-based, so you need to use Universal Login to complete it.
```kotlin
val email = "info@auth0.com"
val password = "a secret password"
val realm = "my-database-connection"
val authentication = AuthenticationAPIClient(account)
authentication.login(email, password, realm).validateClaims()
.start(object: Callback<Credentials, AuthenticationException> {
override fun onFailure(exception: AuthenticationException) {
if (exception.isVerificationRequired()) {
val params = mapOf("login_hint" to email) // So the user doesn't have to type it again
WebAuthProvider.login(account)
.withConnection(realm)
.withParameters(params)
.start(LoginActivity.this, object: Callback<Credentials, AuthenticationException> {
// You might already have a Callback instance defined
override fun onFailure(exception: AuthenticationException) {
// Handle error
}
override fun onSuccess(credentials: Credentials) {
// Handle WebAuth success
}
})
}
// Handle other errors
}
override fun onSuccess(credentials: Credentials) {
// Handle API success
}
})
```
<details>
<summary>Using Java</summary>
```java
final String email = "info@auth0.com";
final String password = "a secret password";
final String realm = "my-database-connection";
AuthenticationAPIClient authentication = new AuthenticationAPIClient(account);
authentication.login(email, password, realm).validateClaims()
.start(new Callback<Credentials, AuthenticationException>() {
@Override
public void onSuccess(@Nullable Credentials payload) {
// Handle API success
}
@Override
public void onFailure(@NonNull AuthenticationException error) {
if (error.isVerificationRequired()){
Map<String, Object> params = new HashMap<>();
params.put("login_hint", email); // So the user doesn't have to type it again
WebAuthProvider.login(account)
.withConnection(realm)
.withParameters(params)
.start(LoginActivity.this, new AuthCallback() {
// You might already have an AuthCallback instance defined
@Override
public void onFailure(@NonNull Dialog dialog) {
// Error dialog available
}
@Override
public void onFailure(AuthenticationException exception) {
// Error
}
@Override
public void onSuccess(@NonNull Credentials credentials) {
// Handle WebAuth success
}
});
}
}
});
```
</details>
In the case of signup, you can add [an additional parameter](https://auth0.com/docs/universal-login/new-experience#signup) to make the user land directly on the signup page:
```kotlin
val params = mapOf(
"login_hint" to email,
"screen_hint" to "signup"
)
```
<details>
<summary>Using Java</summary>
```java
params.put("login_hint", email);
params.put("screen_hint", "signup");
```
</details>
## Management API
The client provides a few methods to interact with the [Users Management API](https://auth0.com/docs/api/management/v2/#!/Users).
Create a new instance passing the account and an access token with the Management API audience and the right scope:
```kotlin
val users = UsersAPIClient(account, "api access token")
```
<details>
<summary>Using Java</summary>
```java
Auth0 account = new Auth0("client id", "domain");
UsersAPIClient users = new UsersAPIClient(account, "api token");
```
</details>
### Link users
```kotlin
users
.link("primary user id", "secondary user token")
.start(object: Callback<List<UserIdentity>, ManagementException> {
override fun onFailure(exception: ManagementException) { }
override fun onSuccess(identities: List<UserIdentity>) { }
})
```
<details>
<summary>Using coroutines</summary>
```kotlin
try {
val identities = users
.link("primary user id", "secondary user token")
.await()
println(identities)
} catch (e: ManagementException) {
e.printStacktrace()
}
```
</details>
<details>
<summary>Using Java</summary>
```java
users
.link("primary user id", "secondary user token")
.start(new Callback<List<UserIdentity>, ManagementException>() {
@Override
public void onSuccess(List<UserIdentity> payload) {
//Got the updated identities! Accounts linked.
}
@Override
public void onFailure(@NonNull ManagementException error) {
//Error!
}
});
```
</details>
### Unlink users
```kotlin
users
.unlink("primary user id", "secondary user id", "secondary provider")
.start(object: Callback<List<UserIdentity>, ManagementException> {
override fun onFailure(exception: ManagementException) { }
override fun onSuccess(identities: List<UserIdentity>) { }
})
```
<details>
<summary>Using coroutines</summary>
```kotlin
try {
val identities = users
.unlink("primary user id", "secondary user id", "secondary provider")
.await()
println(identities)
} catch (e: ManagementException) {
e.printStacktrace()
}
```
</details>
<details>
<summary>Using Java</summary>
```java
users
.unlink("primary user id", "secondary user id", "secondary provider")
.start(new Callback<List<UserIdentity>, ManagementException>() {
@Override
public void onSuccess(List<UserIdentity> payload) {
//Got the updated identities! Accounts linked.
}
@Override
public void onFailure(@NonNull ManagementException error) {
//Error!
}
});
```
</details>
### Get User Profile
```kotlin
users
.getProfile("user id")
.start(object: Callback<UserProfile, ManagementException> {
override fun onFailure(exception: ManagementException) { }
override fun onSuccess(identities: UserProfile) { }
})
```
<details>
<summary>Using coroutines</summary>
```kotlin
try {
val user = users
.getProfile("user id")
.await()
println(user)
} catch (e: ManagementException) {
e.printStacktrace()
}
```
</details>
<details>
<summary>Using Java</summary>
```java
users
.getProfile("user id")
.start(new Callback<UserProfile, ManagementException>() {
@Override
public void onSuccess(@Nullable UserProfile payload) {
//Profile received
}
@Override
public void onFailure(@NonNull ManagementException error) {
//Error!
}
});
```
</details>
### Update User Metadata
```kotlin
val metadata = mapOf(
"name" to listOf("My", "Name", "Is"),
"phoneNumber" to "1234567890"
)
users
.updateMetadata("user id", metadata)
.start(object: Callback<UserProfile, ManagementException> {
override fun onFailure(exception: ManagementException) { }
override fun onSuccess(identities: UserProfile) { }
})
```
<details>
<summary>Using coroutines</summary>
```kotlin
val metadata = mapOf(
"name" to listOf("My", "Name", "Is"),
"phoneNumber" to "1234567890"
)
try {
val user = users
.updateMetadata("user id", metadata)
.await()
println(user)
} catch (e: ManagementException) {
e.printStacktrace()
}
```
</details>
<details>
<summary>Using Java</summary>
```java
Map<String, Object> metadata = new HashMap<>();
metadata.put("name", Arrays.asList("My", "Name", "Is"));
metadata.put("phoneNumber", "1234567890");
users
.updateMetadata("user id", metadata)
.start(new Callback<UserProfile, ManagementException>() {
@Override
public void onSuccess(@Nullable UserProfile payload) {
//User Metadata updated
}
@Override
public void onFailure(@NonNull ManagementException error) {
//Error!
}
});
```
</details>
> In all the cases, the `user ID` parameter is the unique identifier of the auth0 account instance. i.e. in `google-oauth2|123456789` it would be the part after the '|' pipe: `123456789`.
## Token Validation
The ID token received as part of the authentication flow is should be verified following the [OpenID Connect specification](https://openid.net/specs/openid-connect-core-1_0.html).
If you are a user of Auth0 Private Cloud with ["Custom Domains"](https://auth0.com/docs/custom-domains) still on the [legacy behavior](https://auth0.com/docs/private-cloud/private-cloud-migrations/migrate-private-cloud-custom-domains#background), you need to override the expected issuer to match your Auth0 domain before starting the authentication.
The validation is done automatically for Web Authentication
```kotlin
val account = Auth0("{YOUR_CLIENT_ID}", "{YOUR_CUSTOM_DOMAIN}")
WebAuthProvider.login(account)
.withIdTokenVerificationIssuer("https://{YOUR_AUTH0_DOMAIN}/")
.start(this, callback)
```
For Authentication Client, the method `validateClaims()` has to be called to enable it.
```kotlin
val auth0 = Auth0("YOUR_CLIENT_ID", "YOUR_DOMAIN")
val client = AuthenticationAPIClient(auth0)
client
.login("{username or email}", "{password}", "{database connection name}")
.validateClaims()
.withIdTokenVerificationIssuer("https://{YOUR_AUTH0_DOMAIN}/")
.start(object : Callback<Credentials, AuthenticationException> {
override fun onSuccess(result: Credentials) { }
override fun onFailure(error: AuthenticationException) { }
})
```
<details>
<summary>Using coroutines</summary>
```kotlin
val auth0 = Auth0("YOUR_CLIENT_ID", "YOUR_DOMAIN")
val client = AuthenticationAPIClient(auth0)
try {
val credentials = client
.login("{username or email}", "{password}", "{database connection name}")
.validateClaims()
.withIdTokenVerificationIssuer("https://{YOUR_AUTH0_DOMAIN}/")
.await()
println(credentials)
} catch (e: AuthenticationException) {
e.printStacktrace()
}
```
</details>
<details>
<summary>Using Java</summary>
```java
Auth0 auth0 = new Auth0("client id", "domain");
AuthenticationAPIClient client = new AuthenticationAPIClient(account);
client
.login("{username or email}", "{password}", "{database connection name}")
.validateClaims()
.withIdTokenVerificationIssuer("https://{YOUR_AUTH0_DOMAIN}/")
.start(new Callback<Credentials, AuthenticationException>() {
@Override
public void onSuccess(@Nullable Credentials payload) {
//Logged in!
}
@Override
public void onFailure(@NonNull AuthenticationException error) {
//Error!
}
});
```
</details>
## Organizations
[Organizations](https://auth0.com/docs/organizations) is a set of features that provide better support for developers who build and maintain SaaS and Business-to-Business (B2B) applications.
Note that Organizations is currently only available to customers on our Enterprise and Startup subscription plans.
### Log in to an organization
```kotlin
WebAuthProvider.login(account)
.withOrganization(organizationIdOrName)
.start(this, callback)
```
### Accept user invitations