• Stars
    star
    171
  • Rank 215,210 (Top 5 %)
  • Language
    Kotlin
  • License
    MIT License
  • Created almost 8 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Android toolkit for Auth0 API

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.

Auth0.Android

Maven Central Coverage Status CircleCI License javadoc

๐Ÿ“š Documentation โ€ข ๐Ÿš€ Getting Started โ€ข ๐Ÿ’ฌ Feedback

Documentation

Getting Started

Requirements

Android API version 31 or later and Java 8+.

โš ๏ธ Applications targeting Android SDK version 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'
    }
}

Installation

To install Auth0.Android with Gradle, simply add the following line to your build.gradle file:

dependencies {
    implementation 'com.auth0.android:auth0:2.9.3'
}

Permissions

Open your app's AndroidManifest.xml file and add the following permission.

<uses-permission android:name="android.permission.INTERNET" />

Configure the SDK

First, create an instance of Auth0 with your Application information

val account = Auth0("{YOUR_CLIENT_ID}", "{YOUR_DOMAIN}")
Using Java
Auth0 account = new Auth0("{YOUR_CLIENT_ID}", "{YOUR_DOMAIN}");
Configure using Android Context

Alternatively, you can save your Application information in the strings.xml file using the following names:

<resources>
    <string name="com_auth0_client_id">YOUR_CLIENT_ID</string>
    <string name="com_auth0_domain">YOUR_DOMAIN</string>
</resources>

You can then create a new Auth0 instance by passing an Android Context:

val account = Auth0(context)

Authentication with Universal Login

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)
Using coroutines
try {
    val credentials = WebAuthProvider.login(account)
        .await(requireContext())
    println(credentials)    
} catch(e: AuthenticationException) {
    e.printStacktrace()
}
Using Java
Callback<Credentials, AuthenticationException> callback = new Callback<Credentials, AuthenticationException>() {
    @Override
    public void onFailure(@NonNull AuthenticationException exception) {
        //failed with an exception
    }

    @Override
    public void onSuccess(@Nullable Credentials credentials) {
        //succeeded!
    }
};

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:

  • When the device cannot open the URL because it doesn't have any compatible browser application installed. You can check this scenario with error.isBrowserAppNotAvailable.
  • When the user manually closed the browser (e.g. pressing the back key). You can check this scenario with error.isAuthenticationCanceled.
  • When there was a server error. Check the received exception for details.

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.

A note about App Deep Linking:

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.

  1. Update the auth0Scheme Manifest Placeholder on the app/build.gradle file or update the intent-filter declaration in the AndroidManifest.xml to use the new scheme.
  2. Update the Allowed Callback URLs in your Auth0 Dashboard application's settings.
  3. Call 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.

Clearing the session

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)
Using coroutines
try {
    WebAuthProvider.logout(account)
        .await(requireContext())
    println("Logged out")
} catch(e: AuthenticationException) {
    e.printStacktrace()
}
Using Java
//Declare the callback that will receive the result
Callback<Void, AuthenticationException> logoutCallback = new Callback<Void, AuthenticationException>() {
    @Override
    public void onFailure(@NonNull Auth0Exception exception) {
        //failed with an exception
    }

    @Override
    public void onSuccess(@Nullable Void payload) {
        //succeeded!
    }
};

//Configure and launch the log out
WebAuthProvider.logout(account)
    .start(MainActivity.this, logoutCallback);

The callback will get invoked when the user returns to your application. There are a few scenarios where this may fail:

  • When the device cannot open the URL because it doesn't have any compatible browser application installed. You can check this scenario with error.isBrowserAppNotAvailable.
  • When the user manually closed the browser (e.g. pressing the back key). You can check this scenario with 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.

Credentials Manager

This library ships with two additional classes that help you manage the Credentials received during authentication.

Basic

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.

Usage

  1. Instantiate the manager: You'll need an 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)
