Authentication
Most of the features in the SDK require the SDK to be authenticated with any type of authentication token. The SDK provides several mechanism to perform authentication. The SDK will cache the authentication information until they expire or new information will be provided by a re-authentication call.
Only re-authenticate the SDK, if you have not yet authenticated the SDK or if the current authentication information are not valid anymore.
You don't need to re-authenticate the SDK after every initialization. If you want to check, if an authentication is required you can use the the modules get_current_authentication_method() method to verify, if the SDK is currently successfully authenticated with any known method.
If the return value is None , you have not yet authenticated the SDK or the existing authentication information are not valid anymore.
Too many re-authentications might result in API endpoints to rate limit the request.
- Swift
- Kotlin
let credentials = AuthCredentials(
accessToken: "OPENID ACCESS TOKEN",
refreshToken: "OPENID REFRESH TOKEN",
idToken: "OPENID ID TOKEN"
)
try manager.authentication().openidAuthenticateWithAuthCredentials(
authCredentials: credentials
)
val credentials = AuthCredentials(
accessToken = "OPENID ACCESS TOKEN",
refreshToken = "OPENID REFRESH TOKEN",
idToken = "OPENID ID TOKEN"
)
manager.authentication().openidAuthenticateWithAuthCredentials(
authCredentials = credentials
)
This method should only be used, if the regular OpenID Web Flow is not available. It only supports authentication with a username and password, while the regular OpenID Authentication might support a variety of authentication methods. This internally uses the Resource-Owner-Password-Credentials Flow specified in the OpenID standard.
- Swift
- Kotlin
try manager.authentication().openidAuthenticateWithUsernamePassword(
username: "jon.doe",
password: "my_secret"
)
manager.authentication().openidAuthenticateWithUsernamePassword(
username = "jon.doe",
password = "my_secret"
)
To redeem a Login Token minted for your client ID without a browser, see Login Token via Direct Grant.
- Swift
- Kotlin
try manager.authentication().openidAuthenticateWithAuthorizationCode(
authorizationCode: "XYZ123",
)
manager.authentication().openidAuthenticateWithAuthorizationCode(
authorizationCode = "XYZ123",
)
Supported Authentication Methods
OpenID Connect
See OpenID Connect Authentication.
Authentication with Opaque Token
In this mode, the SDK will not perform any authentication token validation and will just pass it to the endpoints which will then know how to validate it.
As the SDK internally manages authentication tokens per each user in a separate storage session, the app would need to provide a userId under which the SDK should internally store this token. This can also be any random string.
- Swift
- Kotlin
try manager.authentication().authenticateWithOpaqueToken(
userId: "user_1234",
token: "ANYTOKEN"
)
try manager.authentication().authenticateWithOpaqueToken(
userId = "user_1234",
token = "ANYTOKEN"
)
Authentication with Legacy XV Authentication
This mode is used by legacy ExpressVPN apps and uses a JWT Access Token.
Pass the refresh token as well: the SDK uses it to renew the access token when it expires. An access token that has already expired is accepted if a refresh token comes with it — the SDK refreshes first and only creates the session if the refresh succeeds.
- Swift
- Kotlin
let credentials = AuthCredentials(
accessToken: "<ACCESS TOKEN>",
refreshToken: "<REFRESH TOKEN>",
idToken: "", // not needed
)
try manager.authentication().authenticateWithXvLegacyAuthCredentials(
authCredentials: credentials
)
val credentials = AuthCredentials(
accessToken = "<ACCESS TOKEN>",
refreshToken = "<REFRESH TOKEN>",
idToken = "", // not needed
)
manager.authentication().authenticateWithXvLegacyAuthCredentials(
authCredentials = credentials
)
The SDK allows also to authenticate using the legacy XV user name and password:
- Swift
- Kotlin
try manager.authentication().authenticateWithXvLegacyUsernamePassword(
password: "my-password"
)
try manager.authentication().authenticateWithXvLegacyUsernamePassword(
password = "my-password"
)
Migrating XV legacy credentials to OpenID
An app that still holds XV legacy credentials can move the user to an OpenID session without asking them to sign in again. Pass the XV access and refresh token; the SDK refreshes an expired access token, exchanges it for a single-use Login Token and redeems that at the Identity Provider (see Login Token via Direct Grant). The OpenID client ID, redirect URI and scopes come from the SDK configuration.
- Swift
- Kotlin
let credentials = AuthCredentials(
accessToken: "<XV ACCESS TOKEN>",
refreshToken: "<XV REFRESH TOKEN>",
idToken: "" // not needed
)
try manager.authentication().convertXvLegacyCredentialsToOpenid(
authCredentials: credentials
)
val credentials = AuthCredentials(
accessToken = "<XV ACCESS TOKEN>",
refreshToken = "<XV REFRESH TOKEN>",
idToken = "" // not needed
)
manager.authentication().convertXvLegacyCredentialsToOpenid(
authCredentials = credentials
)
Nothing changes until the last step has succeeded. If the migration fails, the previous session — typically the XV legacy one — stays exactly as it was, so the app keeps working and can try again later.
| Error | When | What to do |
|---|---|---|
CredentialsInvalid | Empty access token, or no OpenID client ID configured | Fix the call or the configuration |
CredentialsMigrationFailed { desc } | The XV token is invalid, expired without a refresh token, or its refresh was refused; the Login Token or the Identity Provider refused. desc names the step | Keep the current session; do not retry in a loop |
Network, HttpWithBody (5xx) | A request could not be made, or a server error | Retry later |
Apple InApp Receipt Authentication
In this mode, you will provide an Apple InApp Receipt to authenticate the SDK using the Authentication with Opaque Token method.
SDK Methods
Getting the currently logged in User
- Swift
- Kotlin
let userProfile = try manager.authentication().getCurrentUserProfile()
val userProfile = manager.authentication().getCurrentUserProfile()
UserProfile
| Name | Type | Description |
|---|---|---|
user_id | Option<String> | Contains the user id of the currently logged in user, None, if no user is logged in |
email | Option<String> | Contains the email of the currently logged in user, None, if no user is logged in.This field is only populated when using OpenID authentication. |
authentication_method | AuthenticationMethod | Current Authentication Method being used, can be one ofNoneOpenIDLegacyXVOpaque |
Getting the last known logged in User
This method will return the last successfully authenticated User Profile.
- Swift
- Kotlin
let lastKnownProfile = try manager.authentication().getLastKnownUserProfile()
val lastKnownProfile = manager.authentication().getLastKnownUserProfile()
Replacing the in-app-purchase placeholder email
An account created through an in-app purchase has an auto-generated placeholder email
(unknown@<billing_id>.expressiap.com). Replace it in two steps, so the user proves they own the
new address:
requestEmailChange(newEmail)emails a verification code to the new address. Nothing on the account changes yet. Show a "check your inbox" screen with a code input.confirmEmailChange(activationCode)applies the change. The authentication session reports the new email at once.
To resend the code, or to correct a mistyped address, call requestEmailChange again: the
latest address is the one confirmed. A code is valid for one hour. Both calls need a signed-in
account (not a guest).
setEmailAddress is deprecated; use these two calls instead.
- Swift
- Kotlin
try manager.authentication().requestEmailChange(newEmail: email)
do {
try manager.authentication().confirmEmailChange(activationCode: code)
} catch AuthException.ExceptionDetails(source: .InvalidActivationCode) {
// Stay on the screen; offer to resend.
} catch AuthException.ExceptionDetails(source: .EmailAlreadyInUse) {
// Ask for another address.
}
manager.authentication().requestEmailChange(email)
try {
manager.authentication().confirmEmailChange(code)
} catch (e: AuthException.ExceptionDetails) {
when (e.source) {
is SdkException.InvalidActivationCode -> { /* Stay on the screen; offer to resend. */ }
is SdkException.EmailAlreadyInUse -> { /* Ask for another address. */ }
else -> throw e
}
}
Errors
Both methods throw AuthException.ExceptionDetails, like the rest of the module. Branch on its
source:
source | Code | Meaning | Suggested handling |
|---|---|---|---|
InvalidActivationCode | 404 | The code is wrong, expired or was never requested. | Stay on the code screen; offer to resend. |
EmailAlreadyInUse | 402 | Another account uses the address. On confirmation: it was taken after the code was sent. | Ask for another address. |
InvalidEmail | 403 | The server refused the address as malformed. | Ask the user to correct it. |
StepUpRequired | 55 | The session's level of assurance is below 2. | Re-authenticate the user, then retry. |
| anything else | No network, a server error, blank input, no signed-in account. | Retry if it is a network or server error. |
The C functions csdk_auth_api_request_email_change / csdk_auth_api_confirm_email_change
return these codes.
Logging out a User
This method will reset the SDK cache, including all cached tokens. This method will not logout from any OpenID Session! You need to implement OpenID Logout on the client side.
- Swift
- Kotlin
// Logout the SDK by deleting all cache files
manager.authentication().logout()
// Logout the SDK by deleting all cache files
manager.authentication().logout()