-
Notifications
You must be signed in to change notification settings - Fork 168
Expand file tree
/
Copy pathAuthenticationAPIClient.kt
More file actions
executable file
·1202 lines (1149 loc) · 50.8 KB
/
AuthenticationAPIClient.kt
File metadata and controls
executable file
·1202 lines (1149 loc) · 50.8 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.android.authentication
import android.content.Context
import androidx.annotation.VisibleForTesting
import com.auth0.android.Auth0
import com.auth0.android.Auth0Exception
import com.auth0.android.NetworkErrorException
import com.auth0.android.authentication.mfa.MfaApiClient
import com.auth0.android.dpop.DPoP
import com.auth0.android.dpop.DPoPException
import com.auth0.android.dpop.SenderConstraining
import com.auth0.android.request.AuthenticationRequest
import com.auth0.android.request.ErrorAdapter
import com.auth0.android.request.JsonAdapter
import com.auth0.android.request.ProfileRequest
import com.auth0.android.request.PublicKeyCredentials
import com.auth0.android.request.Request
import com.auth0.android.request.SignUpRequest
import com.auth0.android.request.UserData
import com.auth0.android.request.internal.BaseAuthenticationRequest
import com.auth0.android.request.internal.BaseRequest
import com.auth0.android.request.internal.GsonAdapter
import com.auth0.android.request.internal.GsonAdapter.Companion.forMap
import com.auth0.android.request.internal.GsonAdapter.Companion.forMapOf
import com.auth0.android.request.internal.GsonProvider
import com.auth0.android.request.internal.RequestFactory
import com.auth0.android.request.internal.ResponseUtils.isNetworkError
import com.auth0.android.result.Challenge
import com.auth0.android.result.Credentials
import com.auth0.android.result.DatabaseUser
import com.auth0.android.result.PasskeyChallenge
import com.auth0.android.result.PasskeyRegistrationChallenge
import com.auth0.android.result.SSOCredentials
import com.auth0.android.result.UserProfile
import com.google.gson.Gson
import okhttp3.HttpUrl.Companion.toHttpUrl
import java.io.IOException
import java.io.Reader
import java.security.PublicKey
/**
* API client for Auth0 Authentication API.
* ```
* val auth0 = Auth0.getInstance("YOUR_CLIENT_ID", "YOUR_DOMAIN")
* val client = AuthenticationAPIClient(auth0)
* ```
*
* @see [Auth API docs](https://auth0.com/docs/auth-api)
*/
public class AuthenticationAPIClient @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) internal constructor(
private val auth0: Auth0,
private val factory: RequestFactory<AuthenticationException>,
private val gson: Gson
) : SenderConstraining<AuthenticationAPIClient> {
private var dPoP: DPoP? = null
/**
* Creates a new API client instance providing Auth0 account info.
*
* Example usage:
*
* ```
* val auth0 = Auth0.getInstance("YOUR_CLIENT_ID", "YOUR_DOMAIN")
* val client = AuthenticationAPIClient(auth0)
* ```
* @param auth0 account information
*/
public constructor(auth0: Auth0) : this(
auth0,
RequestFactory<AuthenticationException>(auth0.networkingClient, createErrorAdapter()),
GsonProvider.gson
)
public val clientId: String
get() = auth0.clientId
public val baseURL: String
get() = auth0.getDomainUrl()
/**
* Enable DPoP for this client.
*/
public override fun useDPoP(context: Context): AuthenticationAPIClient {
dPoP = DPoP(context)
return this
}
/**
* Creates a new [MfaApiClient] to handle a multi-factor authentication transaction.
*
* Example usage:
* ```
* try {
* val credentials = authClient.login("user@example.com", "password").await()
* } catch (error: AuthenticationException) {
* if (error.isMultifactorRequired) {
* val mfaToken = error.mfaRequiredErrorPayload?.mfaToken
* if (mfaToken != null) {
* val mfaClient = authClient.mfaClient(mfaToken)
* // Use mfaClient to handle MFA flow
* }
* }
* }
* ```
*
* @param mfaToken The token received in the 'mfa_required' error from a login attempt.
* @return A new [MfaApiClient] instance configured for the transaction.
*/
public fun mfaClient(mfaToken: String): MfaApiClient {
return MfaApiClient(this.auth0, mfaToken)
}
/**
* Log in a user with email/username and password for a connection/realm.
* It will use the password-realm grant type for the `/oauth/token` endpoint
* The default scope used is 'openid profile email'.
*
* Example usage:
*
* ```
* client
* .login("{username or email}", "{password}", "{database connection name}")
* .validateClaims() //mandatory
* .start(object : Callback<Credentials, AuthenticationException> {
* override fun onSuccess(result: Credentials) { }
* override fun onFailure(error: AuthenticationException) { }
* })
*```
*
* @param usernameOrEmail of the user depending of the type of DB connection
* @param password of the user
* @param realmOrConnection realm to use in the authorize flow or the name of the database to authenticate with.
* @return a request to configure and start that will yield [Credentials]
*/
public fun login(
usernameOrEmail: String,
password: String,
realmOrConnection: String
): AuthenticationRequest {
val parameters = ParameterBuilder.newAuthenticationBuilder()
.set(USERNAME_KEY, usernameOrEmail)
.set(PASSWORD_KEY, password)
.setGrantType(ParameterBuilder.GRANT_TYPE_PASSWORD_REALM)
.setRealm(realmOrConnection)
.asDictionary()
return loginWithToken(parameters)
}
/**
* Log in a user with email/username and password using the password grant and the default directory.
* The default scope used is 'openid profile email'.
*
* Example usage:
*
* ```
* client.login("{username or email}", "{password}")
* .validateClaims() //mandatory
* .start(object: Callback<Credentials, AuthenticationException> {
* override fun onSuccess(result: Credentials) { }
* override fun onFailure(error: AuthenticationException) { }
* })
*```
*
* @param usernameOrEmail of the user
* @param password of the user
* @return a request to configure and start that will yield [Credentials]
*/
public fun login(usernameOrEmail: String, password: String): AuthenticationRequest {
val requestParameters = ParameterBuilder.newAuthenticationBuilder()
.set(USERNAME_KEY, usernameOrEmail)
.set(PASSWORD_KEY, password)
.setGrantType(ParameterBuilder.GRANT_TYPE_PASSWORD)
.asDictionary()
return loginWithToken(requestParameters)
}
/**
* Log in a user using the One Time Password code after they have received the 'mfa_required' error.
* The MFA token tells the server the username or email, password, and realm values sent on the first request.
*
* Requires your client to have the **MFA OTP** Grant Type enabled. See [Client Grant Types](https://auth0.com/docs/clients/client-grant-types) to learn how to enable it.
*
* Example usage:
*
*```
* client.loginWithOTP("{mfa token}", "{one time password}")
* .validateClaims() //mandatory
* .start(object : Callback<Credentials, AuthenticationException> {
* override fun onFailure(error: AuthenticationException) { }
* override fun onSuccess(result: Credentials) { }
* })
*```
*
* @param mfaToken the token received in the previous [.login] response.
* @param otp the one time password code provided by the resource owner, typically obtained from an
* MFA application such as Google Authenticator or Guardian.
* @return a request to configure and start that will yield [Credentials]
*/
@Deprecated(
message = "loginWithOTP is deprecated and will be removed in the next major version of the SDK. Use the APIs in the [com.auth0.android.authentication.mfa.MfaApiClient] class instead.",
level = DeprecationLevel.WARNING
)
public fun loginWithOTP(mfaToken: String, otp: String): AuthenticationRequest {
val parameters = ParameterBuilder.newBuilder()
.setGrantType(ParameterBuilder.GRANT_TYPE_MFA_OTP)
.set(MFA_TOKEN_KEY, mfaToken)
.set(ONE_TIME_PASSWORD_KEY, otp)
.asDictionary()
return loginWithToken(parameters)
}
/**
* Sign-in a user using passkeys.
* This should be called after the client has received the passkey challenge from the server and generated the public key response.
* The default scope used is 'openid profile email'.
*
* Requires the client to have the **Passkey** Grant Type enabled. See [Client Grant Types](https://auth0.com/docs/clients/client-grant-types)
* to learn how to enable it.
*
* Example usage:
*
* ```
* client.signinWithPasskey("{authSession}", "{authResponse}","{realm}","${organization}")
* .validateClaims() //mandatory
* .setScope("{scope}")
* .start(object: Callback<Credentials, AuthenticationException> {
* override fun onFailure(error: AuthenticationException) { }
* override fun onSuccess(result: Credentials) { }
* })
* ```
*
* @param authSession the auth session received from the server as part of the public key challenge request.
* @param authResponse the [PublicKeyCredentials] authentication response
* @param realm the connection to use. If excluded, the application will use the default connection configured in the tenant
* @param organization id of the organization to be associated with the user while signing in
* @return a request to configure and start that will yield [Credentials]
*/
public fun signinWithPasskey(
authSession: String,
authResponse: PublicKeyCredentials,
realm: String? = null,
organization: String? = null,
): AuthenticationRequest {
val params = ParameterBuilder.newBuilder().apply {
setGrantType(ParameterBuilder.GRANT_TYPE_PASSKEY)
set(AUTH_SESSION_KEY, authSession)
realm?.let { setRealm(it) }
organization?.let { set(ORGANIZATION_KEY, organization) }
}.asDictionary()
return loginWithToken(params)
.addParameter(
AUTH_RESPONSE_KEY,
Gson().toJsonTree(authResponse)
) as AuthenticationRequest
}
/**
* Sign-in a user using passkeys.
* This should be called after the client has received the passkey challenge from the server and generated the public key response.
* The default scope used is 'openid profile email'.
*
* Requires the client to have the **Passkey** Grant Type enabled. See [Client Grant Types](https://auth0.com/docs/clients/client-grant-types)
* to learn how to enable it.
*
* Example usage:
*
* ```
* client.signinWithPasskey("{authSession}", "{authResponse}","{realm}","{organization}")
* .validateClaims() //mandatory
* .setScope("{scope}")
* .start(object: Callback<Credentials, AuthenticationException> {
* override fun onFailure(error: AuthenticationException) { }
* override fun onSuccess(result: Credentials) { }
* })
* ```
*
* @param authSession the auth session received from the server as part of the public key challenge request.
* @param authResponse the public key credential authentication response in JSON string format that follows the standard webauthn json format
* @param realm the connection to use. If excluded, the application will use the default connection configured in the tenant
* @param organization id of the organization to be associated with the user while signing in
* @return a request to configure and start that will yield [Credentials]
*/
public fun signinWithPasskey(
authSession: String,
authResponse: String,
realm: String? = null,
organization: String? = null,
): AuthenticationRequest {
val publicKeyCredentials = gson.fromJson(
authResponse,
PublicKeyCredentials::class.java
)
return signinWithPasskey(authSession, publicKeyCredentials, realm, organization)
}
/**
* Sign-up a user and returns a challenge for private and public key generation.
* The default scope used is 'openid profile email'.
* Requires the client to have the **Passkey** Grant Type enabled. See [Client Grant Types](https://auth0.com/docs/clients/client-grant-types)
* to learn how to enable it.
*
* Example usage:
*
*
* ```
* client.signupWithPasskey("{userData}","{realm}","{organization}")
* .addParameter("scope","scope")
* .start(object: Callback<PasskeyRegistration, AuthenticationException> {
* override fun onSuccess(result: PasskeyRegistration) { }
* override fun onFailure(error: AuthenticationException) { }
* })
* ```
*
* @param userData user information of the client
* @param realm the connection to use. If excluded, the application will use the default connection configured in the tenant
* @param organization id of the organization to be associated with the user while signing up
* @return a request to configure and start that will yield [PasskeyRegistrationChallenge]
*/
public fun signupWithPasskey(
userData: UserData,
realm: String? = null,
organization: String? = null
): Request<PasskeyRegistrationChallenge, AuthenticationException> {
val user = gson.toJsonTree(userData)
val url = auth0.getDomainUrl().toHttpUrl().newBuilder()
.addPathSegment(PASSKEY_PATH)
.addPathSegment(REGISTER_PATH)
.build()
val params = ParameterBuilder.newBuilder().apply {
setClientId(clientId)
realm?.let { setRealm(it) }
organization?.let { set(ORGANIZATION_KEY, it) }
}.asDictionary()
val passkeyRegistrationChallengeAdapter: JsonAdapter<PasskeyRegistrationChallenge> =
GsonAdapter(
PasskeyRegistrationChallenge::class.java, gson
)
val post = factory.post(url.toString(), passkeyRegistrationChallengeAdapter)
.addParameters(params) as BaseRequest<PasskeyRegistrationChallenge, AuthenticationException>
post.addParameter(USER_PROFILE_KEY, user)
return post
}
/**
* Request for a challenge to initiate passkey login flow
* Requires the client to have the **Passkey** Grant Type enabled. See [Client Grant Types](https://auth0.com/docs/clients/client-grant-types)
* to learn how to enable it.
*
* Example usage:
*
* ```
* client.passkeyChallenge("{realm}", "{organization}")
* .start(object: Callback<PasskeyChallenge, AuthenticationException> {
* override fun onSuccess(result: PasskeyChallenge) { }
* override fun onFailure(error: AuthenticationException) { }
* })
* ```
*
* @param realm the connection to use. If excluded, the application will use the default connection configured in the tenant
* @param organization id of the organization to be associated with the user while signing in
* @return a request to configure and start that will yield [PasskeyChallenge]
*/
public fun passkeyChallenge(
realm: String? = null,
organization: String? = null
): Request<PasskeyChallenge, AuthenticationException> {
val url = auth0.getDomainUrl().toHttpUrl().newBuilder()
.addPathSegment(PASSKEY_PATH)
.addPathSegment(CHALLENGE_PATH)
.build()
val parameters = ParameterBuilder.newBuilder().apply {
setClientId(clientId)
realm?.let { setRealm(it) }
organization?.let { set(ORGANIZATION_KEY, organization) }
}.asDictionary()
val passkeyChallengeAdapter: JsonAdapter<PasskeyChallenge> = GsonAdapter(
PasskeyChallenge::class.java, gson
)
return factory.post(url.toString(), passkeyChallengeAdapter)
.addParameters(parameters)
}
/**
* Log in a user using an Out Of Band authentication code after they have received the 'mfa_required' error.
* The MFA token tells the server the username or email, password, and realm values sent on the first request.
*
* Requires your client to have the **MFA OOB** Grant Type enabled. See [Client Grant Types](https://auth0.com/docs/clients/client-grant-types) to learn how to enable it.
*
* Example usage:
*
*```
* client.loginWithOOB("{mfa token}", "{out of band code}", "{binding code}")
* .validateClaims() //mandatory
* .start(object : Callback<Credentials, AuthenticationException> {
* override fun onFailure(error: AuthenticationException) { }
* override fun onSuccess(result: Credentials) { }
* })
*```
*
* @param mfaToken the token received in the previous [.login] response.
* @param oobCode the out of band code received in the challenge response.
* @param bindingCode the code used to bind the side channel (used to deliver the challenge) with the main channel you are using to authenticate.
* This is usually an OTP-like code delivered as part of the challenge message.
* @return a request to configure and start that will yield [Credentials]
*/
@Deprecated(
message = "loginWithOOB is deprecated and will be removed in the next major version of the SDK. Use the APIs in the [com.auth0.android.authentication.mfa.MfaApiClient] class instead.",
level = DeprecationLevel.WARNING
)
public fun loginWithOOB(
mfaToken: String,
oobCode: String,
bindingCode: String? = null
): AuthenticationRequest {
val parameters = ParameterBuilder.newBuilder()
.setGrantType(ParameterBuilder.GRANT_TYPE_MFA_OOB)
.set(MFA_TOKEN_KEY, mfaToken)
.set(OUT_OF_BAND_CODE_KEY, oobCode)
.set(BINDING_CODE_KEY, bindingCode)
.asDictionary()
return loginWithToken(parameters)
}
/**
* Log in a user using a multi-factor authentication Recovery Code after they have received the 'mfa_required' error.
* The MFA token tells the server the username or email, password, and realm values sent on the first request.
*
* Requires your client to have the **MFA** Grant Type enabled. See [Client Grant Types](https://auth0.com/docs/clients/client-grant-types) to learn how to enable it.
*
* Example usage:
*
*```
* client.loginWithRecoveryCode("{mfa token}", "{recovery code}")
* .validateClaims() //mandatory
* .start(object : Callback<Credentials, AuthenticationException> {
* override fun onFailure(error: AuthenticationException) { }
* override fun onSuccess(result: Credentials) { }
* })
*```
*
* @param mfaToken the token received in the previous [.login] response.
* @param recoveryCode the recovery code provided by the end-user.
* @return a request to configure and start that will yield [Credentials]. It might also include a [recoveryCode] field,
* which your application must display to the end-user to be stored securely for future use.
*/
@Deprecated(
message = "loginWithRecoveryCode is deprecated and will be removed in the next major version of the SDK. Use the APIs in the [com.auth0.android.authentication.mfa.MfaApiClient] class instead.",
level = DeprecationLevel.WARNING
)
public fun loginWithRecoveryCode(
mfaToken: String,
recoveryCode: String
): AuthenticationRequest {
val parameters = ParameterBuilder.newBuilder()
.setGrantType(ParameterBuilder.GRANT_TYPE_MFA_RECOVERY_CODE)
.set(MFA_TOKEN_KEY, mfaToken)
.set(RECOVERY_CODE_KEY, recoveryCode)
.asDictionary()
return loginWithToken(parameters)
}
/**
* Request a challenge for multi-factor authentication (MFA) based on the challenge types supported by the application and user.
* The challenge type is how the user will get the challenge and prove possession. Supported challenge types include: "otp" and "oob".
*
* Example usage:
*
*```
* client.multifactorChallenge("{mfa token}", "{challenge type}", "{authenticator id}")
* .start(object : Callback<Challenge, AuthenticationException> {
* override fun onFailure(error: AuthenticationException) { }
* override fun onSuccess(result: Challenge) { }
* })
*```
*
* @param mfaToken the token received in the previous [.login] response.
* @param challengeType A whitespace-separated list of the challenges types accepted by your application.
* Accepted challenge types are oob or otp. Excluding this parameter means that your client application
* accepts all supported challenge types.
* @param authenticatorId The ID of the authenticator to challenge.
* @return a request to configure and start that will yield [Challenge]
*/
@Deprecated(
message = "multifactorChallenge is deprecated and will be removed in the next major version of the SDK. Use the APIs in the [com.auth0.android.authentication.mfa.MfaApiClient] class instead.",
level = DeprecationLevel.WARNING
)
public fun multifactorChallenge(
mfaToken: String,
challengeType: String? = null,
authenticatorId: String? = null
): Request<Challenge, AuthenticationException> {
val parameters = ParameterBuilder.newBuilder()
.setClientId(clientId)
.set(MFA_TOKEN_KEY, mfaToken)
.set(CHALLENGE_TYPE_KEY, challengeType)
.set(AUTHENTICATOR_ID_KEY, authenticatorId)
.asDictionary()
val url = auth0.getDomainUrl().toHttpUrl().newBuilder()
.addPathSegment(MFA_PATH)
.addPathSegment(CHALLENGE_PATH)
.build()
val challengeAdapter: JsonAdapter<Challenge> = GsonAdapter(
Challenge::class.java, gson
)
return factory.post(url.toString(), challengeAdapter)
.addParameters(parameters)
}
/**
* Log in a user using a token obtained from a Native Social Identity Provider, such as Facebook, using ['\oauth\token' endpoint](https://auth0.com/docs/api/authentication#token-exchange-for-native-social)
* The default scope used is 'openid profile email'.
*
* Example usage:
*
* ```
* client.loginWithNativeSocialToken("{subject token}", "{subject token type}")
* .validateClaims() //mandatory
* .start(object: Callback<Credentials, AuthenticationException> {
* override fun onSuccess(result: Credentials) { }
* override fun onFailure(error: AuthenticationException) { }
* })
* ```
*
* @param token the subject token, typically obtained through the Identity Provider's SDK
* @param tokenType the subject token type that is associated with this Identity Provider. e.g. 'http://auth0.com/oauth/token-type/facebook-session-access-token'
* @return a request to configure and start that will yield [Credentials]
*/
public fun loginWithNativeSocialToken(token: String, tokenType: String): AuthenticationRequest {
return tokenExchange(tokenType, token)
}
/**
* Log in a user using a phone number and a verification code received via SMS (Part of passwordless login flow)
* The default scope used is 'openid profile email'.
*
* Your Application must have the **Passwordless OTP** Grant Type enabled.
*
* Example usage:
* ```
* client.loginWithPhoneNumber("{phone number}", "{code}", "{passwordless connection name}")
* .validateClaims() //mandatory
* .start(object: Callback<Credentials, AuthenticationException> {
* override fun onSuccess(result: Credentials) { }
* override fun onFailure(error: AuthenticationException) { }
* })
* ```
*
* @param phoneNumber where the user received the verification code
* @param verificationCode sent by Auth0 via SMS
* @param realmOrConnection to end the passwordless authentication on
* @return a request to configure and start that will yield [Credentials]
*/
@JvmOverloads
public fun loginWithPhoneNumber(
phoneNumber: String,
verificationCode: String,
realmOrConnection: String = SMS_CONNECTION
): AuthenticationRequest {
val parameters = ParameterBuilder.newAuthenticationBuilder()
.setClientId(clientId)
.set(USERNAME_KEY, phoneNumber)
.setGrantType(ParameterBuilder.GRANT_TYPE_PASSWORDLESS_OTP)
.set(ONE_TIME_PASSWORD_KEY, verificationCode)
.setRealm(realmOrConnection)
.asDictionary()
return loginWithToken(parameters)
}
/**
* Log in a user using an email and a verification code received via Email (Part of passwordless login flow).
* The default scope used is 'openid profile email'.
*
* Your Application must have the **Passwordless OTP** Grant Type enabled.
*
* Example usage:
* ```
* client.loginWithEmail("{email}", "{code}", "{passwordless connection name}")
* .validateClaims() //mandatory
* .start(object: Callback<Credentials, AuthenticationException> {
* override fun onSuccess(result: Credentials) { }
* override fun onFailure(error: AuthenticationException) { }
* })
*```
*
* @param email where the user received the verification code
* @param verificationCode sent by Auth0 via Email
* @param realmOrConnection to end the passwordless authentication on
* @return a request to configure and start that will yield [Credentials]
*/
@JvmOverloads
public fun loginWithEmail(
email: String,
verificationCode: String,
realmOrConnection: String = EMAIL_CONNECTION
): AuthenticationRequest {
val parameters = ParameterBuilder.newAuthenticationBuilder()
.setClientId(clientId)
.set(USERNAME_KEY, email)
.setGrantType(ParameterBuilder.GRANT_TYPE_PASSWORDLESS_OTP)
.set(ONE_TIME_PASSWORD_KEY, verificationCode)
.setRealm(realmOrConnection)
.asDictionary()
return loginWithToken(parameters)
}
/**
* Returns the information of the user associated with the given access_token.
*
* Example usage:
* ```
* client.userInfo("{access_token}")
* .start(object: Callback<UserProfile, AuthenticationException> {
* override fun onSuccess(result: UserProfile) { }
* override fun onFailure(error: AuthenticationException) { }
* })
*```
*
* @param accessToken used to fetch it's information
* @param tokenType type of the token from [Credentials]. Defaults to Bearer.
* @return a request to start
*/
public fun userInfo(
accessToken: String, tokenType: String = "Bearer"
): Request<UserProfile, AuthenticationException> {
return profileRequest()
.addHeader(HEADER_AUTHORIZATION, "$tokenType $accessToken")
}
/**
* Creates a user in a DB connection using ['/dbconnections/signup' endpoint](https://auth0.com/docs/api/authentication#signup)
*
* Example usage:
* ```
* client.createUser("{email}", "{password}", "{username}", "{database connection name}")
* .start(object: Callback<DatabaseUser, AuthenticationException> {
* override fun onSuccess(result: DatabaseUser) { }
* override fun onFailure(error: AuthenticationException) { }
* })
* ```
*
* @param email of the user and must be non null
* @param password of the user and must be non null
* @param username of the user and must be non null
* @param connection of the database to create the user on
* @param userMetadata to set upon creation of the user
* @return a request to start
*/
@JvmOverloads
public fun createUser(
email: String,
password: String,
username: String? = null,
connection: String,
userMetadata: Map<String, String>? = null
): Request<DatabaseUser, AuthenticationException> {
val url = auth0.getDomainUrl().toHttpUrl().newBuilder()
.addPathSegment(DB_CONNECTIONS_PATH)
.addPathSegment(SIGN_UP_PATH)
.build()
val parameters = ParameterBuilder.newBuilder()
.set(USERNAME_KEY, username)
.set(EMAIL_KEY, email)
.set(PASSWORD_KEY, password)
.setConnection(connection)
.setClientId(clientId)
.asDictionary()
val databaseUserAdapter: JsonAdapter<DatabaseUser> = GsonAdapter(
DatabaseUser::class.java, gson
)
val post = factory.post(url.toString(), databaseUserAdapter)
.addParameters(parameters) as BaseRequest<DatabaseUser, AuthenticationException>
userMetadata?.let { post.addParameter(USER_METADATA_KEY, userMetadata) }
return post
}
/**
* Creates a user in a DB connection using ['/dbconnections/signup' endpoint](https://auth0.com/docs/api/authentication#signup)
* and then logs in the user.
* The default scope used is 'openid profile email'.
*
* Example usage:
*
* ```
* client.signUp("{email}", "{password}", "{username}", "{database connection name}")
* .validateClaims() //mandatory
* .start(object: Callback<Credentials, AuthenticationException> {
* override fun onSuccess(result: Credentials) { }
* override fun onFailure(error: AuthenticationException) { }
* })
*```
*
* @param email of the user and must be non null
* @param password of the user and must be non null
* @param username of the user and must be non null
* @param connection of the database to sign up with
* @param userMetadata to set upon creation of the user
* @return a request to configure and start that will yield [Credentials]
*/
@JvmOverloads
public fun signUp(
email: String,
password: String,
username: String? = null,
connection: String,
userMetadata: Map<String, String>? = null
): SignUpRequest {
val createUserRequest = createUser(email, password, username, connection, userMetadata)
val authenticationRequest = login(email, password, connection)
return SignUpRequest(createUserRequest, authenticationRequest)
}
/**
* Request a reset password using ['/dbconnections/change_password'](https://auth0.com/docs/api/authentication#change-password)
*
* Example usage:
*
* ```
* client.resetPassword("{email}", "{database connection name}")
* .start(object: Callback<Void?, AuthenticationException> {
* override fun onSuccess(result: Void?) { }
* override fun onFailure(error: AuthenticationException) { }
* })
* ```
*
* @param email of the user to request the password reset. An email will be sent with the reset instructions.
* @param connection of the database to request the reset password on
* @return a request to configure and start
*/
public fun resetPassword(
email: String,
connection: String
): Request<Void?, AuthenticationException> {
val url = auth0.getDomainUrl().toHttpUrl().newBuilder()
.addPathSegment(DB_CONNECTIONS_PATH)
.addPathSegment(CHANGE_PASSWORD_PATH)
.build()
val parameters = ParameterBuilder.newBuilder()
.set(EMAIL_KEY, email)
.setClientId(clientId)
.setConnection(connection)
.asDictionary()
return factory.post(url.toString())
.addParameters(parameters)
}
/**
* Request the revoke of a given refresh_token. Once revoked, the refresh_token cannot be used to obtain new tokens.
* Your Auth0 Application Type should be set to 'Native' and Token Endpoint Authentication Method must be set to 'None'.
*
* Example usage:
*
* ```
* client.revokeToken("{refresh_token}")
* .start(object: Callback<Void?, AuthenticationException> {
* override fun onSuccess(result: Void?) { }
* override fun onFailure(error: AuthenticationException) { }
* })
* ```
*
* @param refreshToken the token to revoke
* @return a request to start
*/
public fun revokeToken(refreshToken: String): Request<Void?, AuthenticationException> {
val parameters = ParameterBuilder.newBuilder()
.setClientId(clientId)
.set(TOKEN_KEY, refreshToken)
.asDictionary()
val url = auth0.getDomainUrl().toHttpUrl().newBuilder()
.addPathSegment(OAUTH_PATH)
.addPathSegment(REVOKE_PATH)
.build()
return factory.post(url.toString())
.addParameters(parameters)
}
/**
* The Custom Token Exchange feature allows clients to exchange their existing tokens for Auth0 tokens by calling the `/oauth/token` endpoint with specific parameters.
* The default scope used is 'openid profile email'.
*
* Example usage:
*
* ```
* client.customTokenExchange("{subject token type}", "{subject token}")
* .validateClaims() //mandatory
* .setScope("{scope}")
* .setAudience("{audience}")
* .start(object: Callback<Credentials, AuthenticationException> {
* override fun onSuccess(result: Credentials) { }
* override fun onFailure(error: AuthenticationException) { }
* })
* ```
*
* @param subjectTokenType the subject token type that is associated with the existing Identity Provider. e.g. 'http://acme.com/legacy-token'
* @param subjectToken the subject token, typically obtained through the Identity Provider's SDK
* @param organization id of the organization the user belongs to
* @return a request to configure and start that will yield [Credentials]
*/
public fun customTokenExchange(
subjectTokenType: String,
subjectToken: String,
organization: String? = null
): AuthenticationRequest {
return tokenExchange(subjectTokenType, subjectToken, organization)
}
/**
* Requests new Credentials using a valid Refresh Token. You can request credentials for a specific API by passing its audience value. The default scopes
* configured for the API will be granted if you don't request any specific scopes.
*
*
* This method will use the /oauth/token endpoint with the 'refresh_token' grant, and the response will include an id_token and an access_token if 'openid' scope was requested when the refresh_token was obtained.
* Additionally, if the application has Refresh Token Rotation configured, a new one-time use refresh token will also be included in the response.
*
* The scope of the newly received Access Token can be reduced sending the scope parameter with this request.
*
* Example usage:
* ```
* client.renewAuth("{refresh_token}","{audience}","{scope})
* .start(object: Callback<Credentials, AuthenticationException> {
* override fun onSuccess(result: Credentials) { }
* override fun onFailure(error: AuthenticationException) { }
* })
* ```
*
* @param refreshToken used to fetch the new Credentials.
* @param audience Identifier of the API that your application is requesting access to. Defaults to null.
* @param scope Space-separated list of scope values to request. Defaults to null.
* @return a request to start
*/
public fun renewAuth(
refreshToken: String,
audience: String? = null,
scope: String? = null
): Request<Credentials, AuthenticationException> {
val parameters = ParameterBuilder.newBuilder()
.setClientId(clientId)
.setRefreshToken(refreshToken)
.setGrantType(ParameterBuilder.GRANT_TYPE_REFRESH_TOKEN)
.apply {
audience?.let {
setAudience(it)
}
scope?.let {
setScope(it)
}
}
.asDictionary()
val url = auth0.getDomainUrl().toHttpUrl().newBuilder()
.addPathSegment(OAUTH_PATH)
.addPathSegment(TOKEN_PATH)
.build()
val credentialsAdapter = GsonAdapter(
Credentials::class.java, gson
)
val request = factory.post(url.toString(), credentialsAdapter, dPoP)
.addParameters(parameters)
return request
}
/**
* Start a passwordless flow with an [Email](https://auth0.com/docs/api/authentication#get-code-or-link).
*
* Your Application must have the **Passwordless OTP** Grant Type enabled.
*
* Example usage:
* ```
* client.passwordlessWithEmail("{email}", PasswordlessType.CODE, "{passwordless connection name}")
* .start(object: Callback<Void?, AuthenticationException> {
* override onSuccess(result: Void?) { }
* override onFailure(error: AuthenticationException) { }
* })
* ```
*
* @param email that will receive a verification code to use for login
* @param passwordlessType indicate whether the email should contain a code, link or magic link (android & iOS)
* @param connection the passwordless connection to start the flow with.
* @return a request to configure and start
*/
@JvmOverloads
public fun passwordlessWithEmail(
email: String,
passwordlessType: PasswordlessType,
connection: String = EMAIL_CONNECTION
): Request<Void?, AuthenticationException> {
val parameters = ParameterBuilder.newBuilder()
.set(EMAIL_KEY, email)
.setSend(passwordlessType)
.setConnection(connection)
.asDictionary()
return passwordless()
.addParameters(parameters)
}
/**
* Start a passwordless flow with a [SMS](https://auth0.com/docs/api/authentication#get-code-or-link)
*
* Your Application requires to have the **Passwordless OTP** Grant Type enabled.
*
* Example usage:
* ```
* client.passwordlessWithSms("{phone number}", PasswordlessType.CODE, "{passwordless connection name}")
* .start(object: Callback<Void?, AuthenticationException> {
* override fun onSuccess(result: Void?) { }
* override fun onFailure(error: AuthenticationException) { }
* })
* ```
*
* @param phoneNumber where an SMS with a verification code will be sent
* @param passwordlessType indicate whether the SMS should contain a code, link or magic link (android & iOS)
* @param connection the passwordless connection to start the flow with.
* @return a request to configure and start
*/
@JvmOverloads
public fun passwordlessWithSMS(
phoneNumber: String,
passwordlessType: PasswordlessType,
connection: String = SMS_CONNECTION
): Request<Void?, AuthenticationException> {
val parameters = ParameterBuilder.newBuilder()
.set(PHONE_NUMBER_KEY, phoneNumber)
.setSend(passwordlessType)
.setConnection(connection)
.asDictionary()
return passwordless()
.addParameters(parameters)
}
/**
* Start a custom passwordless flow
*
* @return a request to configure and start
*/
private fun passwordless(): Request<Void?, AuthenticationException> {
val url = auth0.getDomainUrl().toHttpUrl().newBuilder()
.addPathSegment(PASSWORDLESS_PATH)
.addPathSegment(START_PATH)
.build()
val parameters = ParameterBuilder.newBuilder()
.setClientId(clientId)
.asDictionary()
return factory.post(url.toString())
.addParameters(parameters)
}
/**
* Fetch the user's profile after it's authenticated by a login request.
* If the login request fails, the returned request will fail
*
* @param authenticationRequest that will authenticate a user with Auth0 and return a [Credentials]
* @return a [ProfileRequest] that first logs in and then fetches the profile
*/
public fun getProfileAfter(authenticationRequest: AuthenticationRequest): ProfileRequest {
return ProfileRequest(authenticationRequest, profileRequest())
}
/**
* Fetch the token information from Auth0, using the authorization_code grant type
* The authorization code received from the Auth0 server and the code verifier used
* to generate the challenge sent to the /authorize call must be provided.
*
* Example usage:
*
* ```
* client
* .token("authorization code", "code verifier", "redirect_uri")
* .start(object: Callback<Credentials, AuthenticationException> {...})
* ```
*
* @param authorizationCode the authorization code received from the /authorize call.
* @param codeVerifier the code verifier used to generate the code challenge sent to /authorize.
* @param redirectUri the uri sent to /authorize as the 'redirect_uri'.
* @return a request to obtain access_token by exchanging an authorization code.
*/
public fun token(
authorizationCode: String,
codeVerifier: String,
redirectUri: String
): Request<Credentials, AuthenticationException> {
val parameters = ParameterBuilder.newBuilder()
.setClientId(clientId)
.setGrantType(ParameterBuilder.GRANT_TYPE_AUTHORIZATION_CODE)
.set(OAUTH_CODE_KEY, authorizationCode).set(REDIRECT_URI_KEY, redirectUri)
.set("code_verifier", codeVerifier)
.asDictionary()
val url = auth0.getDomainUrl().toHttpUrl().newBuilder()
.addPathSegment(OAUTH_PATH)
.addPathSegment(TOKEN_PATH)
.build()
val credentialsAdapter: JsonAdapter<Credentials> = GsonAdapter(