Note As part of our ongoing commitment to best security practices, we have rotated the signing keys used to sign previous releases of this SDK. As a result, new patch builds have been released using the new signing key. Please upgrade at your earliest convenience.
While this change won't affect most developers, if you have implemented a dependency signature validation step in your build process, you may notice a warning that past releases can't be verified. This is expected, and a result of the key rotation process. Updating to the latest version will resolve this for you.
📚 Documentation • 🚀 Getting Started • 💬 Feedback
Android API version 31 or later and Java 8+.
:warning: Applications targeting Android SDK version 30 (
targetSdkVersion = 30
) and below should use version 2.9.0.
Here’s what you need in build.gradle
to target Java 8 byte code for Android and Kotlin plugins respectively.
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
To install Auth0.Android with Gradle, simply add the following line to your build.gradle
file:
dependencies {
implementation 'com.auth0.android:auth0:3.2.0'
}
Open your app's AndroidManifest.xml
file and add the following permission.
<uses-permission android:name="android.permission.INTERNET" />
First, create an instance of Auth0
with your Application information
val account = Auth0.getInstance("{YOUR_CLIENT_ID}", "{YOUR_DOMAIN}")
First go to the Auth0 Dashboard and go to your application's settings. Make sure you have in Allowed Callback URLs a URL with the following format:
https://{YOUR_AUTH0_DOMAIN}/android/{YOUR_APP_PACKAGE_NAME}/callback
⚠️ Make sure that the application type of the Auth0 application is Native.
Replace {YOUR_APP_PACKAGE_NAME}
with your actual application's package name, available in your app/build.gradle
file as the applicationId
value.
Next, define the Manifest Placeholders for the Auth0 Domain and Scheme which are going to be used internally by the library to register an intent-filter. Go to your application's build.gradle
file and add the manifestPlaceholders
line as shown below:
apply plugin: 'com.android.application'
android {
compileSdkVersion 30
defaultConfig {
applicationId "com.auth0.samples"
minSdkVersion 21
targetSdkVersion 30
//...
//---> Add the next line
manifestPlaceholders = [auth0Domain: "@string/com_auth0_domain", auth0Scheme: "https"]
//<---
}
//...
}
It's a good practice to define reusable resources like @string/com_auth0_domain
, but you can also hard-code the value.
The scheme value can be either
https
or a custom one. Read this section to learn more.
Declare the callback instance that will receive the authentication result and authenticate by showing the Auth0 Universal Login:
val callback = object : Callback<Credentials, AuthenticationException> {
override fun onFailure(exception: AuthenticationException) {
// Failure! Check the exception for details
}
override fun onSuccess(credentials: Credentials) {
// Success! Access token and ID token are presents
}
}
WebAuthProvider.login(account)
.start(this, callback)
The callback will get invoked when the user returns to your application. There are a few scenarios where this may fail:
error.isBrowserAppNotAvailable
.error.isAuthenticationCanceled
.If the
redirect
URL is not found in the Allowed Callback URLs of your Auth0 Application, the server will not make the redirection and the browser will remain open.
If you followed the configuration steps documented here, you may have noticed the default scheme used for the Callback URI is https
. This works best for Android API 23 or newer if you're using Android App Links, but in previous Android versions this may show the intent chooser dialog prompting the user to choose either your application or the browser. You can change this behaviour by using a custom unique scheme so that the OS opens directly the link with your app.
auth0Scheme
Manifest Placeholder on the app/build.gradle
file or update the intent-filter declaration in the AndroidManifest.xml
to use the new scheme.withScheme()
in the WebAuthProvider
builder passing the custom scheme you want to use.WebAuthProvider.login(account)
.withScheme("myapp")
.start(this, callback)
Note that the schemes can only have lowercase letters.
To log the user out and clear the SSO cookies that the Auth0 Server keeps attached to your browser app, you need to call the logout endpoint. This can be done in a similar fashion to how you authenticated before: using the WebAuthProvider
class.
Make sure to revisit this section to configure the Manifest Placeholders if you still cannot authenticate successfully. The values set there are used to generate the URL that the server will redirect the user back to after a successful log out.
In order for this redirection to happen, you must copy the Allowed Callback URLs value you added for authentication into the Allowed Logout URLs field in your application settings. Both fields should have an URL with the following format:
https://{YOUR_AUTH0_DOMAIN}/android/{YOUR_APP_PACKAGE_NAME}/callback
Remember to replace {YOUR_APP_PACKAGE_NAME}
with your actual application's package name, available in your app/build.gradle
file as the applicationId
value.
Initialize the provider, this time calling the static method logout
.
//Declare the callback that will receive the result
val logoutCallback = object: Callback<Void?, AuthenticationException> {
override fun onFailure(exception: AuthenticationException) {
// Failure! Check the exception for details
}
override fun onSuccess(result: Void?) {
// Success! The browser session was cleared
}
}
//Configure and launch the log out
WebAuthProvider.logout(account)
.start(this, logoutCallback)
The callback will get invoked when the user returns to your application. There are a few scenarios where this may fail:
error.isBrowserAppNotAvailable
.error.isAuthenticationCanceled
.If the returnTo
URL is not found in the Allowed Logout URLs of your Auth0 Application, the server will not make the redirection and the browser will remain open.
⚠️ 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 use this feature, there are some additional steps you must take:
keytool -printcert -jarfile sample-debug.apk
Once the above prerequisites are met, you can call your login method as shown below to open your web authentication in Trusted Web Activity.
WebAuthProvider.login(account)
.withTrustedWebActivity()
.await(this)
This library ships with two additional classes that help you manage the Credentials received during authentication.
The basic version supports asking for Credentials
existence, storing them and getting them back. If the credentials have expired and a refresh_token was saved, they are automatically refreshed. The class is called CredentialsManager
.
AuthenticationAPIClient
instance to renew the credentials when they expire and a Storage
object. We provide a SharedPreferencesStorage
class that makes use of SharedPreferences
to create a file in the application's directory with Context.MODE_PRIVATE mode.val authentication = AuthenticationAPIClient(account)
val storage = SharedPreferencesStorage(this)
val manager = CredentialsManager(authentication, storage)
expires_at
and at least an access_token
or id_token
value. If one of the values is missing when trying to set the credentials, the method will throw a CredentialsManagerException
. If you want the manager to successfully renew the credentials when expired you must also request the offline_access
scope when logging in in order to receive a refresh_token
value along with the rest of the tokens. i.e. Logging in with a database connection and saving the credentials:authentication
.login("info@auth0.com", "a secret password", "my-database-connection")
.setScope("openid email profile offline_access")
.start(object : Callback<Credentials, AuthenticationException> {
override fun onFailure(exception: AuthenticationException) {
// Error
}
override fun onSuccess(credentials: Credentials) {
//Save the credentials
manager.saveCredentials(credentials)
}
})
Note: This method has been made thread-safe after version 2.8.0.
hasValidCredentials
method that can let you know in advance if a non-expired token is available without making an additional network call. The same rules of the getCredentials
method apply:val authenticated = manager.hasValidCredentials()
refresh_token
will be used to attempt to renew them. If the expires_at
or both the access_token
and id_token
values are missing, the method will throw a CredentialsManagerException
. The same will happen if the credentials have expired and there's no refresh_token
available.manager.getCredentials(object : Callback<Credentials, CredentialsManagerException> {
override fun onFailure(exception: CredentialsManagerException) {
// Error
}
override fun onSuccess(credentials: Credentials) {
// Use the credentials
}
})
Note: In the scenario where the stored credentials have expired and a refresh_token
is available, the newly obtained tokens are automatically saved for you by the Credentials Manager. This method has been made thread-safe after version 2.8.0.
manager.clearCredentials()
We appreciate feedback and contribution to this repo! Before you get started, please see the following:
To provide feedback or report a bug, please raise an issue on our issue tracker.
Please do not report security vulnerabilities on the public Github issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.
Auth0 is an easy to implement, adaptable authentication and authorization platform. To learn more checkout Why Auth0?
This project is licensed under the MIT license. See the LICENSE file for more info.