Using Java
AuthenticationAPIClient authentication = new AuthenticationAPIClient(account);
Storage storage = new SharedPreferencesStorage(this);
CredentialsManager manager = new CredentialsManager(authentication, storage);
  1. Save credentials: The credentials to save must have 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("[email protected]", "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)
        }
    })
Using coroutines
try {
    val credentials = authentication
        .login("[email protected]", "a secret password", "my-database-connection")
        .setScope("openid email profile offline_access")
        .await()
    manager.saveCredentials(credentials)
} catch (e: AuthenticationException) {
    e.printStacktrace()
}
Using Java
authentication
    .login("[email protected]", "a secret password", "my-database-connection")
    .setScope("openid email profile offline_access")
    .start(new BaseCallback<Credentials, AuthenticationException>() {
        @Override
        public void onSuccess(Credentials payload) {
            //Save the credentials
            manager.saveCredentials(credentials);
        }

        @Override
        public void onFailure(AuthenticationException error) {
            //Error!
        }
    });

Note: This method has been made thread-safe after version 2.8.0.

  1. Check credentials existence: There are cases were you just want to check if a user session is still valid (i.e. to know if you should present the login screen or the main screen). For convenience, we include a 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()
Using Java
boolean authenticated = manager.hasValidCredentials();
  1. Retrieve credentials: Existing credentials will be returned if they are still valid, otherwise the 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
    }
})
Using coroutines
try {
    val credentials = manager.awaitCredentials()
    println(credentials)
} catch (e: CredentialsManagerException) {
    e.printStacktrace()
}
Using Java
manager.getCredentials(new BaseCallback<Credentials, CredentialsManagerException>() {
    @Override
    public void onSuccess(Credentials credentials){
        //Use the Credentials
    }

    @Override
    public void onFailure(CredentialsManagerException error){
        //Error!
    }
});

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.

  1. Clear credentials: When you want to log the user out:
manager.clearCredentials()

Feedback

Contributing

We appreciate feedback and contribution to this repo! Before you get started, please see the following:

Raise an issue

To provide feedback or report a bug, please raise an issue on our issue tracker.

Vulnerability Reporting

Please do not report security vulnerabilities on the public Github issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.


Auth0 Logo

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.

More Repositories

1

node-jsonwebtoken

JsonWebToken implementation for node.js http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html
JavaScript
17,054
star
2

java-jwt

Java implementation of JSON Web Token (JWT)
Java
5,403
star
3

express-jwt

connect/express middleware that validates a JsonWebToken (JWT) and set the req.user with the attributes
TypeScript
4,396
star
4

jwt-decode

Decode JWT tokens; useful for browser applications.
JavaScript
2,913
star
5

angular2-jwt

Helper library for handling JWTs in Angular apps
TypeScript
2,606
star
6

nextjs-auth0

Next.js SDK for signing in with Auth0
TypeScript
1,903
star
7

angular-jwt

Library to help you work with JWTs on AngularJS
JavaScript
1,259
star
8

lock

Auth0's signin solution
JavaScript
1,121
star
9

go-jwt-middleware

A Middleware for Go Programming Language to check for JWTs on HTTP requests
Go
978
star
10

auth0.js

Auth0 headless browser sdk
JavaScript
949
star
11

auth0-spa-js

Auth0 authentication for Single Page Applications (SPA) with PKCE
TypeScript
873
star
12

auth0-react

Auth0 SDK for React Single Page Applications (SPA)
TypeScript
820
star
13

node-jwks-rsa

A library to retrieve RSA public keys from a JWKS (JSON Web Key Set) endpoint.
JavaScript
767
star
14

node-jws

JSON Web Signatures
JavaScript
698
star
15

angular-storage

A storage library for AngularJS done right
JavaScript
644
star
16

repo-supervisor

Scan your code for security misconfiguration, search for passwords and secrets. ๐Ÿ”
JavaScript
632
star
17

node-auth0

Node.js client library for the Auth0 platform.
JavaScript
586
star
18

cosmos

๐Ÿ”ญ Auth0 Design System
JavaScript
545
star
19

JWTDecode.swift

