Java client library for the Auth0 platform.
Get Auth0 Java via Maven:
<dependency>
<groupId>com.auth0</groupId>
<artifactId>auth0</artifactId>
<version>1.5.1</version>
</dependency>
or Gradle:
compile 'com.auth0:auth0:1.5.1'
The Auth0 Authentication API and User's Management API are available for Android in the auth0.android
library. Check https://github.com/auth0/auth0.android for more information.
The implementation is based on the Authentication API Docs.
Create an AuthAPI
instance by providing the Application details from the dashboard.
AuthAPI auth = new AuthAPI("{YOUR_DOMAIN}", "{YOUR_CLIENT_ID}", "{YOUR_CLIENT_SECRET}");
Creates an AuthorizeUrlBuilder
to authenticate the user with an OAuth provider. The redirectUri
must be white-listed in the "Allowed Callback URLs" section of the Applications Settings. Parameters can be added to the final url by using the builder methods. When ready, call build()
and obtain the Url.
AuthorizeUrlBuilder authorizeUrl(String redirectUri)
Example:
String url = auth.authorizeUrl("https://me.auth0.com/callback")
.withConnection("facebook")
.withAudience("https://api.me.auth0.com/users")
.withScope("openid contacts")
.withState("state123")
.build();
Creates a LogoutUrlBuilder
to log out the user. The returnToUrl
must be white-listed in the "Allowed Logout URLs" section of the Dashboard, depending on the value of setClientId
this configuration should be set in the Application or in the Tenant Settings. Parameters can be added to the final url by using the builder methods. When ready, call build()
and obtain the Url.
LogoutUrlBuilder logoutUrl(String returnToUrl, boolean setClientId)
Example:
String url = auth.logoutUrl("https://me.auth0.com/home", true)
.useFederated(true)
.build();
Creates a request to get the user information associated to a given access token. This will only work if the token has been granted the openid
scope.
Request<UserInfo> userInfo(String accessToken)
Example:
Request<UserInfo> request = auth.userInfo("nisd1h9dk.....s1doWJOsaf");
try {
UserInfo info = request.execute();
// info.getValues();
} catch (APIException exception) {
// api error
} catch (Auth0Exception exception) {
// request error
}
Creates a request to reset the user's password. This will only work for db connections.
Request resetPassword(String email, String connection)
Example:
Request request = auth.resetPassword("[email protected]", "Username-Password-Authentication");
try {
request.execute();
} catch (APIException exception) {
// api error
} catch (Auth0Exception exception) {
// request error
}
Creates a request to create a user. Up to 10 additional Sign Up fields can be added to the request. This will only work for db connections.
SignUpRequest signUp(String email, String username, String password, String connection)
SignUpRequest signUp(String email, String password, String connection)
Example:
Map<String, String> fields = new HashMap<>();
fields.put("age", "25");
fields.put("city", "Buenos Aires");
SignUpRequest request = auth.signUp("[email protected]", "username", "password123", "Username-Password-Authentication")
.setCustomFields(fields);
try {
CreatedUser user = request.execute();
} catch (APIException exception) {
// api error
} catch (Auth0Exception exception) {
// request error
}
Creates a request to exchange the code
previously obtained by calling the /authorize endpoint. The redirect uri must be the one sent in the /authorize call.
AuthRequest exchangeCode(String code, String redirectUri)
Example:
AuthRequest request = auth.exchangeCode("asdfgh", "https://me.auth0.com/callback")
.setAudience("https://api.me.auth0.com/users")
.setScope("openid contacts");
try {
TokenHolder holder = request.execute();
} catch (APIException exception) {
// api error
} catch (Auth0Exception exception) {
// request error
}
Creates a request to log in the user with username
and password
. The connection used is the one defined as "Default Directory" in the account settings.
AuthRequest login(String emailOrUsername, String password)
Example:
AuthRequest request = auth.login("[email protected]", "password123")
.setAudience("https://api.me.auth0.com/users")
.setScope("openid contacts");
try {
TokenHolder holder = request.execute();
} catch (APIException exception) {
// api error
} catch (Auth0Exception exception) {
// request error
}
Creates a request to log in the user with username
and password
using the Password Realm.
AuthRequest login(String emailOrUsername, String password, String realm)
Example:
AuthRequest request = auth.login("[email protected]", "password123", "Username-Password-Authentication")
.setAudience("https://api.me.auth0.com/users")
.setScope("openid contacts");
try {
TokenHolder holder = request.execute();
} catch (APIException exception) {
// api error
} catch (Auth0Exception exception) {
// request error
}
Creates a request to get a Token for the given Audience.
AuthRequest requestToken(String audience)
Example:
AuthRequest request = auth.requestToken("https://api.me.auth0.com/users")
.setScope("openid contacts");
try {
TokenHolder holder = request.execute();
} catch (APIException exception) {
// api error
} catch (Auth0Exception exception) {
// request error
}
Creates a request to revoke an existing Refresh Token.
Request<Void> revokeToken(String refreshToken)
Example:
Request<Void> request = auth.revokeToken("nisd1h9dks1doWJOsaf");
try {
request.execute();
} catch (APIException exception) {
// api error
} catch (Auth0Exception exception) {
// request error
}
Creates a request to renew the authentication and get fresh new credentials using a valid Refresh Token.
AuthRequest renewAuth(String refreshToken)
Example:
AuthRequest request = auth.renewAuth("nisd1h9dks1doWJOsaf");
try {
TokenHolder holder = request.execute();
} catch (APIException exception) {
// api error
} catch (Auth0Exception exception) {
// request error
}
The implementation is based on the Management API Docs.
Create a ManagementAPI
instance by providing the domain from the Application dashboard and a valid API Token.
ManagementAPI mgmt = new ManagementAPI("{YOUR_DOMAIN}", "{YOUR_API_TOKEN}");
You can use the Authentication API to obtain a token for a previously authorized Application:
AuthAPI authAPI = new AuthAPI("{YOUR_DOMAIN}", "{YOUR_CLIENT_ID}", "{YOUR_CLIENT_SECRET}");
AuthRequest authRequest = authAPI.requestToken("https://{YOUR_DOMAIN}/api/v2/");
TokenHolder holder = authRequest.execute();
ManagementAPI mgmt = new ManagementAPI("{YOUR_DOMAIN}", holder.getAccessToken());
(Note that the simplified should have error handling, and ideally cache the obtained token until it expires instead of requesting one access token for each Management API v2 invocation).
Click here for more information on how to obtain API Tokens.
The Management API is divided into different entities. Each of them have the list, create, update, delete and update methods plus a few more if corresponds. The calls are authenticated using the API Token given in the ManagementAPI
instance creation and must contain the scope
required by each entity. See the javadoc for details on which scope
is expected for each call.
- Client Grants: See Docs. Access the methods by calling
mgmt.clientGrants()
. - Clients: See Docs. Access the methods by calling
mgmt.clients()
. - Connections: See Docs. Access the methods by calling
mgmt.connections()
. - Device Credentials: See Docs. Access the methods by calling
mgmt.deviceCredentials()
. - Logs: See Docs. Access the methods by calling
mgmt.logEvents()
. - Rules: See Docs. Access the methods by calling
mgmt.rules()
. - User Blocks: See Docs. Access the methods by calling
mgmt.userBlocks()
. - Users: See this and this doc. Access the methods by calling
mgmt.users()
. - Blacklists: See Docs. Access the methods by calling
mgmt.blacklists()
. - Emails: See Docs. Access the methods by calling
mgmt.emailProvider()
. - Guardian: See Docs. Access the methods by calling
mgmt.guardian()
. - Stats: See Docs. Access the methods by calling
mgmt.stats()
. - Tenants: See Docs. Access the methods by calling
mgmt.tenants()
. - Tickets: See Docs. Access the methods by calling
mgmt.tickets()
. - Resource Servers: See Docs. Access the methods by calling
mgmt.resourceServers()
.
Creates a request to list the Users by Email. This is the preferred and fastest way to query Users by Email, and should be used instead of calling the generic list method with an email query. An API Token with scope read:users
is needed. If you want the identities.access_token property to be included, you will also need the scope read:user_idp_tokens
.
You can pass an optional Filter to narrow the results in the response.
Request<List<User>> listByEmail(String email, UserFilter filter)
Example:
FieldsFilter filter = new FieldsFilter(...);
Request<List<User>> request = mgmt.users().listByEmail("[email protected]", filter);
try {
List<User> response = request.execute();
} catch (APIException exception) {
// api error
} catch (Auth0Exception exception) {
// request error
}
Creates a request to list the Users. An API Token with scope read:users
is needed. If you want the identities.access_token property to be included, you will also need the scope read:user_idp_tokens
.
You can pass an optional Filter to narrow the results in the response.
Request<UsersPage> list(UserFilter filter)
Example:
UserFilter filter = new UserFilter(...);
Request<UsersPage> request = mgmt.users().list(filter);
try {
UsersPage response = request.execute();
} catch (APIException exception) {
// api error
} catch (Auth0Exception exception) {
// request error
}
Creates a request to get a User. An API Token with scope read:users
is needed. If you want the identities.access_token property to be included, you will also need the scope read:user_idp_tokens
.
You can pass an optional Filter to narrow the results in the response.
Request<User> get(String userId, UserFilter filter)
Example:
UserFilter filter = new UserFilter(...);
Request<User> request = mgmt.users().get("auth0|123", filter);
try {
User response = request.execute();
} catch (APIException exception) {
// api error
} catch (Auth0Exception exception) {
// request error
}
Creates a request to create a User. An API Token with scope create:users
is needed.
Request<User> create(User user)
Example:
User data = new User(...);
Request<User> request = mgmt.users().create(data);
try {
User response = request.execute();
} catch (APIException exception) {
// api error
} catch (Auth0Exception exception) {
// request error
}
Creates a request to delete a User. An API Token with scope delete:users
is needed.
Request delete(String userId)
Example:
Request request = mgmt.users().delete("auth0|123");
try {
request.execute();
} catch (APIException exception) {
// api error
} catch (Auth0Exception exception) {
// request error
}
Creates a request to update a User. An API Token with scope update:users
is needed. If you're updating app_metadata you'll also need update:users_app_metadata
scope.
Request<User> update(String userId, User user)
Example:
User data = new User(...);
Request request = mgmt.users().update("auth0|123", data);
try {
User response = request.execute();
} catch (APIException exception) {
// api error
} catch (Auth0Exception exception) {
// request error
}
Creates a request to list the User's Guardian Enrollments. An API Token with scope read:users
is needed.
Request<List<Enrollment>> getEnrollments(String userId)
Example:
Request<List<Enrollment>> request = mgmt.users().getEnrollments("auth0|123");
try {
List<Enrollment> response = request.execute();
} catch (APIException exception) {
// api error
} catch (Auth0Exception exception) {
// request error
}
Creates a request to list the User's Log Events. An API Token with scope read:logs
is needed.
You can pass an optional Filter to narrow the results in the response.
Request<LogEventsPage> getLogEvents(String userId, LogEventFilter filter)
Example:
LogEventFilter filter = new LogEventFilter(...);
Request<LogEventsPage> request = mgmt.users().getLogEvents("auth0|123", filter);
try {
LogEventsPage response = request.execute();
} catch (APIException exception) {
// api error
} catch (Auth0Exception exception) {
// request error
}
Creates a request to delete the User's Multifactor Provider. An API Token with scope update:users
is needed.
Request deleteMultifactorProvider(String userId, String provider)
Example:
Request request = mgmt.users().deleteMultifactorProvider("auth0|123", "duo");
try {
request.execute();
} catch (APIException exception) {
// api error
} catch (Auth0Exception exception) {
// request error
}
Creates a request to rotate the User's Recovery Code. An API Token with scope update:users
is needed.
Request<RecoveryCode> rotateRecoveryCode(String userId)
Example:
Request<RecoveryCode> request = mgmt.users().rotateRecoveryCode("auth0|123");
try {
RecoveryCode response = request.execute();
} catch (APIException exception) {
// api error
} catch (Auth0Exception exception) {
// request error
}
Creates a request to link two User identities. An API Token with scope update:users
is needed.
Request<List<Identity>> linkIdentity(String primaryUserId, String secondaryUserId, String provider, String connectionId)
Example:
Request<List<Identities>> request = mgmt.users().linkIdentity("auth0|123", "124", "facebook", "c90");
try {
List<Identities> response = request.execute();
} catch (APIException exception) {
// api error
} catch (Auth0Exception exception) {
// request error
}
Creates a request to un-link two User identities. An API Token with scope update:users
is needed.
Request<List<Identity>> unlinkIdentity(String primaryUserId, String secondaryUserId, String provider)
Example:
Request<List<Identities>> request = mgmt.users().unlinkIdentity("auth0|123", "124", "facebook");
try {
List<Identities> response = request.execute();
} catch (APIException exception) {
// api error
} catch (Auth0Exception exception) {
// request error
}
The API Clients throw Auth0Exception
when an unexpected error happens on a request execution, i.e. Connectivity or Timeout error.
If you need to handle different error scenarios you need to catch first APIException
, which provides methods to get a clue of what went wrong.
The APIExplorer includes a list of response messages for each endpoint. You can get a clue of what went wrong by asking the Http status code: exception.getStatusCode()
. i.e. a status_code=403
would mean that the token has an insufficient scope.
An error code will be included to categorize the type of error, you can get it by calling exception.getError()
. If you want to see a user friendly description of what happened and why the request is failing check the exception.getDescription()
.
Example exception data
{
statusCode: 400,
description: "Query validation error: 'String 'users' does not match pattern. Must be a comma separated list of the following values: name,strategy,options,enabled_clients,id,provisioning_ticket_url' on property fields (A comma separated list of fields to include or exclude (depending on include_fields) from the result, empty to retrieve all fields).",
error: "invalid_query_string"
}
For more information about auth0 check our documentation page.
Auth0 helps you to:
- Add authentication with multiple authentication sources, either social like Google, Facebook, Microsoft Account, LinkedIn, GitHub, Twitter, Box, Salesforce, among others, or enterprise identity systems like Windows Azure AD, Google Apps, Active Directory, ADFS or any SAML Identity Provider.
- Add authentication through more traditional username/password databases.
- Add support for linking different user accounts with the same user.
- Support for generating signed Json Web Tokens to call your APIs and flow the user identity securely.
- Analytics of how, when and where users are logging in.
- Pull data from other sources and add it to the user profile, through JavaScript rules.
- Go to Auth0 and click Sign Up.
- Use Google, GitHub or Microsoft Account to login.
If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.
This project is licensed under the MIT license. See the LICENSE file for more info.