Create Token API

Request

The CreateTokenRequest supports three different OAuth2 grant types:

Password Grants

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

Refresh Token Grants

createTokenRequest = CreateTokenRequest.refreshTokenGrant(refreshToken);

Client Credential Grants

CreateTokenRequest createTokenRequest = CreateTokenRequest.clientCredentialsGrant();

Execution

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

CreateTokenResponse createTokenResponse = client.security().createToken(createTokenRequest, RequestOptions.DEFAULT);

Response

The returned CreateTokenResponse contains the following properties:

accessToken
This is the newly created access token. It can be used to authenticate to the Elasticsearch cluster.
type
The type of the token, this is always "Bearer".
expiresIn
The length of time until the token will expire. The token will be considered invalid after that time.
scope
The scope of the token. May be null.
refreshToken
A secondary "refresh" token that may be used to extend the life of an access token. May be null.
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 Execution

This request can be executed asynchronously using the security().createTokenAsync() method:

client.security().createTokenAsync(createTokenRequest, 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>() {
    @Override
    public void onResponse(CreateTokenResponse createTokenResponse) {
        
    }

    @Override
    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