A JWT decoder for iOS, macOS, tvOS, and watchOS
Swift
545
star
20

nginx-jwt

Lua script for Nginx that performs reverse proxy auth using JWT's
JavaScript
534
star
21

SimpleKeychain

A simple Keychain wrapper for iOS, macOS, tvOS, and watchOS
Swift
488
star
22

auth0-python

Auth0 SDK for Python
Python
445
star
23

express-openid-connect

An Express.js middleware to protect OpenID Connect web applications.
JavaScript
434
star
24

react-native-auth0

React Native toolkit for Auth0 API
JavaScript
432
star
25

JWTDecode.Android

A library to help you decode JWTs for Android
Java
428
star
26

docs

Auth0 documentation
JavaScript
364
star
27

auth0-PHP

PHP SDK for Auth0 Authentication and Management APIs.
PHP
355
star
28

wt-cli

Webtask CLI - all you need is code
JavaScript
322
star
29

auth0.net

.NET client for the Auth0 Authentication & Management APIs.
C#
296
star
30

passport-auth0

Auth0 authentication strategy for Passport.js
JavaScript
283
star
31

rules

Rules are code snippets written in JavaScript that are executed as part of the authentication pipeline in Auth0
JavaScript
283
star
32

react-native-lock

[DEPRECATED] A wrapper of Lock to use with React Native (iOS & Android)
Java
277
star
33

Auth0.swift

Auth0 SDK for Apple platforms
Swift
275
star
34

auth0-java

Java client library for the Auth0 platform
Java
265
star
35

Lock.swift

A Swift & iOS framework to authenticate using Auth0 and with a Native Look & Feel
Swift
251
star
36

auth0-cli

Build, manage and test your Auth0 integrations from the command line
Go
232
star
37

auth0-deploy-cli

The Auth0 Deploy CLI is a tool that helps you manage your Auth0 tenant configuration. It integrates into your development workflows as a standalone CLI or as a node module.
JavaScript
231
star
38

laravel-auth0

Laravel SDK for Auth0 Authentication and Management APIs.
PHP
224
star
39

ruby-auth0

Ruby toolkit for Auth0 API
Ruby
189
star
40

cxn

cXn: extensible open-source CDN
Ruby
178
star
41

jwks-rsa-java

Java
178
star
42

passport-windowsauth

Windows Authentication strategy for Passport.js
JavaScript
175
star
43

auth0-angular

Auth0 SDK for Angular Single Page Applications
TypeScript
167
star
44

styleguide

๐Ÿ–Œ Conjunction of design patterns, components and resources used across our products.
Stylus
160
star
45

terraform-provider-auth0

The Auth0 Terraform Provider is the official plugin for managing Auth0 tenant configuration through the Terraform tool.
Go
155
star
46

Lock.Android

Android Library to authenticate using Auth0 and with a Native Look & Feel
Java
140
star
47

jwt-handbook-samples

JWT Handbook code samples
JavaScript
139
star
48

wordpress

WordPress Plugin for Auth0 Authentication
PHP
133
star
49

node-samlp

SAML Protocol support for node (only IdP for now)
JavaScript
129
star
50

passport-linkedin-oauth2

Passport Strategy for LinkedIn OAuth 2.0
JavaScript
115
star
51

omniauth-auth0

OmniAuth strategy to login with Auth0
Ruby
112
star
52

symfony

Symfony SDK for Auth0 Authentication and Management APIs.
PHP
110
star
53

go-auth0

Go SDK for the Auth0 Management API.
Go
107
star
54

node-odata-parser

OData query string parser for node.js.
JavaScript
106
star
55

node-jwa

JSON Web Algorithms
JavaScript
98
star
56

auth0-vue

Auth0 authentication SDK for Vue.js apps
TypeScript
95
star
57

lock-passwordless

Auth0 Lock Passwordless [DEPRECATED]
JavaScript
93
star
58

express-jwt-authz

Validate the JWT scope to authorize access to an endpoint
JavaScript
93
star
59

