Create Token APIedit


The CreateTokenRequest supports three different OAuth2 grant types:

Password Grantsedit

final char[] password = new char[]{'t', 'e', 's', 't', '-', 'u', 's', 'e', 'r', '-', 'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};
CreateTokenRequest createTokenRequest = CreateTokenRequest.passwordGrant("token_user", password);

Refresh Token Grantsedit

createTokenRequest = CreateTokenRequest.refreshTokenGrant(refreshToken);

Client Credential Grantsedit

CreateTokenRequest createTokenRequest = CreateTokenRequest.clientCredentialsGrant();


Creating a OAuth2 security token can be performed by passing the appropriate request to the security().createToken() method:

CreateTokenResponse createTokenResponse =, RequestOptions.DEFAULT);


The returned CreateTokenResponse contains the following properties:

This is the newly created access token. It can be used to authenticate to the Elasticsearch cluster.
The type of the token, this is always "Bearer".
The length of time until the token will expire. The token will be considered invalid after that time.
The scope of the token. May be null.
A secondary "refresh" token that may be used to extend the life of an access token. May be null.
This is the authentication object for the newly created token. See also authenticate response for details.
String accessToken = createTokenResponse.getAccessToken();    
String refreshToken = createTokenResponse.getRefreshToken();    

The accessToken can be used to authentication to Elasticsearch.

The refreshToken can be used in to create a new CreateTokenRequest with a refresh_token grant.

Asynchronous Executionedit

This request can be executed asynchronously using the security().createTokenAsync() method:, RequestOptions.DEFAULT, listener); 

The CreateTokenRequest to execute and the ActionListener to use when the execution completes

The asynchronous method does not block and returns immediately. Once the request has completed the ActionListener is called back using the onResponse method if the execution successfully completed or using the onFailure method if it failed.

A typical listener for a CreateTokenResponse looks like:

listener = new ActionListener<CreateTokenResponse>() {
    public void onResponse(CreateTokenResponse createTokenResponse) {

    public void onFailure(Exception e) {

Called when the execution is successfully completed. The response is provided as an argument

Called in case of failure. The raised exception is provided as an argument