The Token use itself is very simple - in the place where you would usually use the password, you just use the Token itself. Nevertheless here are some examples in different languages.


The Example

Jira

The API call we'll use as an example in Jira is

https://<YOUR_JIRA_BASEURL>/rest/api/2/myself
CODE


This gives you profile information about the currently logged-in User (in our case the User associated with the token).

A result looks like this:

{
    "self": "http://www.example.com/jira/rest/api/2/user?username=fred",
    "name": "fred",
    "emailAddress": "fred@example.com",
    "avatarUrls": {
        "48x48": "http://www.example.com/jira/secure/useravatar?size=large&ownerId=fred",
        "24x24": "http://www.example.com/jira/secure/useravatar?size=small&ownerId=fred",
        "16x16": "http://www.example.com/jira/secure/useravatar?size=xsmall&ownerId=fred",
        "32x32": "http://www.example.com/jira/secure/useravatar?size=medium&ownerId=fred"
    },
    "displayName": "Fred F. User",
    "active": true,
    "timeZone": "Australia/Sydney",
    "groups": {
        "size": 3,
        "items": [
            {
                "name": "jira-user",
                "self": "http://www.example.com/jira/rest/api/2/group?groupname=jira-user"
            },
            {
                "name": "jira-admin",
                "self": "http://www.example.com/jira/rest/api/2/group?groupname=jira-admin"
            },
            {
                "name": "important",
                "self": "http://www.example.com/jira/rest/api/2/group?groupname=important"
            }
        ]
    },
    "applicationRoles": {
        "size": 1,
        "items": []
    },
    "expand": "groups,applicationRoles"
}
CODE

More details in the Atlassian Jira REST Documentation: https://docs.atlassian.com/software/jira/docs/api/REST/7.6.1/#api/2/myself

Confluence

For Confluence the respective call would be:

http://<YOUR_CONFLUENCE_BASEURL>/rest/api/user/current
CODE


This gives you profile information about the currently logged-in User (in our case the User associated with the token).

A result looks like this

{
    "type": "known",
    "username": "jsmith",
    "userKey": "402880824ff933a4014ff9345d7c0002",
    "profilePicture": {
        "path": "/wiki/relative/avatar.png",
        "width": 48,
        "height": 48,
        "isDefault": true
    },
    "displayName": "Joe Smith",
    "_links": {
        "base": "http://myhost:8080/confluence",
        "context": "/confluence",
        "self": "http://myhost:8080/confluence/rest/experimental/user?key=402880824ff933a4014ff9345d7c0002"
    },
    "_expandable": {
        "status": ""
    }
}
CODE

More details in the Atlassian Confluence REST Documentation: https://docs.atlassian.com/atlassian-confluence/REST/6.6.0/#user-getCurrent

Basic Auth header

Most of the following examples will use the basic auth header - that is send.

Basically the Basic Auth Header looks like this:

Authorization: Basic dXNlckBleGFtcGxlLmNvbTpzZWNyZXQ=
CODE

Its value is simply a Base64-encoded representation of "username:password", in our case that would be "<username>:<your-api-token>(like when you place credentials in the URL directly).
There are a variety of website to generate this manually for Lab use like: https://www.blitter.se/utils/basic-authentication-header-generator/

Here are also many examples for different Languages: https://gist.github.com/brandonmwest/a2632d0a65088a20c00a

cURL Example

curl "https://YOUR_JIRA_BASEURL/rest/api/2/myself" \
     -u '<USERNAME>:<YOUR_API_TOKEN>'
CODE

Ruby

Replace in the below:

require 'net/http'
require 'net/https'

# SAML (GET )
def send_request
  uri = URI('https://YOUR_JIRA_BASEURL/rest/api/2/myself')

  # Create client
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_PEER

  # Create Request
  req =  Net::HTTP::Get.new(uri)
  # Add headers
  req.add_field "Authorization", "Basic <YOUR_BASIC_AUTH_HEADER>"

  # Fetch Request
  res = http.request(req)
  puts "Response HTTP Status Code: #{res.code}"
  puts "Response HTTP Response Body: #{res.body}"
rescue StandardError => e
  puts "HTTP Request failed (#{e.message})"
end


CODE


Phyton

Replace in the below:

# Install the Python Requests library:
# `pip install requests`

import requests


def send_request():
    # SAML
    # GET https://YOUR_JIRA_BASEURL/rest/api/2/myself

    try:
        response = requests.get(
            url="https://YOUR_JIRA_BASEURL/rest/api/2/myself",
            headers={
                "Authorization": "Basic <YOUR_BASIC_AUTH_HEADER>",
            },
        )
        print('Response HTTP Status Code: {status_code}'.format(
            status_code=response.status_code))
        print('Response HTTP Response Body: {content}'.format(
            content=response.content))
    except requests.exceptions.RequestException:
        print('HTTP Request failed')



CODE


node.js

Replace in the below:

// request  
(function(callback) {
    'use strict';
        
    const httpTransport = require('https');
    const responseEncoding = 'utf8';
    const httpOptions = {
        hostname: 'YOUR_JIRA_BASEURL',
        port: '443',
        path: '/rest/api/2/myself',
        method: 'GET',
        headers: {"Authorization":"Basic <YOUR_BASIC_AUTH_HEADER>"}
    };
    httpOptions.headers['User-Agent'] = 'node ' + process.version;
 
    // Using Basic Auth {"username":"<USERNAME>","password":"<YOUR_API_TOKEN>"}

    const request = httpTransport.request(httpOptions, (res) => {
        let responseBufs = [];
        let responseStr = '';
        
        res.on('data', (chunk) => {
            if (Buffer.isBuffer(chunk)) {
                responseBufs.push(chunk);
            }
            else {
                responseStr = responseStr + chunk;            
            }
        }).on('end', () => {
            responseStr = responseBufs.length > 0 ? 
                Buffer.concat(responseBufs).toString(responseEncoding) : responseStr;
            
            callback(null, res.statusCode, res.headers, responseStr);
        });
        
    })
    .setTimeout(0)
    .on('error', (error) => {
        callback(error);
    });
    request.write("")
    request.end();
    

})((error, statusCode, headers, body) => {
    console.log('ERROR:', error); 
    console.log('STATUS:', statusCode);
    console.log('HEADERS:', JSON.stringify(headers));
    console.log('BODY:', body);
});




CODE


Java

Replace in the below:

public class SendRequest
{
  public static void main(String[] args) {
    sendRequest();
  }
  
  private static void sendRequest() {
    
    // SAML (GET )
    
    try {
      
      // Create request
      Content content = Request.Get("https://YOUR_JIRA_BASEURL/rest/api/2/myself")
      
      // Add headers
      .addHeader("Authorization", "Basic <YOUR_BASIC_AUTH_HEADER>")
      
      // Fetch request and return content
      .execute().returnContent();
      
      // Print content
      System.out.println(content);
    }
    catch (IOException e) { System.out.println(e); }
  }
}





CODE


PHP

Replace in the below:

<?php

// get cURL resource
$ch = curl_init();

// set url
curl_setopt($ch, CURLOPT_URL, 'https://YOUR_JIRA_BASEURL/rest/api/2/myself');

// set method
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');

// return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// set headers
curl_setopt($ch, CURLOPT_HTTPHEADER, [
  'Authorization: Basic <YOUR_BASIC_AUTH_HEADER>',
]);

// send the request and save response to $response
$response = curl_exec($ch);

// stop if fails
if (!$response) {
  die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
}

echo 'HTTP Status Code: ' . curl_getinfo($ch, CURLINFO_HTTP_CODE) . PHP_EOL;
echo 'Response Body: ' . $response . PHP_EOL;

// close curl resource to free up system resources 
curl_close($ch);

CODE


GO

Replace in the below:

package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func sendRequest() {
	// Request (GET https://YOUR_JIRA_BASEURL/rest/api/2/myself)

	// Create client
	client := &http.Client{}

	// Create request
	req, err := http.NewRequest("GET", "https://YOUR_JIRA_BASEURL/rest/api/2/myself", nil)

	// Headers
	req.Header.Add("Authorization", "Basic <YOUR_BASIC_AUTH_HEADER>")

	// Fetch Request
	resp, err := client.Do(req)
	
	if err != nil {
		fmt.Println("Failure : ", err)
	}

	// Read Response Body
	respBody, _ := ioutil.ReadAll(resp.Body)

	// Display Results
	fmt.Println("response Status : ", resp.Status)
	fmt.Println("response Headers : ", resp.Header)
	fmt.Println("response Body : ", string(respBody))
}

CODE


ServiceNow RESTMessgage V2

Replace in the below:

//Request - RESTMessageV2 
try {
  var rm = new sn_ws.RESTMessageV2();
  rm.setHttpMethod("GET");
  rm.setEndpoint("https://YOUR_JIRA_BASEURL/rest/api/2/myself");
  rm.setRequestHeader('Authorization','Basic <YOUR_BASIC_AUTH_HEADER>');

  var response = rm.execute();
  var responseBody = response.getBody();
  var httpStatus = response.getStatusCode();
  gs.debug("httpStatus: {0}", httpStatus);
  gs.debug("responseBody: {0}", responseBody);
}
catch(ex) {
  gs.error("Request REST error", ex);
}



CODE


PHP - Wordpress 

Replace in the below:

<?php

// {@see https://codex.wordpress.org/HTTP_API}
$response = wp_remote_get( 'https://YOUR_JIRA_BASEURL/rest/api/2/myself', array(
    'headers' => array(
        'Authorization' => 'Basic <YOUR_BASIC_AUTH_HEADER>',
    ),
) );

if ( ! is_wp_error( $response ) ) {
    // The request went through successfully, check the response code against
    // what we're expecting
    if ( 200 == wp_remote_retrieve_response_code( $response ) ) {
        // Do something with the response
        // $body = wp_remote_retrieve_body( $response );
        // $headers = wp_remote_retrieve_headers( $response );
    } else {
        // The response code was not what we were expecting, record the message
        $error_message = wp_remote_retrieve_response_message( $response );
    }
} else {
    // There was an error making the request
    $error_message = $response->get_error_message();
}



CODE