auth0-angular2

84
star
60

auth0-aspnetcore-authentication

SDK for integrating Auth0 in ASPNET Core
C#
82
star
61

open-source-template

A template for open source projects at Auth0
81
star
62

auth0-authorization-extension

Auth0 Extension that adds authorization features to your account
JavaScript
81
star
63

react-browserify-spa-seed

Seed / Boilerplate project to create your own SPA using React, Browserify and ReworkCSS
JavaScript
80
star
64

node-baas

Node.js implementation of Bcrypt as a micro service.
JavaScript
79
star
65

password-sheriff

Password policies made easy.
JavaScript
77
star
66

sharelock-android

Sharelock Android app
Java
76
star
67

auth0-oidc-client-net

OIDC Client for .NET Desktop and Mobile applications
C#
75
star
68

node-oauth2-jwt-bearer

Monorepo for libraries that protect Node APIs with OAuth2 Bearer JWTs
TypeScript
75
star
69

idtoken-verifier

Lightweight RSA JWT verification
JavaScript
73
star
70

ad-ldap-connector

Auth0 AD and LDAP connector
JavaScript
70
star
71

nodejs-msi

Build an MSI Windows Installer for a node.js application using WIX Toolset.
PowerShell
70
star
72

auth0-spring-security-api

Spring Security integration with Auth0 to secure your API with JWTs
Java
70
star
73

id-generator

Generates random ids with a prefix (a la Stripe)
JavaScript
66
star
74

node-saml

SAML assertion creation for node
JavaScript
65
star
75

webtask-scripts

JavaScript
61
star
76

TouchIDAuth

A library for passwordless authentication using TouchID & JWT
Objective-C
60
star
77

passport-azure-ad-oauth2

OAuth 2.0 authentication Passport strategies for Windows Azure Active Directory
JavaScript
59
star
78

spa-pkce

JavaScript
58
star
79

discourse-plugin

Discourse plugin to authenticate with auth0.
Ruby
58
star
80

auth0-multitenant-spa-api-sample

JQuery SPA + Node.js API with multi-tenant support
JavaScript
58
star
81

sandboxjs

Sandbox node.js code like a boss
JavaScript
58
star
82

multitenant-jwt-auth

This sample shows how to implement an API that authenticates using JWTs. It supports mutiple tenants and JWT blacklisting.
JavaScript
54
star
83

coreos-mongodb

CoreOS MongoDB units
52
star
84

shiny-auth0

Auth0 shiny proxy
JavaScript
51
star
85

auth0-flutter

Auth0 SDK for Flutter
Dart
49
star
86

auth0-cordova

Auth0 integration for Cordova apps
JavaScript
49
star
87

sharelock-osx

Swift
47
star
88

disyuntor

A circuit-breaker implementation for node.js
TypeScript
47
star
89

passport-wsfed-saml2

passport strategy for both WS-fed and SAML2 protocol
JavaScript
47
star
90

php-jwt-example

Php JWT example.
PHP
46
star
91

auth0-aspnet-owin

Auth0 ASP.NET 4.5 Owin/Katana Authentication Handler
JavaScript
46
star
92

webauthn.me

webauthn.me, learn more about the Web Authentication API or try the debugger.
JavaScript
43
star
93

auth0-custom-password-reset-hosted-page

An example on how to do a custom reset password hosted page.
HTML
41
star
94

magic

Auth0 Cryptography Toolkit
JavaScript
40
star
95

auth0-java-mvc-common

Contains common helper classes and api client logic that are used across our Java MVC libraries
Java
39
star
96

single-page-app-seed

A very opinionated seed for creating Single Page Apps that uses NO framework at all. Just a bunch of component libs
JavaScript
39
star
97

auth0-dotnet-templates

Auth0 Templates for .NET
C#
38
star
98

webtask-workshop

37
star
99

kbd

Styles for <kbd> tags.
HTML
37
star
100

express-oauth2-bearer

Experimental Middleware for express.js to validate access tokens.
JavaScript
36
star