From 52b1b21f0e4ce17736d18da9bd19cc29456f023d Mon Sep 17 00:00:00 2001 From: Greg Holmes Date: Tue, 28 Oct 2025 11:50:59 +0000 Subject: [PATCH] Migrate REST SDK API spec Authentication page to MDX --- content/api/rest-sdk/authentication.textile | 597 --------- .../docs/api/rest-sdk/authentication.mdx | 1185 +++++++++++++++++ 2 files changed, 1185 insertions(+), 597 deletions(-) delete mode 100644 content/api/rest-sdk/authentication.textile create mode 100644 src/pages/docs/api/rest-sdk/authentication.mdx diff --git a/content/api/rest-sdk/authentication.textile b/content/api/rest-sdk/authentication.textile deleted file mode 100644 index a944f181bf..0000000000 --- a/content/api/rest-sdk/authentication.textile +++ /dev/null @@ -1,597 +0,0 @@ ---- -title: Authentication -meta_description: "Client Library SDK REST API Reference Authentication documentation." -meta_keywords: "Ably, Ably REST, API Reference, REST SDK, REST interface, REST API, Authentication" -section: api -index: 60 -languages: - - javascript - - nodejs - - php - - python - - ruby - - java - - swift - - objc - - csharp - - go -jump_to: - Help with: - - Tokens#tokens - - Auth object#auth-object - Auth API properties: - - clientId#client-id - Auth API methods: - - authorize - - createTokenRequest#create-token-request - - requestToken#request-token - - revokeTokens#revoke-tokens - Types: - - Related Types#related-types -redirect_from: - - /docs/api/versions/v1.1/rest-sdk/authentication - - /docs/api/versions/v1.0/rest-sdk/authentication - - /docs/api/versions/v0.8/rest-sdk/authentication ---- - -This is the Authentication API Reference. - -h2(#tokens). Tokens - -In the documentation, references to Ably-compatible tokens typically refer either to an Ably Token, or an "Ably JWT":#ably-jwt. For Ably Tokens, this can either be referring to the @TokenDetails@ object that contain the @token@ string or the token string itself. @TokenDetails@ objects are obtained when "requesting an Ably Token":#request-token from the Ably service and contain not only the @token@ string in the @token@ attribute, but also contain attributes describing the properties of the Ably Token. For "Ably JWT":#ably-jwt, this will be simply referring to a JWT which has been signed by an Ably private API key. - -h2(#auth-object). Auth object - -The principal use-case for the @Auth@ object is to create Ably "@TokenRequest@":#token-request objects with "createTokenRequest":#create-token-request or obtain "Ably Tokens":#token-details from Ably with "requestToken":#request-token, and then issue them to other "less trusted" clients. Typically, your servers should be the only devices to have a "private API key":/docs/auth#api-key, and this private API key is used to securely sign Ably "@TokenRequest@":#token-request objects or request "Ably Tokens":#token-details from Ably. Clients are then issued with these short-lived "Ably Tokens":#token-details or Ably "@TokenRequest@":#token-request objects, and the libraries can then use these to authenticate with Ably. If you adopt this model, your private API key is never shared with clients directly. - -A subsidiary use-case for the @Auth@ object is to preemptively trigger renewal of a token or to acquire a new token with a revised set of capabilities by explicitly calling "@authorize@@Authorize@":#authorize. - -The Auth object is available as the "@auth@ field":/docs/api/rest-sdk#auth"@auth@ property":/docs/api/rest-sdk#auth"@Auth@ property":/docs/api/rest-sdk#auth"@auth@ attribute":/docs/api/rest-sdk#auth of an "Ably REST client instance":/docs/api/rest-sdk#constructor. - -h2(#properties). - default: Auth Properties - php: Ably\Auth Properties - java: io.ably.lib.rest.Auth Members - ruby: Ably::Auth Attributes - python: Auth Attributes - objc,swift: ARTAuth Properties - -The @ART@@Auth@ object exposes the following public propertiesattributesmembers: - -h6(#client-id). - default: clientId - ruby: client_id - python: client_id - csharp: ClientId - go: ClientID - -The client ID string, if any, configured for this client connection. See "identified clients":#identified-clients for more information on trusted client identifiers. - -h2(#methods). - default: Auth Methods - java: io.ably.lib.rest.Auth Methods - ruby: Ably::Auth Methods - php: Ably\Auth Methods - objc,swift: ARTAuth Methods - -h6(#authorize). - default: authorize - csharp,go: Authorize - - - -bq(definition). - default: authorize("TokenParams":#token-params tokenParams, "AuthOptions":#auth-options authOptions, callback("ErrorInfo":/docs/api/rest-sdk/types#error-info err, "TokenDetails":#token-details tokenDetails)) - jsall: authorize("TokenParams":#token-params tokenParams?, "AuthOptions":#auth-options authOptions?): Promise<"TokenDetails":#token-details> - ruby: "TokenDetails":#token-details authorize("TokenParams":#token-params token_params, "AuthOptions":#auth-options auth_options) - python: "TokenDetails":#token-details authorize(token_params="TokenParams":#token-params, auth_options="AuthOptions":#auth-options) - php: "TokenDetails":#token-details authorize("TokenParams":#token-params tokenParams, "AuthOptions":#auth-options authOptions) - java: "TokenDetails":#token-details authorize("TokenParams":#token-params tokenParams, "AuthOptions":#auth-options authOptions) - csharp: Task AuthorizeAsync("TokenParams":#token-params tokenParams = null, "AuthOptions":#auth-options options = null); - go: "TokenDetails":#token-details Authorize("TokenParams":#token-params tokenParams, "AuthOptions":#auth-options authOptions) - swift,objc: authorize(tokenParams: "ARTTokenParams":#token-params?, authOptions: "ARTAuthOptions":#auth-options?, callback: ("ARTTokenDetails":#token-details?, NSError?) -> Void) - -Instructs the library to get a new token immediately using the specified @token_params@ and @auth_options@@tokenParams@ and @authOptions@@TokenParams@ and @AuthOptions@ (or if none specified, the client library defaults). Also stores any @token_params@ and @auth_options@@TokenParams@ and @AuthOptions@@tokenParams@ and @authOptions@ passed in as the new defaults, to be used for all subsequent implicit or explicit token requests. - -Any @token_params@ and @auth_options@@TokenParams@ and @AuthOptions@@tokenParams@ and @authOptions@ objects passed in will entirely replace (as opposed to being merged with) the currently saved @token_params@ and @auth_options@@tokenParams@ and @authOptions@. - -h4. Parameters - -- token_paramsTokenParamstokenParams := an optional object containing the "Ably Token parameters":#token-paramsan optional "@TokenParams@":#token-params object containing the token parametersan optional Dict containing the "Ably Token parameters":#token-paramsan optional set of key value pairs containing the "Ably Token parameters":#token-paramsan optional set of key value pairs in an associative array containing the "Ably Token parameters":#token-params for the authorization request
__Type: "@TokenParams@":#token-params__ - -- auth_optionsAuthOptionsauthOptions := an optional object containing the "authentication options":#auth-optionsan optional "@AuthOptions@":#auth-options object containing the authentication optionsan optional Dict containing the "authentication options":#auth-optionsan optional set of key value pairs containing the "authentication options":#auth-optionsan optional set of key value pairs in an associative array containing the "authentication options":#auth-options for the authorization request
__Type: "@AuthOptions@":#auth-options__ - --
callback
:= called with a "@ARTTokenDetails@":#token-details object or an error - -blang[jsall]. - h4. Returns - - Returns a promise. - - On success, the promise is fulfilled with the a "@TokenDetails@":#token-details object containing the details of the new or existing "Ably Token":#token-details along with the @token@ string. - - On failure to obtain an token, the promise is rejected with an "@ErrorInfo@":/docs/api/rest-sdk/types#error-info object with the error response as defined in the "Ably REST API":/docs/api/rest-api#common documentation. - -blang[objc,swift]. - h4. Callback result - - On success, @tokenDetails@ contains a "@TokenDetails@":#token-details object containing the details of the new or existing "Ably Token":#token-details along with the @token@ string. - - On failure to obtain an token, @err@ contains an "@ErrorInfo@":#error-info@NSError@ object with an error response as defined in the "Ably REST API":/docs/api/rest-api#common documentation. - -blang[java,ruby,php,python,go]. - h4. Returns - - On success, a "@TokenDetails@":#token-details object containing the details of the new or existing token along with the @token@ string is returned. - - Failure to obtain an token will raise an "@AblyException@":#ably-exception. - -blang[csharp]. - h4. Returns - - The method is asynchronous and returns a @Task@ which needs to be awaited. - - On success, a "@TokenDetails@":#token-details object containing the details of the new or existing token along with the @token@ string is returned. - - Failure to obtain a token will raise an "@AblyException@":#ably-exception. - -h4. Example - -bc[jsall]. try { - const tokenDetails = await client.auth.authorize({ clientId: 'bob' }); - console.log('Success; token: ' + tokenDetails.token); -} catch (error) { - console.log('An error occurred; err = ' + error.message); -} - -bc[java]. try { - TokenParams tokenParams = new TokenParams(); - tokenParams.clientId = "bob"; - TokenDetails tokenDetails = client.auth.authorize(tokenParams, null); - System.out.println("Success; token = " + tokenDetails.token); -} catch(AblyException e) { - System.out.println("An error occurred; err = " + e.getMessage()); -} - -bc[csharp]. try -{ - TokenParams tokenParams = new TokenParams { ClientId = "bob" }; - TokenDetails tokenDetails = await client.Auth.AuthorizeAsync(tokenParams); - Console.WriteLine("Success; token = " + tokenDetails.Token); -} -catch (AblyException e) -{ - Console.WriteLine("An error occurred; err = " + e.Message); -} - -bc[ruby]. token_details = client.auth.authorize(client_id: 'bob') -puts "Success; token = #{token_details.token}" - -bc[python]. token_details = client.auth.authorize(token_params={'client_id': 'bob'}) -print("Success; token = " + str(token_details.token)) - -bc[php]. $tokenDetails = $client->auth->authorize(array('clientId' => 'bob')); -echo("Success; token = " . $tokenDetails->token); - -bc[objc]. ARTTokenParams *tokenParams = [[ARTTokenParams alloc] initWithClientId:@"Bob"]; -[client.auth authorize:tokenParams options:nil callback:^(ARTTokenDetails *tokenDetails, NSError *error) { - if (error) { - NSLog(@"An error occurred; err = %@", error); - } else { - NSLog(@"Success; token = %@", tokenDetails.token); - } -}]; - -bc[swift]. let tokenParams = ARTTokenParams(clientId: "Bob") -client.auth.authorize(tokenParams, options: nil) { tokenDetails, error in - guard let tokenDetails = tokenDetails else { - print("An error occurred; err = \(error!)") - return - } - print("Success; token = \(tokenDetails.token)") -} - -bc[go]. tokenParams := &ably.TokenParams{ - ClientID: "Bob", -} -token, err := client.Auth.Authorize(tokenParams, &ably.AuthOptions{}) -if err != nil { - fmt.Println(err) -} -fmt.Println(token) - -h6(#create-token-request). - default: createTokenRequest - csharp,go: CreateTokenRequest - ruby: create_token_request - python: create_token_request - -bq(definition). - default: createTokenRequest("TokenParams":#token-params tokenParams, "AuthOptions":#auth-options authOptions, callback("ErrorInfo":/docs/api/rest-sdk/types#error-info err, "TokenRequest":#token-request tokenRequest)) - jsall: createTokenRequest("TokenParams":#token-params tokenParams?, "AuthOptions":#auth-options authOptions?): Promise<"TokenRequest":#token-request> - ruby: "TokenRequest":#token-request create_token_request("TokenParams":#token-params token_params, "AuthOptions":#auth-options auth_options) - python: "TokenRequest":#token-request create_token_request(token_params="TokenParams":#token-params, key_name=String, key_secret=String) - php: "TokenRequest":#token-request createTokenRequest("TokenParams":#token-params tokenParams, "AuthOptions":#auth-options authOptions) - java: "TokenRequest":#token-request createTokenRequest("TokenParams":#token-params tokenParams, "AuthOptions":#auth-options authOptions) - go: "TokenRequest":#token-request CreateTokenRequest("TokenParams":#token-params tokenParams, "AuthOptions":#auth-options authOptions) - csharp: Task CreateTokenRequestAsync(TokenParams tokenParams = null, AuthOptions authOptions = null) - objc,swift: createTokenRequest(tokenParams: "ARTTokenParams":#token-params?, options: "ARTAuthOptions":#auth-options?, callback: ("ARTTokenRequest":#token-request?, NSError?) -> Void) - -Creates and signs an Ably "@TokenRequest@":#request-token based on the specified @token_params@ and @auth_options@@TokenParams@ and @AuthOptions@@tokenParams@ and @authOptions@. Note this can only be used when the "API @key@":/docs/auth#api-key value is available locally, due to it being required to sign the Ably "@TokenRequest@":#request-token. Otherwise, Ably "@TokenRequests@":#request-token must be obtained from the key owner. Use this to generate Ably "@TokenRequests@":#request-token in order to implement an "Ably Token":#token-details request callback for use by other clients. - -Both @auth_options@ and @token_params@@AuthOptions@ and @TokenParams@@authOptions@ and @tokenParams@ are optional. When omitted or @null@@Null@@None@@nil@, the default Ably-compatible token parameters and authentication options for the client library are used, as specified in the @ClientOptions@ when the client library was instantiated, or later updated with an explicit "@authorize@@Authorize@":#authorize request. Values passed in will be used instead of (rather than being merged with) the default values. - -To understand why an Ably "@TokenRequest@":#request-token may be issued to clients in favor of an "Ably Token":#token-details, see "Token Authentication explained":/docs/auth/token. - -h4. Parameters - -- token_paramsTokenParamstokenParams := an optional object containing the "token parameters":#token-paramsan optional "@TokenParams@":#token-params object containing the token parametersan optional Dict containing the "token parameters":#token-paramsan optional set of key value pairs containing the "token parameters":#token-paramsan optional set of key value pairs in an associative array containing the "token parameters":#token-params for the Ably "@TokenRequest@":#request-token
__Type: "@TokenParams@":#token-params__ - -- auth_options[auth options]AuthOptionsauthOptions := an optional object containing the "authentication options":#auth-optionsan optional "@TokenParams@":#auth-options object containing the authentication optionsvarious keyword arguments with the "authentication options":#auth-optionsan optional set of key value pairs containing the "authentication options":#auth-optionsan optional set of key value pairs in an associative array containing the "authentication options":#auth-optionsan optional "@ARTTokenParams@":#token-params containing the "authentication options":#auth-options for the "Ably Token":#token-details Request
__Type: "@AuthOptions@":#auth-options__ - --
callback
:= called with a "@ARTTokenRequest@":#token-request object or an error - -blang[jsall]. - h4. Returns - - Returns a promise. - - On success, the promise is fulfilled with a "@TokenRequest@":#token-request JSON object. - - On failure to issue a "@TokenRequest@":#token-request, the promise is rejected with an "@ErrorInfo@":/docs/api/rest-sdk/types#error-info object with the error response as defined in the "Ably REST API":/docs/api/rest-api#common documentation. - -blang[objc,swift]. - h4. Callback result - - On success, @tokenRequest@ contains a "@TokenRequest@":#token-request JSON object. - - On failure to issue a "@TokenRequest@":#token-request, @err@ contains an "@ErrorInfo@":#error-info object with an error response as defined in the "Ably REST API":/docs/api/rest-api#common documentation. - -blang[java,ruby,php,python,go]. - h4. Returns - - On success, a "@TokenRequest@":#token-request object is returned. - - Failure to issue a "@TokenRequest@":#token-request will raise an "@AblyException@":#ably-exception. - -blang[csharp]. - h4. Returns - - The method is asynchronous and returns a @Task@ which needs to be awaited. - - On success, a "@TokenRequest@":#token-request object is returned. - - Failure to issue a "@TokenRequest@":#token-request will raise an "@AblyException@":#ably-exception. - -h4. Example - -bc[jsall]. try { - const tokenRequest = await client.auth.createTokenRequest({ clientId: 'bob' }); - console.log('Success; token request = ' + tokenRequest); -} catch (error) { - console.log('An error occurred; err = ' + error.message); -} - -bc[java]. try { - TokenParams tokenParams = new TokenParams(); - tokenParams.clientId = "bob"; - TokenRequest tokenRequest = client.auth.createTokenRequest(tokenParams, null); - System.out.println("Success; token request issued"); -} catch(AblyException e) { - System.out.println("An error occurred; err = " + e.getMessage()); -} - -bc[csharp]. try -{ - TokenParams tokenParams = new TokenParams { ClientId = "bob" }; - var tokenRequest = await client.Auth.CreateTokenRequestAsync(tokenParams); - Console.WriteLine("Success; token request issued"); -} -catch (AblyException e) -{ - Console.WriteLine("An error occurred; err = " + e.Message); -} - -bc[ruby]. token_request = client.auth.create_token_request(client_id: 'bob') -puts "Success; token request = #{token_request}" - -bc[python]. token_request = client.auth.create_token_request(token_params={'client_id': 'bob'}) -print("Success; token request = ' + str(token_request)) - -bc[php]. $tokenRequest = $client->auth->createTokenRequest(array('clientId' => 'bob')) -echo("Success; token request = " . $tokenRequest); - -bc[objc]. ARTTokenParams *tokenParams = [[ARTTokenParams alloc] initWithClientId:@"Bob"]; -[client.auth createTokenRequest:tokenParams options:nil callback:^(ARTTokenRequest *tokenRequest, NSError *error) { - if (error) { - NSLog(@"An error occurred; err = %@", error); - } else { - NSLog(@"Success; token request = %@", tokenRequest); - } -}]; - -bc[swift]. let tokenParams = ARTTokenParams(clientId: "Bob") -client.auth.createTokenRequest(tokenParams, options: nil) { tokenRequest, error in - guard let tokenRequest = tokenRequest else { - print("An error occurred; err = \(error!)") - return - } - print("Success; token request = \(tokenRequest)") -} - -bc[go]. tokenParams := &ably.TokenParams{ - ClientID: "Bob", -} -tokenRequest, err := client.Auth.CreateTokenRequest(tokenParams, &ably.AuthOptions{}) -if err != nil { - fmt.Println(err) -} -fmt.Println(tokenRequest) - -h6(#request-token). - default: requestToken - ruby: request_token - python: request_token - csharp: RequestToken - go: RequestToken - -bq(definition). - default: requestToken("TokenParams":#token-params tokenParams, "AuthOptions":#auth-options authOptions, callback("ErrorInfo":/docs/api/rest-sdk/types#error-info err, "TokenDetails":#token-details tokenDetails)) - jsall: requestToken("TokenParams":#token-params tokenParams?, "AuthOptions":#auth-options authOptions?): Promise<"TokenDetails":#token-details> - ruby: "TokenDetails":#token-details request_token("TokenParams":#token-params token_params, "AuthOptions":#auth-options auth_options) - python: "TokenDetails":#token-details request_token(token_params="TokenParams":#token-params, key_name=String, key_secret=None, auth_callback=Lambda, auth_url=String, auth_method=String, auth_headers=Dict, auth_params=Dict, query_time=Boolean) - php: "TokenDetails":#token-details requestToken("TokenParams":#token-params tokenParams, "AuthOptions":#auth-options authOptions) - csharp: Task RequestTokenAsync(TokenParams tokenParams = null, AuthOptions options = null) - java: "TokenDetails":#token-details requestToken("TokenParams":#token-params tokenParams, "AuthOptions":#auth-options authOptions) - objc,swift: requestToken(tokenParams: "ARTTokenParams":#token-params?, withOptions: "ARTAuthOptions":#auth-options?, callback: ("ARTTokenDetails":#token-details?, NSError?) -> Void) - go: "TokenDetails":#token-details RequestToken("TokenParams":#token-params tokenParams, "AuthOptions":#auth-options authOptions) - -Calls the "@requestToken@@RequestToken@ REST API endpoint":/docs/api/rest-api#request-token to obtain an "Ably Token":#token-details according to the specified @token_params@ and @auth_options@@tokenParams@ and @authOptions@. - -Both @auth_options@ and @token_params@@authOptions@ and @tokenParams@ are optional. When omitted or @null@@Null@@None@@nil@, the default token parameters and authentication options for the client library are used, as specified in the @ClientOptions@ when the client library was instantiated, or later updated with an explicit "@authorize@@Authorize@":#authorize request. Values passed in will be used instead of (rather than being merged with) the default values. - -To understand why an Ably "@TokenRequest@":#request-token may be issued to clients in favor of an "Ably Token":#token-details, see "Token Authentication explained":/docs/auth/token. - -h4. Parameters - -- token_paramstokenParams := an optional object containing the "token parameters":#token-paramsan optional Dict containing the "token parameters":#token-paramsan optional "@TokenParams@":#token-params object containing the token parametersan optional set of key value pairs containing the "token parameters":#token-paramsan optional set of key value pairs in an associative array containing the "token parameters":#token-params for the requested "Ably Token":#token-details
__Type: "@TokenParams@":#token-params__ - -- [auth options]auth_optionsauthOptions := an optional object containing the "authentication options":#auth-optionsvarious keyword arguments with the "authentication options":#auth-optionsan optional "@TokenParams@":#auth-options object containing the authentication optionsan optional set of key value pairs containing the "authentication options":#auth-optionsan optional set of key value pairs in an associative array containing the "authentication options":#auth-options for the requested "Ably Token":#token-details
__Type: "@AuthOptions@":#auth-options__ - --
callback
:= called with a "@ARTTokenDetails@":#token-details object or an error - -blang[jsall]. - h4. Returns - - Returns a promise. - - On success, the promise is fulfilled with a "@TokenDetails@":#token-details object containing the details of the new "Ably Token":#token-details along with the @token@ string. - - On failure to obtain an "Ably Token":#token-details, the promise is rejected with an "@ErrorInfo@":/docs/api/rest-sdk/types#error-info object with the error response as defined in the "Ably REST API":/docs/api/rest-api#common documentation. - -blang[objc,swift]. - h4. Callback result - - On success, @tokenDetails@ contains a "@TokenDetails@":#token-details object containing the details of the new "Ably Token":#token-details along with the @token@ string. - - On failure to obtain an "Ably Token":#token-details, @err@ contains an "@ErrorInfo@":#error-info@NSError@ object with an error response as defined in the "Ably REST API":/docs/api/rest-api#common documentation. - -blang[java,ruby,php,python,go]. - h4. Returns - - On success, a "@TokenDetails@":#token-details object containing the details of the new "Ably Token":#token-details along with the @token@ string is returned. - - Failure to obtain an "Ably Token":#token-details will raise an "@AblyException@":#ably-exception. - -blang[csharp]. - h4. Returns - - The method is asynchronous and returns a @Task@ which needs to be awaited. - - On success, a "@TokenDetails@":#token-details object containing the details of the new "Ably Token":#token-details along with the @token@ string is returned. - - Failure to obtain an "Ably Token":#token-details will raise an "@AblyException@":#ably-exception. - -h4. Example - -bc[jsall]. try { - const tokenDetails = await client.auth.requestToken({ clientId: 'bob'}); - console.log('Success; token = ' + tokenDetails.token); -} catch (error) { - console.log('An error occurred; err = ' + error.message); -} - -bc[ruby]. token_details = client.auth.request_token(client_id: 'bob') -puts "Success; token = #{token_details.token}" - -bc[python]. token_details = client.auth.request_token(token_params={'client_id': 'bob'}) -print("Success; token = " + str(token_details.token)) - -bc[php]. $tokenDetails = $client->auth->requestToken(array('clientId' => 'bob')) -echo("Success; token = " . $tokenDetails->token); - -bc[java]. try { - TokenParams tokenParams = new TokenParams(); - tokenParams.clientId = "bob"; - TokenDetails tokenDetails = client.auth.requestToken(tokenParams, null); - System.out.println("Success; token = " + tokenDetails.token); -} catch(AblyException e) { - System.out.println("An error occurred; err = " + e.getMessage()); -} - -bc[csharp]. try { - TokenParams tokenParams = new TokenParams { ClientId = "bob" }; - var tokenDetails = await client.Auth.RequestTokenAsync(tokenParams); - Console.WriteLine("Success; token = " + tokenDetails.Token); -} -catch (AblyException e) -{ - Console.WriteLine("An error occurred; err = " + e.Message); -} - -bc[objc]. ARTTokenParams *tokenParams = [[ARTTokenParams alloc] initWithClientId:@"Bob"]; -[client.auth requestToken:tokenParams withOptions:nil callback:^(ARTTokenDetails *tokenDetails, NSError *error) { - if (error) { - NSLog(@"An error occurred; err = %@", error); - } else { - NSLog(@"Success; token = %@", tokenDetails.token); - } -}]; - -bc[swift]. let tokenParams = ARTTokenParams(clientId: "Bob") -client.auth.requestToken(tokenParams, withOptions: nil) { tokenDetails, error in - guard let tokenDetails = tokenDetails else { - print("An error occurred; err = \(error!)") - return - } - print("Success; token = \(tokenDetails.token)") -} - -bc[go]. tokenParams := &ably.TokenParams{ - ClientID: "Bob", -} -token, err := client.Auth.RequestToken(tokenParams, &ably.AuthOptions{}) -if err != nil { - fmt.Println(err) -} -fmt.Println(token) - -blang[jsall]. - - h6(#revoke-tokens). - jsall: revokeTokens - - bq(definition). - jsall: revokeTokens("TokenRevocationTargetSpecifier[]":#token-revocation-target-specifier specifiers, "TokenRevocationOptions":#token-revocation-options options?): Promise<"BatchResult":#batch-result<"TokenRevocationSuccessResult":#token-revocation-success-result | "TokenRevocationFailureResult":#token-revocation-failure-result>> - - Calls the "@revokeTokens@ REST API endpoint":/docs/api/rest-api#revoke-tokens to revoke tokens specified by the provided array of "TokenRevocationTargetSpecifier":#token-revocation-target-specifier. - - Only tokens issued by an API key that had revocable tokens enabled before the token was issued can be revoked. See the "token revocation docs":/docs/auth/revocation for more information. - - h4. Parameters - - - specifiers := an array of "TokenRevocationTargetSpecifier":#token-revocation-target-specifier objects
__Type: "@TokenRevocationTargetSpecifier[]@":#token-revocation-target-specifier__ - - - options := an optional set of options which are used to modify the revocation request
__Type: "@TokenRevocationOptions@":#token-revocation-options__ - - h4. Returns - - Returns a promise. - - On success, the promise is fulfilled with a "BatchResult":#batch-result containing information about the result of the token revocation request for each provided "TokenRevocationTargetSpecifier":#token-revocation-target-specifier. - - On failure, the promise is rejected with an "@ErrorInfo@":/docs/api/rest-sdk/types#error-info object with the error response as defined in the "Ably REST API":/docs/api/rest-api#common documentation. - - h4. Example - - bc[jsall]. try { - const response = await client.auth.revokeTokens([{ type: 'clientId', value: 'bob' }]); - console.log('Revocation successful; revoked tokens: ' + response.results.length); - } catch (error) { - console.log('An error occurred; err = ' + error.message); - } - -h2(#related-types). Related types - -h3(#auth-options). - default: AuthOptions Object - ruby: AuthOptions Hash - java: io.ably.lib.rest.Auth.AuthOptions - -<%= partial partial_version('types/_auth_options') %> - -h3(#token-details). - default: TokenDetails Object - objc,swift: ARTTokenDetails - java: io.ably.lib.types.TokenDetails - ruby: Ably::Models::TokenDetails - -<%= partial partial_version('types/_token_details') %> - -h3(#token-params). - default: TokenParams Object - objc,swift: ARTTokenParams - ruby: TokenParams Hash - java: io.ably.lib.rest.Auth.TokenParams - -<%= partial partial_version('types/_token_params') %> - -h3(#token-request). - default: TokenRequest Object - objc,swift: ARTTokenRequest - ruby: Ably::Models::TokenRequest - java: io.ably.lib.rest.Auth.TokenRequest - -<%= partial partial_version('types/_token_request') %> - -h3(#ably-jwt). Ably JWT - -An Ably JWT is not strictly an Ably construct, rather it is a "JWT":https://jwt.io/ which has been constructed to be compatible with Ably. The JWT must adhere to the following to ensure compatibility: - -* *The JOSE header must include:* -** @kid@ - Key name, such that an API key of @{{API_KEY}}@ will have key name @{{API_KEY_NAME}}@ -* *The JWT claim set must include:* -** @iat@ - time of issue in seconds -** @exp@ - expiry time in seconds -* *The JWT claim set may include:* -** @x-ably-capability@ - JSON text encoding of the "capability":#tokens -** @x-ably-clientId@ - client ID - -Arbitrary additional claims and headers are supported (apart from those prefixed with @x-ably-@ which are reserved for future use). - -The Ably JWT must be signed with the secret part of your "Ably API key":/docs/auth#api-key using the signature algorithm HS256 (HMAC using the SHA-256 hash algorithm). View the "JSON Web Algorithms (JWA) specification":https://tools.ietf.org/html/rfc7518 for further information. - -We recommend you use one of the many "JWT libraries available for simplicity":https://jwt.io/ when creating your JWTs. - -The following is an example of creating an Ably JWT: - -```[javascript] - var header = { - "typ":"JWT", - "alg":"HS256", - "kid": "{{API_KEY_NAME}}" - }; - var currentTime = Math.round(Date.now()/1000); - var claims = { - "iat": currentTime, /* current time in seconds */ - "exp": currentTime + 3600, /* time of expiration in seconds */ - "x-ably-capability": "{\"*\":[\"*\"]}" - }; - var base64Header = btoa(header); - var base64Claims = btoa(claims); - /* Apply the hash specified in the header */ - var signature = hash((base64Header + "." + base64Claims), "{{API_KEY_SECRET}}"); - var ablyJwt = base64Header + "." + base64Claims + "." + signature; -``` - -*Note:* At present Ably does not support asymmetric signatures based on a keypair belonging to a third party. - -h3(#batch-result). - jsall: BatchResult - -blang[jsall]. - <%= partial partial_version('types/_batch_result') %> - -h3(#token-revocation-target-specifier). - jsall: TokenRevocationTargetSpecifier - -blang[jsall]. - <%= partial partial_version('types/_token_revocation_target_specifier') %> - -h3(#token-revocation-options). - jsall: TokenRevocationOptions - -blang[jsall]. - <%= partial partial_version('types/_token_revocation_options') %> - -h3(#token-revocation-success-result). - jsall: TokenRevocationSuccessResult - -blang[jsall]. - <%= partial partial_version('types/_token_revocation_success_result') %> - -h3(#token-revocation-failure-result). - jsall: TokenRevocationFailureResult - -blang[jsall]. - <%= partial partial_version('types/_token_revocation_failure_result') %> diff --git a/src/pages/docs/api/rest-sdk/authentication.mdx b/src/pages/docs/api/rest-sdk/authentication.mdx new file mode 100644 index 0000000000..1f8922febb --- /dev/null +++ b/src/pages/docs/api/rest-sdk/authentication.mdx @@ -0,0 +1,1185 @@ +--- +title: Authentication +meta_description: "Client Library SDK REST API Reference Authentication documentation." +meta_keywords: "Ably, Ably REST, API Reference, REST SDK, REST interface, REST API, Authentication" +jump_to: + Help with: + - Tokens#tokens + - Auth object#auth-object + Auth API properties: + - clientId#client-id + Auth API methods: + - authorize + - createTokenRequest#create-token-request + - requestToken#request-token + - revokeTokens#revoke-tokens + Types: + - Related Types#related-types +redirect_from: + - /docs/api/versions/v1.1/rest-sdk/authentication + - /docs/api/versions/v1.0/rest-sdk/authentication + - /docs/api/versions/v0.8/rest-sdk/authentication +--- + +This is the Authentication API Reference. + +## Tokens + +In the documentation, references to Ably-compatible tokens typically refer either to an Ably Token, or an [Ably JWT](#ably-jwt). For Ably Tokens, this can either be referring to the `TokenDetails` object that contain the `token` string or the token string itself. `TokenDetails` objects are obtained when [requesting an Ably Token](#request-token) from the Ably service and contain not only the `token` string in the `token` attribute, but also contain attributes describing the properties of the Ably Token. For [Ably JWT](#ably-jwt), this will be simply referring to a JWT which has been signed by an Ably private API key. + +## Auth object + +The principal use-case for the `Auth` object is to create Ably [`TokenRequest`](#token-request) objects with [`createTokenRequest`](#create-token-request) or obtain [Ably Tokens](#token-details) from Ably with [`requestToken`](#request-token), and then issue them to other "less trusted" clients. Typically, your servers should be the only devices to have a [private API key](/docs/auth#api-key), and this private API key is used to securely sign Ably [`TokenRequest`](#token-request) objects or request [Ably Tokens](#token-details) from Ably. Clients are then issued with these short-lived [Ably Tokens](#token-details) or Ably [`TokenRequest`](#token-request) objects, and the libraries can then use these to authenticate with Ably. If you adopt this model, your private API key is never shared with clients directly. + +A subsidiary use-case for the `Auth` object is to preemptively trigger renewal of a token or to acquire a new token with a revised set of capabilities by explicitly calling [`authorize`](#authorize)[`Authorize`](#authorize). + +The Auth object is available as the [`auth` field](/docs/api/rest-sdk#auth)[`auth` property](/docs/api/rest-sdk#auth)[`Auth` property](/docs/api/rest-sdk#auth)[`auth` attribute](/docs/api/rest-sdk#auth) of an [Ably REST client instance](/docs/api/rest-sdk#constructor). + +## Auth PropertiesAbly\Auth Propertiesio.ably.lib.rest.Auth MembersAbly::Auth AttributesAuth AttributesARTAuth Properties + +The `ART``Auth` object exposes the following public propertiesattributesmembers: + +### clientIdclient_idClientIdClientID + +The client ID string, if any, configured for this client connection. See [identified clients](#identified-clients) for more information on trusted client identifiers. + +## Auth Methodsio.ably.lib.rest.Auth MethodsAbly::Auth MethodsAbly\Auth MethodsARTAuth Methods + +### authorizeAuthorize + + + +`authorize(tokenParams?: TokenParams, authOptions?: AuthOptions): Promise` + + + + +`TokenDetails authorize(TokenParams token_params, AuthOptions auth_options)` + + + + +`TokenDetails authorize(token_params=TokenParams, auth_options=AuthOptions)` + + + + +`TokenDetails authorize(TokenParams $tokenParams, AuthOptions $authOptions)` + + + + +`TokenDetails authorize(TokenParams tokenParams, AuthOptions authOptions)` + + + + +`Task AuthorizeAsync(TokenParams tokenParams = null, AuthOptions options = null);` + + + + +`TokenDetails Authorize(TokenParams tokenParams, AuthOptions authOptions)` + + + + +`authorize(tokenParams: ARTTokenParams?, authOptions: ARTAuthOptions?, callback: (ARTTokenDetails?, NSError?) -> Void)` + + + +Instructs the library to get a new token immediately using the specified `token_params` and `auth_options``tokenParams` and `authOptions``TokenParams` and `AuthOptions` (or if none specified, the client library defaults). Also stores any `token_params` and `auth_options``tokenParams` and `authOptions``TokenParams` and `AuthOptions` passed in as the new defaults, to be used for all subsequent implicit or explicit token requests. + +Any `token_params` and `auth_options``tokenParams` and `authOptions``TokenParams` and `AuthOptions` objects passed in will entirely replace (as opposed to being merged with) the currently saved `token_params` and `auth_options``tokenParams` and `authOptions`. + +#### Parameters + + + +| Parameter | Description | Type | +|-----------|-------------|------| +| token_paramstokenParamsTokenParams | An optional object containing the [Ably Token parameters](#token-params)An optional [`TokenParams`](#token-params) object containing the token parametersAn optional Dict containing the [Ably Token parameters](#token-params)An optional set of key value pairs containing the [Ably Token parameters](#token-params)An optional set of key value pairs in an associative array containing the [Ably Token parameters](#token-params) for the authorization request | [`TokenParams`](#token-params) | +| auth_optionsauthOptionsAuthOptions | An optional object containing the [authentication options](#auth-options)An optional [`AuthOptions`](#auth-options) object containing the authentication optionsAn optional Dict containing the [authentication options](#auth-options)An optional set of key value pairs containing the [authentication options](#auth-options)An optional set of key value pairs in an associative array containing the [authentication options](#auth-options) for the authorization request | [`AuthOptions`](#auth-options) | + + + + +| Parameter | Description | Type | +|-----------|-------------|------| +| tokenParams | An optional object containing the [Ably Token parameters](#token-params) for the authorization request | [`ARTTokenParams`](#token-params) | +| authOptions | An optional object containing the [authentication options](#auth-options) for the authorization request | [`ARTAuthOptions`](#auth-options) | +| callback | Called with a [`ARTTokenDetails`](#token-details) object or an error | Callback | + + + + + +#### Returns + +Returns a promise. + +On success, the promise is fulfilled with the a [`TokenDetails`](#token-details) object containing the details of the new or existing [Ably Token](#token-details) along with the `token` string. + +On failure to obtain an token, the promise is rejected with an [`ErrorInfo`](/docs/api/rest-sdk/types#error-info) object with the error response as defined in the [Ably REST API](/docs/api/rest-api#common) documentation. + + + + +#### Callback result + +On success, `tokenDetails` contains a [`TokenDetails`](#token-details) object containing the details of the new or existing [Ably Token](#token-details) along with the `token` string. + +On failure to obtain an token, `err` contains an `NSError` object with an error response as defined in the [Ably REST API](/docs/api/rest-api#common) documentation. + + + + +#### Returns + +On success, a [`TokenDetails`](#token-details) object containing the details of the new or existing token along with the `token` string is returned. + +Failure to obtain an token will raise an [`AblyException`](#ably-exception). + + + + +#### Returns + +The method is asynchronous and returns a `Task` which needs to be awaited. + +On success, a [`TokenDetails`](#token-details) object containing the details of the new or existing token along with the `token` string is returned. + +Failure to obtain a token will raise an [`AblyException`](#ably-exception). + + + +#### Example + + + + +```javascript +try { + const tokenDetails = await client.auth.authorize({ clientId: 'bob' }); + console.log('Success; token: ' + tokenDetails.token); +} catch (error) { + console.log('An error occurred; err = ' + error.message); +} +``` + + + + + + +```nodejs +try { + const tokenDetails = await client.auth.authorize({ clientId: 'bob' }); + console.log('Success; token: ' + tokenDetails.token); +} catch (error) { + console.log('An error occurred; err = ' + error.message); +} +``` + + + + + + +```java +try { + TokenParams tokenParams = new TokenParams(); + tokenParams.clientId = "bob"; + TokenDetails tokenDetails = client.auth.authorize(tokenParams, null); + System.out.println("Success; token = " + tokenDetails.token); +} catch(AblyException e) { + System.out.println("An error occurred; err = " + e.getMessage()); +} +``` + + + + + + +```csharp +try +{ + TokenParams tokenParams = new TokenParams { ClientId = "bob" }; + TokenDetails tokenDetails = await client.Auth.AuthorizeAsync(tokenParams); + Console.WriteLine("Success; token = " + tokenDetails.Token); +} +catch (AblyException e) +{ + Console.WriteLine("An error occurred; err = " + e.Message); +} +``` + + + + + + +```ruby +token_details = client.auth.authorize(client_id: 'bob') +puts "Success; token = #{token_details.token}" +``` + + + + + + +```python +token_details = client.auth.authorize(token_params={'client_id': 'bob'}) +print("Success; token = " + str(token_details.token)) +``` + + + + + + +```php +$tokenDetails = $client->auth->authorize(array('clientId' => 'bob')); +echo("Success; token = " . $tokenDetails->token); +``` + + + + + + +```objc +ARTTokenParams *tokenParams = [[ARTTokenParams alloc] initWithClientId:@"Bob"]; +[client.auth authorize:tokenParams options:nil callback:^(ARTTokenDetails *tokenDetails, NSError *error) { + if (error) { + NSLog(@"An error occurred; err = %@", error); + } else { + NSLog(@"Success; token = %@", tokenDetails.token); + } +}]; +``` + + + + + + +```swift +let tokenParams = ARTTokenParams(clientId: "Bob") +client.auth.authorize(tokenParams, options: nil) { tokenDetails, error in + guard let tokenDetails = tokenDetails else { + print("An error occurred; err = \(error!)") + return + } + print("Success; token = \(tokenDetails.token)") +} +``` + + + + + + +```go +tokenParams := &ably.TokenParams{ + ClientID: "Bob", +} +token, err := client.Auth.Authorize(tokenParams, &ably.AuthOptions{}) +if err != nil { + fmt.Println(err) +} +fmt.Println(token) +``` + + + + +### createTokenRequestCreateTokenRequestcreate_token_request + + + +`createTokenRequest(tokenParams?: TokenParams, authOptions?: AuthOptions): Promise` + + + + +`TokenRequest create_token_request(TokenParams token_params, AuthOptions auth_options)` + + + + +`TokenRequest create_token_request(token_params=TokenParams, key_name=String, key_secret=String)` + + + + +`TokenRequest createTokenRequest(TokenParams $tokenParams, AuthOptions $authOptions)` + + + + +`TokenRequest createTokenRequest(TokenParams tokenParams, AuthOptions authOptions)` + + + + +`TokenRequest CreateTokenRequest(TokenParams tokenParams, AuthOptions authOptions)` + + + + +`Task CreateTokenRequestAsync(TokenParams tokenParams = null, AuthOptions authOptions = null)` + + + + +`createTokenRequest(tokenParams: ARTTokenParams?, options: ARTAuthOptions?, callback: (ARTTokenRequest?, NSError?) -> Void)` + + + +Creates and signs an Ably [`TokenRequest`](#request-token) based on the specified `token_params` and `auth_options``tokenParams` and `authOptions``TokenParams` and `AuthOptions``tokenParams` and `authOptions`. Note this can only be used when the [API `key`](/docs/auth#api-key) value is available locally, due to it being required to sign the Ably [`TokenRequest`](#request-token). Otherwise, Ably [`TokenRequests`](#request-token) must be obtained from the key owner. Use this to generate Ably [`TokenRequests`](#request-token) in order to implement an [Ably Token](#token-details) request callback for use by other clients. + +Both `auth_options` and `token_params``authOptions` and `tokenParams``AuthOptions` and `TokenParams``authOptions` and `tokenParams` are optional. When omitted or `null``Null``None``nil`, the default Ably-compatible token parameters and authentication options for the client library are used, as specified in the `ClientOptions` when the client library was instantiated, or later updated with an explicit [`authorize`](#authorize)[`Authorize`](#authorize) request. Values passed in will be used instead of (rather than being merged with) the default values. + +To understand why an Ably [`TokenRequest`](#request-token) may be issued to clients in favor of an [Ably Token](#token-details), see [Token Authentication explained](/docs/auth/token). + +#### Parameters + + + +| Parameter | Description | Type | +|-----------|-------------|------| +| token_paramstokenParamsTokenParams | An optional object containing the [token parameters](#token-params)An optional [`TokenParams`](#token-params) object containing the token parametersAn optional Dict containing the [token parameters](#token-params)An optional set of key value pairs containing the [token parameters](#token-params)An optional set of key value pairs in an associative array containing the [token parameters](#token-params)An optional [`TokenParams`](#token-params) object containing the token parameters for the Ably [`TokenRequest`](#request-token) | [`TokenParams`](#token-params) | +| auth_options[auth options]authOptionsAuthOptions | An optional object containing the [authentication options](#auth-options)An optional [`AuthOptions`](#auth-options) object containing the authentication optionsVarious keyword arguments with the [authentication options](#auth-options)An optional set of key value pairs containing the [authentication options](#auth-options)An optional set of key value pairs in an associative array containing the [authentication options](#auth-options) for the [Ably Token](#token-details) Request | [`AuthOptions`](#auth-options) | + + + + +| Parameter | Description | Type | +|-----------|-------------|------| +| tokenParams | An optional object containing the [token parameters](#token-params) for the Ably [`TokenRequest`](#request-token) | [`ARTTokenParams`](#token-params) | +| authOptions | An optional object containing the [authentication options](#auth-options) for the [Ably Token](#token-details) Request | [`ARTAuthOptions`](#auth-options) | +| callback | Called with a [`ARTTokenRequest`](#token-request) object or an error | Callback | + + + + + +#### Returns + +Returns a promise. + +On success, the promise is fulfilled with a [`TokenRequest`](#token-request) JSON object. + +On failure to issue a [`TokenRequest`](#token-request), the promise is rejected with an [`ErrorInfo`](/docs/api/rest-sdk/types#error-info) object with the error response as defined in the [Ably REST API](/docs/api/rest-api#common) documentation. + + + + +#### Callback result + +On success, `tokenRequest` contains a [`TokenRequest`](#token-request) JSON object. + +On failure to issue a [`TokenRequest`](#token-request), `err` contains an [`ErrorInfo`](#error-info) object with an error response as defined in the [Ably REST API](/docs/api/rest-api#common) documentation. + + + + +#### Returns + +On success, a [`TokenRequest`](#token-request) object is returned. + +Failure to issue a [`TokenRequest`](#token-request) will raise an [`AblyException`](#ably-exception). + + + + +#### Returns + +The method is asynchronous and returns a `Task` which needs to be awaited. + +On success, a [`TokenRequest`](#token-request) object is returned. + +Failure to issue a [`TokenRequest`](#token-request) will raise an [`AblyException`](#ably-exception). + + + +#### Example + + + + +```javascript +try { + const tokenRequest = await client.auth.createTokenRequest({ clientId: 'bob' }); + console.log('Success; token request = ' + tokenRequest); +} catch (error) { + console.log('An error occurred; err = ' + error.message); +} +``` + + + + + + +```java +try { + TokenParams tokenParams = new TokenParams(); + tokenParams.clientId = "bob"; + TokenRequest tokenRequest = client.auth.createTokenRequest(tokenParams, null); + System.out.println("Success; token request issued"); +} catch(AblyException e) { + System.out.println("An error occurred; err = " + e.getMessage()); +} +``` + + + + + + +```csharp +try +{ + TokenParams tokenParams = new TokenParams { ClientId = "bob" }; + var tokenRequest = await client.Auth.CreateTokenRequestAsync(tokenParams); + Console.WriteLine("Success; token request issued"); +} +catch (AblyException e) +{ + Console.WriteLine("An error occurred; err = " + e.Message); +} +``` + + + + + + +```ruby +token_request = client.auth.create_token_request(client_id: 'bob') +puts "Success; token request = #{token_request}" +``` + + + + + + +```python +token_request = client.auth.create_token_request(token_params={'client_id': 'bob'}) +print("Success; token request = ' + str(token_request)) +``` + + + + + + +```php +$tokenRequest = $client->auth->createTokenRequest(array('clientId' => 'bob')) +echo("Success; token request = " . $tokenRequest); +``` + + + + + + +```objc +ARTTokenParams *tokenParams = [[ARTTokenParams alloc] initWithClientId:@"Bob"]; +[client.auth createTokenRequest:tokenParams options:nil callback:^(ARTTokenRequest *tokenRequest, NSError *error) { + if (error) { + NSLog(@"An error occurred; err = %@", error); + } else { + NSLog(@"Success; token request = %@", tokenRequest); + } +}]; +``` + + + + + + +```swift +let tokenParams = ARTTokenParams(clientId: "Bob") +client.auth.createTokenRequest(tokenParams, options: nil) { tokenRequest, error in + guard let tokenRequest = tokenRequest else { + print("An error occurred; err = \(error!)") + return + } + print("Success; token request = \(tokenRequest)") +} +``` + + + + + + +```go +tokenParams := &ably.TokenParams{ + ClientID: "Bob", +} +tokenRequest, err := client.Auth.CreateTokenRequest(tokenParams, &ably.AuthOptions{}) +if err != nil { + fmt.Println(err) +} +fmt.Println(tokenRequest) +``` + + + + +### requestTokenrequest_tokenRequestToken + + + +`requestToken(tokenParams?: TokenParams, authOptions?: AuthOptions): Promise` + + + + +`TokenDetails request_token(TokenParams token_params, AuthOptions auth_options)` + + + + +`TokenDetails request_token(token_params=TokenParams, key_name=String, key_secret=None, auth_callback=Lambda, auth_url=String, auth_method=String, auth_headers=Dict, auth_params=Dict, query_time=Boolean)` + + + + +`TokenDetails requestToken(TokenParams $tokenParams, AuthOptions $authOptions)` + + + + +`TokenDetails requestToken(TokenParams tokenParams, AuthOptions authOptions)` + + + + +`Task RequestTokenAsync(TokenParams tokenParams = null, AuthOptions options = null)` + + + + +`TokenDetails RequestToken(TokenParams tokenParams, AuthOptions authOptions)` + + + + +`requestToken(tokenParams: ARTTokenParams?, withOptions: ARTAuthOptions?, callback: (ARTTokenDetails?, NSError?) -> Void)` + + + +Calls the [`requestToken` REST API endpoint](/docs/api/rest-api#request-token)[`RequestToken` REST API endpoint](/docs/api/rest-api#request-token) to obtain an [Ably Token](#token-details) according to the specified `token_params` and `auth_options``tokenParams` and `authOptions``tokenParams` and `authOptions`. + +Both `auth_options` and `token_params``authOptions` and `tokenParams``authOptions` and `tokenParams` are optional. When omitted or `null``Null``None``nil``null`, the default token parameters and authentication options for the client library are used, as specified in the `ClientOptions` when the client library was instantiated, or later updated with an explicit [`authorize`](#authorize)[`Authorize`](#authorize) request. Values passed in will be used instead of (rather than being merged with) the default values. + +To understand why an Ably [`TokenRequest`](#request-token) may be issued to clients in favor of an [Ably Token](#token-details), see [Token Authentication explained](/docs/auth/token). + +#### Parameters + + + +| Parameter | Description | Type | +|-----------|-------------|------| +| token_paramstokenParamstokenParams | An optional object containing the [token parameters](#token-params)An optional Dict containing the [token parameters](#token-params)An optional [`TokenParams`](#token-params) object containing the token parametersAn optional set of key value pairs containing the [token parameters](#token-params)An optional set of key value pairs in an associative array containing the [token parameters](#token-params)An optional object containing the [token parameters](#token-params) for the requested [Ably Token](#token-details) | [`TokenParams`](#token-params) | +| [auth options]auth_optionsauthOptions | An optional object containing the [authentication options](#auth-options)Various keyword arguments with the [authentication options](#auth-options)An optional [`AuthOptions`](#auth-options) object containing the authentication optionsAn optional set of key value pairs containing the [authentication options](#auth-options)An optional set of key value pairs in an associative array containing the [authentication options](#auth-options)An optional object containing the [authentication options](#auth-options) for the requested [Ably Token](#token-details) | [`AuthOptions`](#auth-options) | + + + + +| Parameter | Description | Type | +|-----------|-------------|------| +| tokenParams | An optional object containing the [token parameters](#token-params) for the requested [Ably Token](#token-details) | [`ARTTokenParams`](#token-params) | +| authOptions | An optional object containing the [authentication options](#auth-options) for the requested [Ably Token](#token-details) | [`ARTAuthOptions`](#auth-options) | +| callback | Called with a [`ARTTokenDetails`](#token-details) object or an error | Callback | + + + + + +#### Returns + +Returns a promise. + +On success, the promise is fulfilled with a [`TokenDetails`](#token-details) object containing the details of the new [Ably Token](#token-details) along with the `token` string. + +On failure to obtain an [Ably Token](#token-details), the promise is rejected with an [`ErrorInfo`](/docs/api/rest-sdk/types#error-info) object with the error response as defined in the [Ably REST API](/docs/api/rest-api#common) documentation. + + + + +#### Callback result + +On success, `tokenDetails` contains a [`TokenDetails`](#token-details) object containing the details of the new [Ably Token](#token-details) along with the `token` string. + +On failure to obtain an [Ably Token](#token-details), `err` contains an `NSError` object with an error response as defined in the [Ably REST API](/docs/api/rest-api#common) documentation. + + + +#### Returns + +On success, a [`TokenDetails`](#token-details) object containing the details of the new [Ably Token](#token-details) along with the `token` string is returned. + +Failure to obtain an [Ably Token](#token-details) will raise an [`AblyException`](#ably-exception). + + + +#### Returns + +The method is asynchronous and returns a `Task` which needs to be awaited. + +On success, a [`TokenDetails`](#token-details) object containing the details of the new [Ably Token](#token-details) along with the `token` string is returned. + +Failure to obtain an [Ably Token](#token-details) will raise an [`AblyException`](#ably-exception). + + +#### Example + + + + +```javascript +try { + const tokenDetails = await client.auth.requestToken({ clientId: 'bob'}); + console.log('Success; token = ' + tokenDetails.token); +} catch (error) { + console.log('An error occurred; err = ' + error.message); +} +``` + + + + + + +```nodejs +try { + const tokenDetails = await client.auth.requestToken({ clientId: 'bob'}); + console.log('Success; token = ' + tokenDetails.token); +} catch (error) { + console.log('An error occurred; err = ' + error.message); +} +``` + + + + + + + +```ruby +token_details = client.auth.request_token(client_id: 'bob') +puts "Success; token = #{token_details.token}" +``` + + + + + + + +```python +token_details = client.auth.request_token(token_params={'client_id': 'bob'}) +print("Success; token = " + str(token_details.token)) +``` + + + + + + + +```php +$tokenDetails = $client->auth->requestToken(array('clientId' => 'bob')) +echo("Success; token = " . $tokenDetails->token); +``` + + + + + + + +```java +try { + TokenParams tokenParams = new TokenParams(); + tokenParams.clientId = "bob"; + TokenDetails tokenDetails = client.auth.requestToken(tokenParams, null); + System.out.println("Success; token = " + tokenDetails.token); +} catch(AblyException e) { + System.out.println("An error occurred; err = " + e.getMessage()); +} +``` + + + + + + + +```csharp +try { + TokenParams tokenParams = new TokenParams { ClientId = "bob" }; + var tokenDetails = await client.Auth.RequestTokenAsync(tokenParams); + Console.WriteLine("Success; token = " + tokenDetails.Token); +} +catch (AblyException e) +{ + Console.WriteLine("An error occurred; err = " + e.Message); +} +``` + + + + + + + +```objc +ARTTokenParams *tokenParams = [[ARTTokenParams alloc] initWithClientId:@"Bob"]; +[client.auth requestToken:tokenParams withOptions:nil callback:^(ARTTokenDetails *tokenDetails, NSError *error) { + if (error) { + NSLog(@"An error occurred; err = %@", error); + } else { + NSLog(@"Success; token = %@", tokenDetails.token); + } +}]; +``` + + + + + + + +```swift +let tokenParams = ARTTokenParams(clientId: "Bob") +client.auth.requestToken(tokenParams, withOptions: nil) { tokenDetails, error in + guard let tokenDetails = tokenDetails else { + print("An error occurred; err = \(error!)") + return + } + print("Success; token = \(tokenDetails.token)") +} +``` + + + + + + + +```go +tokenParams := &ably.TokenParams{ + ClientID: "Bob", +} +token, err := client.Auth.RequestToken(tokenParams, &ably.AuthOptions{}) +if err != nil { + fmt.Println(err) +} +fmt.Println(token) +``` + + + + + + +### revokeTokens + +`revokeTokens(TokenRevocationTargetSpecifier[] specifiers, TokenRevocationOptions options?): Promise>` + +Calls the [`revokeTokens` REST API endpoint](/docs/api/rest-api#revoke-tokens) to revoke tokens specified by the provided array of [`TokenRevocationTargetSpecifier`](#token-revocation-target-specifier). + +Only tokens issued by an API key that had revocable tokens enabled before the token was issued can be revoked. See the [token revocation docs](/docs/auth/revocation) for more information. + +#### Parameters + +| Parameter | Description | Type | +|-----------|-------------|------| +| specifiers | an array of [`TokenRevocationTargetSpecifier`](#token-revocation-target-specifier) objects | [`TokenRevocationTargetSpecifier[]`](#token-revocation-target-specifier) | +| options | an optional set of options which are used to modify the revocation request | [`TokenRevocationOptions`](#token-revocation-options) | + +#### Returns + +Returns a promise. + +On success, the promise is fulfilled with a [`BatchResult`](#batch-result) containing information about the result of the token revocation request for each provided [`TokenRevocationTargetSpecifier`](#token-revocation-target-specifier). + +On failure, the promise is rejected with an [`ErrorInfo`](/docs/api/rest-sdk/types#error-info) object with the error response as defined in the [Ably REST API](/docs/api/rest-api#common) documentation. + +#### Example + + + + +```javascript +try { + const response = await client.auth.revokeTokens([{ type: 'clientId', value: 'bob' }]); + console.log('Revocation successful; revoked tokens: ' + response.results.length); +} catch (error) { + console.log('An error occurred; err = ' + error.message); +} +``` + + + + + + +```nodejs +try { + const response = await client.auth.revokeTokens([{ type: 'clientId', value: 'bob' }]); + console.log('Revocation successful; revoked tokens: ' + response.results.length); +} catch (error) { + console.log('An error occurred; err = ' + error.message); +} +``` + + + + + +## Related types + +### AuthOptions ObjectAuthOptions Hashio.ably.lib.rest.Auth.AuthOptions + + +`AuthOptions` is a plain JavaScript object and is used when making [authentication](/docs/auth) requests. If passed in, an `authOptions` object will be used instead of (as opposed to supplementing or being merged with) the default values given when the library was instantiated. The following attributes are supported: + + + +`AuthOptions` is a Hash object and is used when making [authentication](/docs/auth) requests. These options will supplement or override the corresponding options given when the library was instantiated. The following key symbol values can be added to the Hash: + + + +`AuthOptions` is a Dict and is used when making [authentication](/docs/auth) requests. These options will supplement or override the corresponding options given when the library was instantiated. The following key symbol values can be added to the Dict: + + + +`AuthOptions` is an Associative Array and is used when making [authentication](/docs/auth) requests. These options will supplement or override the corresponding options given when the library was instantiated. The following named keys and values can be added to the Associative Array: + + + +`AuthOptions` is used when making [authentication](/docs/auth) requests. These options will supplement or override the corresponding options given when the library was instantiated. + + + +`ARTAuthOptions` is used when making [authentication](/docs/auth) requests. These options will supplement or override the corresponding options given when the library was instantiated. + + +#### PropertiesMembersAttributes + +| Name | Description | Type | +|------|-------------|------| +| authCallbackAuthCallbackauth_callback:auth_callback | A functionfunction with the form `function(tokenParams, callback(err, tokenOrTokenRequest))``TokenCallback` instancecallable (eg a lambda)proc / lambda (called synchronously in REST and Realtime but does not block EventMachine in the latter)function which is called when a new token is required. The role of the callback is to obtain a fresh token, one of: an Ably Token string (in plain text format); a signed [`TokenRequest`](/docs/api/realtime-sdk/types#token-request); a [`TokenDetails`](/docs/api/realtime-sdk/types#token-details) (in JSON format); an [Ably JWT](/docs/api/realtime-sdk/authentication#ably-jwt). See [our authentication documentation](/docs/auth) for details of the Ably TokenRequest format and associated API calls. | `Callable``TokenCallback``Proc``Func>``Callable``Callable` | +| authUrlAuthUrl:auth_urlauth_url | A URL that the library may use to obtain a fresh token, one of: an Ably Token string (in plain text format); a signed [`TokenRequest`](/docs/api/realtime-sdk/types#token-request); a [`TokenDetails`](/docs/api/realtime-sdk/types#token-details) (in JSON format); an [Ably JWT](/docs/api/realtime-sdk/authentication#ably-jwt). For example, this can be used by a client to obtain signed Ably TokenRequests from an application server. | `String``Uri``NSURL` | +| authMethodAuthMethodauth_method:auth_method | _`GET``:get`_ The HTTP verb to use for the request, either `GET``:get` or `POST``:post` | `String``Symbol``HttpMethod` | +| authHeadersAuthHeadersauth_headers:auth_headers | A set of key value pair headers to be added to any request made to the authUrlAuthUrlAuthUrl. Useful when an application requires these to be added to validate the request or implement the response. If the `authHeaders` object contains an `authorization` key, then `withCredentials` will be set on the xhr request. | `Object``Dict``Hash``Associative Array``Param []``Dictionary` | +| authParamsAuthParams:auth_paramsauth_params | A set of key value pair params to be added to any request made to the authUrlAuthUrl. When the authMethodAuthMethod is `GET`, query params are added to the URL, whereas when authMethodAuthMethod is `POST`, the params are sent as URL encoded form data. Useful when an application require these to be added to validate the request or implement the response. | `Object``Hash``Associative Array``Param[]``Dictionary``NSArray``[NSURLQueryItem]/Array``Object` | +| tokenDetailsTokenDetailstoken_details:token_details | An authenticated [`TokenDetails`](/docs/api/realtime-sdk/types#token-details) object (most commonly obtained from an Ably Token Request response). This option is mostly useful for testing: since tokens are short-lived, in production you almost always want to use an authentication method that allows the client library to renew the token automatically when the previous one expires, such as authUrlAuthUrl:auth_urlauth_url or authCallbackAuthCallbackauth_callback:auth_callback. Use this option if you wish to use Token authentication. Read more about [Token authentication](/docs/auth/token) | `TokenDetails` | +| keyKey:keykey | Optionally the [API key](/docs/auth#api-key) to use can be specified as a full key string; if not, the API key passed into [`ClientOptions`](#client-options) when instancing the Realtime or REST library is used | `String` | +| queryTimeQueryTime:query_timequery_time | _false_ If true, the library will query the Ably servers for the current time when [issuing TokenRequests](/docs/auth/token) instead of relying on a locally-available time of day. Knowing the time accurately is needed to create valid signed Ably [TokenRequests](/docs/auth/token), so this option is useful for library instances on auth servers where for some reason the server clock cannot be kept synchronized through normal means, such as an [NTP daemon](https://en.wikipedia.org/wiki/Ntpd). The server is queried for the current time once per client library instance (which stores the offset from the local clock), so if using this option you should avoid instancing a new version of the library for each request. | `Boolean` | +| tokenToken:tokentoken | An authenticated token. This can either be a [`TokenDetails`](/docs/api/realtime-sdk/types#token-details) object, a [`TokenRequest`](/docs/api/realtime-sdk/types#token-request) object, or token string (obtained from the tokenTokentokentoken property of a [`TokenDetails`](/docs/api/realtime-sdk/types#token-details) component of an Ably TokenRequest response, or a [JSON Web Token](https://tools.ietf.org/html/rfc7519) satisfying [the Ably requirements for JWTs](/docs/auth/token#jwt)). This option is mostly useful for testing: since tokens are short-lived, in production you almost always want to use an authentication method that allows the client library to renew the token automatically when the previous one expires, such as authUrlAuthUrl:auth_urlauth_url or authCallbackAuthCallbackauth_callback:auth_callback. Read more about [Token authentication](/docs/auth/token) | `String`, `TokenDetails` or `TokenRequest` | + +### TokenDetails ObjectARTTokenDetailsio.ably.lib.types.TokenDetailsAbly::Models::TokenDetails + +`TokenDetails` is a type providing details of Ably Token string and its associated metadata. + +#### PropertiesMembersAttributes + +| Name | Description | Type | +|------|-------------|------| +| tokenToken | The [Ably Token](/docs/api/realtime-sdk/authentication#token-details) itself. A typical [Ably Token](/docs/api/realtime-sdk/authentication#token-details) string may appear like `{{TOKEN}}` | `String` | +| expiresExpires | The time (in milliseconds since the epoch)The time at which this token expires | `Integer``Long Integer``DateTimeOffset``Time``NSDate` | +| issuedIssued | The time (in milliseconds since the epoch)The time at which this token was issued | `Integer``Long Integer``DateTimeOffset``Time``NSDate` | +| capabilityCapability | The capability associated with this [Ably Token](/docs/api/realtime-sdk/authentication#token-details). The capability is a a JSON stringified canonicalized representation of the resource paths and associated operations. [Read more about authentication and capabilities](/docs/auth/capabilities) | `String``Capability` | +| clientIdclient_idClientId | The client ID, if any, bound to this [Ably Token](/docs/api/realtime-sdk/authentication#token-details). If a client ID is included, then the [Ably Token](/docs/api/realtime-sdk/authentication#token-details) authenticates its bearer as that client ID, and the [Ably Token](/docs/api/realtime-sdk/authentication#token-details) may only be used to perform operations on behalf of that client ID. The client is then considered to be an [identified client](/docs/auth/identified-clients) | `String` | + + +### Methods + +| Name | Description | Type | +|------|-------------|------| +| expired? | True when the token has expired | `Boolean` | + + + + +### Methods + +| Name | Description | Type | +|------|-------------|------| +| is_expired() | True when the token has expired | `Boolean` | + + + + +### Methods + +| Name | Description | Type | +|------|-------------|------| +| IsValidToken() | True if the token has not expired | `Boolean` | + + + +### TokenDetails constructors + +#### TokenDetails.fromJsonTokenDetails.from_json + + +`TokenDetails.fromJson(String json) -> TokenDetails` + + + +`TokenDetails.from_json(String json) -> TokenDetails` + + +A static factory method to create a [`TokenDetails`](/docs/api/realtime-sdk/types#token-details) from a deserialized `TokenDetails`-like object or a JSON stringified `TokenDetails`. This method is provided to minimize bugs as a result of differing types by platform for fields such as `timestamp` or `ttl`. For example, in Ruby `ttl` in the `TokenDetails` object is exposed in seconds as that is idiomatic for the language, yet when serialized to JSON using `to_json` it is automatically converted to the Ably standard which is milliseconds. By using the `fromJson` method when constructing a `TokenDetails`, Ably ensures that all fields are consistently serialized and deserialized across platforms. + +#### Parameters + +| Parameter | Description | Type | +|-----------|-------------|------| +| json | a `TokenDetails`-like deserialized object or JSON stringified `TokenDetails` | `Object, String` | + +#### Returns + +A [`TokenDetails`](/docs/api/realtime-sdk/types#token-details) object + +### TokenParams ObjectARTTokenParamsTokenParams Hashio.ably.lib.rest.Auth.TokenParams + + +`TokenParams` is a plain JavaScript object and is used in the parameters of [token authentication](/docs/auth/token) requests, corresponding to the desired attributes of the [Ably Token](/docs/api/realtime-sdk/authentication#token-details). The following attributes can be defined on the object: + + + +`TokenParams` is a Hash object and is used in the parameters of [token authentication](/docs/auth/token) requests, corresponding to the desired attributes of the [Ably Token](/docs/api/realtime-sdk/authentication#token-details). The following key symbol values can be added to the Hash: + + + +`TokenParams` is a Dict and is used in the parameters of [token authentication](/docs/auth/token) requests, corresponding to the desired attributes of the [Ably Token](/docs/api/realtime-sdk/authentication#token-details). The following keys-value pairs can be added to the Dict: + + + +`TokenParams` is an Associative Array and is used in the parameters of [token authentication](/docs/auth/token) requests, corresponding to the desired attributes of the [Ably Token](/docs/api/realtime-sdk/authentication#token-details). The following named keys and values can be added to the Associative Array: + + + +`TokenParams` is used in the parameters of [token authentication](/docs/auth/token) requests, corresponding to the desired attributes of the [Ably Token](/docs/api/realtime-sdk/authentication#token-details). + + + +`ARTTokenParams` is used in the parameters of [token authentication](/docs/auth/token) requests, corresponding to the desired attributes of the [Ably Token](/docs/api/realtime-sdk/authentication#token-details). + + +#### PropertiesMembersAttributes + +| Name | Description | Type | +|------|-------------|------| +| capabilityCapability:capability | JSON stringified capability of the [Ably Token](/docs/api/realtime-sdk/authentication#token-details). If the [Ably Token](/docs/api/realtime-sdk/authentication#token-details) request is successful, the capability of the returned [Ably Token](/docs/api/realtime-sdk/authentication#token-details) will be the intersection of this capability with the capability of the issuing key. [Find our more about how to use capabilities to manage access privileges for clients](/docs/auth/capabilities). | `String``Capability` | +| clientIdClientIdclient_id:client_id | A client ID, used for identifying this client when publishing messages or for presence purposes. The clientIdclient_idClientId can be any non-empty string. This option is primarily intended to be used in situations where the library is instantiated with a key; note that a clientIdclient_idClientId may also be implicit in a token used to instantiate the library; an error will be raised if a clientIdclient_idClientId specified here conflicts with the clientIdclient_idClientId implicit in the token. [Find out more about client identities](/docs/auth/identified-clients) | `String` | +| nonceNonce:nonce | An optional opaque nonce string of at least 16 characters to ensure uniqueness of this request. Any subsequent request using the same nonce will be rejected. | `String` | +| timestampTimestamp:timestamp | The timestamp (in milliseconds since the epoch)The timestamp of this request. `timestamp`, in conjunction with the `nonce`, is used to prevent requests for [Ably Token](/docs/api/realtime-sdk/authentication#token-details) from being replayed. | `Integer``Long Integer``Time``NSDate``DateTimeOffset` | +| ttlTtl:ttl | _1 hour_ Requested time to live for the [Ably Token](/docs/api/realtime-sdk/authentication#token-details) being created in millisecondsin secondsas a `NSTimeInterval`as a `TimeSpan`. When omitted, the Ably REST API default of 60 minutes is applied by Ably | `Integer` (milliseconds)`Integer` (seconds)`NSTimeInterval``Long Integer``TimeSpan` | + +### TokenRequest ObjectARTTokenRequestAbly::Models::TokenRequestio.ably.lib.rest.Auth.TokenRequest + +`TokenRequest` is a type containing parameters for an Ably `TokenRequest`. [Ably Tokens](/docs/api/realtime-sdk/authentication#token-details) are requested using [Auth#requestToken](/docs/api/rest-sdk/authentication#request-token)[Auth#request_token](/docs/api/rest-sdk/authentication#request-token) + +#### PropertiesMembersAttributes + +| Name | Description | Type | +|------|-------------|------| +| keyNamekey_nameKeyName | The key name of the key against which this request is made. The key name is public, whereas the key secret is private | `String` | +| ttlTtl | Requested time to live for the [Ably Token](/docs/api/realtime-sdk/authentication#token-details) in millisecondsin secondsas a `TimeSpan`. If the Ably `TokenRequest` is successful, the TTL of the returned [Ably Token](/docs/api/realtime-sdk/authentication#token-details) will be less than or equal to this value depending on application settings and the attributes of the issuing key. | `Integer``TimeSpan``NSTimeInterval``Integer` | +| timestampTimestamp | The timestamp of this request in milliseconds | `Integer``Long Integer``Time``DateTimeOffset``NSDate` | +| capabilityCapability | Capability of the requested [Ably Token](/docs/api/realtime-sdk/authentication#token-details). If the Ably `TokenRequest` is successful, the capability of the returned [Ably Token](/docs/api/realtime-sdk/authentication#token-details) will be the intersection of this capability with the capability of the issuing key. The capability is a JSON stringified canonicalized representation of the resource paths and associated operations. [Read more about authentication and capabilities](/docs/auth) | `String` | +| clientIdclient_idClientId | The client ID to associate with the requested [Ably Token](/docs/api/realtime-sdk/authentication#token-details). When provided, the [Ably Token](/docs/api/realtime-sdk/authentication#token-details) may only be used to perform operations on behalf of that client ID | `String` | +| nonceNonce | An opaque nonce string of at least 16 characters | `String` | +| macMac | The Message Authentication Code for this request | `String` | + +### TokenRequest constructors + +#### TokenRequest.fromJsonTokenRequest.from_json + + +`TokenRequest.fromJson(String json) -> TokenRequest` + + + +`TokenRequest.from_json(String json) -> TokenRequest` + + +A static factory method to create a [`TokenRequest`](/docs/api/realtime-sdk/types#token-request) from a deserialized `TokenRequest`-like object or a JSON stringified `TokenRequest`. This method is provided to minimize bugs as a result of differing types by platform for fields such as `timestamp` or `ttl`. For example, in Ruby `ttl` in the `TokenRequest` object is exposed in seconds as that is idiomatic for the language, yet when serialized to JSON using `to_json` it is automatically converted to the Ably standard which is milliseconds. By using the `fromJson` method when constructing a `TokenRequest`, Ably ensures that all fields are consistently serialized and deserialized across platforms. + +#### Parameters + +| Parameter | Description | Type | +|-----------|-------------|------| +| json | a `TokenRequest`-like deserialized object or JSON stringified `TokenRequest` | `Object, String` | + +#### Returns + +A [`TokenRequest`](/docs/api/realtime-sdk/types#token-request) object + +### Ably JWT + +An Ably JWT is not strictly an Ably construct, rather it is a [JWT](https://jwt.io/) which has been constructed to be compatible with Ably. The JWT must adhere to the following to ensure compatibility: + +* **The JOSE header must include:** + * `kid` - Key name, such that an API key of `{{API_KEY}}` will have key name `{{API_KEY_NAME}}` +* **The JWT claim set must include:** + * `iat` - time of issue in seconds + * `exp` - expiry time in seconds +* **The JWT claim set may include:** + * `x-ably-capability` - JSON text encoding of the [capability](#tokens) + * `x-ably-clientId` - client ID + +Arbitrary additional claims and headers are supported (apart from those prefixed with `x-ably-` which are reserved for future use). + +The Ably JWT must be signed with the secret part of your [Ably API key](/docs/auth#api-key) using the signature algorithm HS256 (HMAC using the SHA-256 hash algorithm). View the [JSON Web Algorithms (JWA) specification](https://tools.ietf.org/html/rfc7518) for further information. + +We recommend you use one of the many [JWT libraries available for simplicity](https://jwt.io/) when creating your JWTs. + + + +The following is an example of creating an Ably JWT: + + + + +```javascript + var header = { + "typ":"JWT", + "alg":"HS256", + "kid": "{{API_KEY_NAME}}" + }; + var currentTime = Math.round(Date.now()/1000); + var claims = { + "iat": currentTime, /* current time in seconds */ + "exp": currentTime + 3600, /* time of expiration in seconds */ + "x-ably-capability": "{\"*\":[\"*\"]}" + }; + var base64Header = btoa(header); + var base64Claims = btoa(claims); + /* Apply the hash specified in the header */ + var signature = hash((base64Header + "." + base64Claims), "{{API_KEY_SECRET}}"); + var ablyJwt = base64Header + "." + base64Claims + "." + signature; +``` + + + + + + +```nodejs + var header = { + "typ":"JWT", + "alg":"HS256", + "kid": "{{API_KEY_NAME}}" + }; + var currentTime = Math.round(Date.now()/1000); + var claims = { + "iat": currentTime, /* current time in seconds */ + "exp": currentTime + 3600, /* time of expiration in seconds */ + "x-ably-capability": "{\"*\":[\"*\"]}" + }; + var base64Header = btoa(header); + var base64Claims = btoa(claims); + /* Apply the hash specified in the header */ + var signature = hash((base64Header + "." + base64Claims), "{{API_KEY_SECRET}}"); + var ablyJwt = base64Header + "." + base64Claims + "." + signature; +``` + + + + +*Note:* At present Ably does not support asymmetric signatures based on a keypair belonging to a third party. + + + + +### BatchResult + +A `BatchResult` contains information about the results of a batch operation. + +#### Properties + +| Property | Description | Type | +|----------|-------------|------| +| successCount | The number of successful operations in the request | `Number` | +| failureCount | The number of unsuccessful operations in the request | `Number` | +| messages | An array of results for the batch operation (for example, an array of [`BatchPublishSuccessResult`](/docs/api/realtime-sdk/types#batch-publish-success-result) or [`BatchPublishFailureResult`](/docs/api/realtime-sdk/types#batch-publish-failure-result) for a channel batch publish request) | `Object[]` | + + + +### TokenRevocationTargetSpecifier + +A `TokenRevocationTargetSpecifier` describes which tokens should be affected by a token revocation request. + + + +#### Properties + +| Property | Description | Type | +|----------|-------------|------| +| type | The type of token revocation target specifier. Valid values include `clientId`, `revocationKey` and `channel` | `String` | +| value | The value of the token revocation target specifier | `String` | + + + +### TokenRevocationOptions + +A `TokenRevocationOptions` describes the additional options accepted by revoke tokens request. + + + +#### Properties + +| Property | Description | Type | +|----------|-------------|------| +| issuedBefore | An optional Unix timestamp in milliseconds where only tokens issued before this time are revoked. The default is the current time. Requests with an `issuedBefore` in the future, or more than an hour in the past, will be rejected | `Number` | +| allowReauthMargin | _false_ If true, permits a token renewal cycle to take place without needing established connections to be dropped, by postponing enforcement to 30 seconds in the future, and sending any existing connections a hint to obtain (and upgrade the connection to use) a new token. The default is `false`, meaning that the effect is near-immediate. | `Boolean` | + + + +### TokenRevocationSuccessResult + +A `TokenRevocationSuccessResult` contains information about the result of a successful token revocation request for a single target specifier. + + + +#### Properties + +| Property | Description | Type | +|----------|-------------|------| +| target | The target specifier | `Number` | +| appliesAt | The time at which the token revocation will take effect, as a Unix timestamp in milliseconds | `Number` | +| issuedBefore | A Unix timestamp in milliseconds. Only tokens issued earlier than this time will be revoked | `Number` | + + + +### TokenRevocationFailureResult + +A `TokenRevocationFailureResult` contains information about the result of an unsuccessful token revocation request for a single target specifier. + + + +#### Properties + +| Property | Description | Type | +|----------|-------------|------| +| target | The target specifier | `String` | +| error | Describes the reason for which token revocation failed for the given `target` as an [`ErrorInfo`](/docs/api/realtime-sdk/types#error-info) object | [`ErrorInfo`](/docs/api/realtime-sdk/types#error-info) | + +