Create Token API

edit

Request

edit

The CreateTokenRequest supports three different OAuth2 grant types:

Password Grants

edit
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 Grants

edit
createTokenRequest = CreateTokenRequest.refreshTokenGrant(refreshToken);

Client Credential Grants

edit
CreateTokenRequest createTokenRequest = CreateTokenRequest.clientCredentialsGrant();

Execution

edit

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

edit

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.
authentication
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 Execution

edit

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