Using Tokens - Examples

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

  1. https://<YOUR_JIRA_BASEURL>/rest/api/2/myself


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:

  1. {
  2. "self": "http://www.example.com/jira/rest/api/2/user?username=fred",
  3. "name": "fred",
  4. "emailAddress": "fred@example.com",
  5. "avatarUrls": {
  6. "48x48": "http://www.example.com/jira/secure/useravatar?size=large&ownerId=fred",
  7. "24x24": "http://www.example.com/jira/secure/useravatar?size=small&ownerId=fred",
  8. "16x16": "http://www.example.com/jira/secure/useravatar?size=xsmall&ownerId=fred",
  9. "32x32": "http://www.example.com/jira/secure/useravatar?size=medium&ownerId=fred"
  10. },
  11. "displayName": "Fred F. User",
  12. "active": true,
  13. "timeZone": "Australia/Sydney",
  14. "groups": {
  15. "size": 3,
  16. "items": [
  17. {
  18. "name": "jira-user",
  19. "self": "http://www.example.com/jira/rest/api/2/group?groupname=jira-user"
  20. },
  21. {
  22. "name": "jira-admin",
  23. "self": "http://www.example.com/jira/rest/api/2/group?groupname=jira-admin"
  24. },
  25. {
  26. "name": "important",
  27. "self": "http://www.example.com/jira/rest/api/2/group?groupname=important"
  28. }
  29. ]
  30. },
  31. "applicationRoles": {
  32. "size": 1,
  33. "items": []
  34. },
  35. "expand": "groups,applicationRoles"
  36. }

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:

  1. http://<YOUR_CONFLUENCE_BASEURL>/rest/api/user/current


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

  1. {
  2. "type": "known",
  3. "username": "jsmith",
  4. "userKey": "402880824ff933a4014ff9345d7c0002",
  5. "profilePicture": {
  6. "path": "/wiki/relative/avatar.png",
  7. "width": 48,
  8. "height": 48,
  9. "isDefault": true
  10. },
  11. "displayName": "Joe Smith",
  12. "_links": {
  13. "base": "http://myhost:8080/confluence",
  14. "context": "/confluence",
  15. "self": "http://myhost:8080/confluence/rest/experimental/user?key=402880824ff933a4014ff9345d7c0002"
  16. },
  17. "_expandable": {
  18. "status": ""
  19. }
  20. }

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

Bearer Auth header

Since version 1.7.0 you can also use a token as bearer token.
The difference is that instead passing type "Basic" you need to specify "Bearer" and you can omit the username and pass the token directly.

  1. Authorization: Bearer <yourToken>

cURL Example

  1. curl "https://YOUR_JIRA_BASEURL/rest/api/2/myself" \
  2. -H "Authorization: Bearer <YOUR_API_TOKEN>"


Basic Auth header

Most of the following examples will use the basic auth header. The Basic auth header looks like this:

  1. Authorization: Basic dXNlckBleGFtcGxlLmNvbTpzZWNyZXQ=

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

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

Ruby

Replace in the below:

  1. require 'net/http'
  2. require 'net/https'
  3. # SAML (GET )
  4. def send_request
  5. uri = URI('https://YOUR_JIRA_BASEURL/rest/api/2/myself')
  6. # Create client
  7. http = Net::HTTP.new(uri.host, uri.port)
  8. http.use_ssl = true
  9. http.verify_mode = OpenSSL::SSL::VERIFY_PEER
  10. # Create Request
  11. req = Net::HTTP::Get.new(uri)
  12. # Add headers
  13. req.add_field "Authorization", "Basic <YOUR_BASIC_AUTH_HEADER>"
  14. # Fetch Request
  15. res = http.request(req)
  16. puts "Response HTTP Status Code: #{res.code}"
  17. puts "Response HTTP Response Body: #{res.body}"
  18. rescue StandardError => e
  19. puts "HTTP Request failed (#{e.message})"
  20. end


Python

Replace in the below:

  1. # Install the Python Requests library:
  2. # `pip install requests`
  3. import requests
  4. def send_request():
  5. # SAML
  6. # GET https://YOUR_JIRA_BASEURL/rest/api/2/myself
  7. try:
  8. response = requests.get(
  9. url="https://YOUR_JIRA_BASEURL/rest/api/2/myself",
  10. headers={
  11. "Authorization": "Basic <YOUR_BASIC_AUTH_HEADER>",
  12. },
  13. )
  14. print('Response HTTP Status Code: {status_code}'.format(
  15. status_code=response.status_code))
  16. print('Response HTTP Response Body: {content}'.format(
  17. content=response.content))
  18. except requests.exceptions.RequestException:
  19. print('HTTP Request failed')


node.js

Replace in the below:

  1. // request
  2. (function(callback) {
  3. 'use strict';
  4. const httpTransport = require('https');
  5. const responseEncoding = 'utf8';
  6. const httpOptions = {
  7. hostname: 'YOUR_JIRA_BASEURL',
  8. port: '443',
  9. path: '/rest/api/2/myself',
  10. method: 'GET',
  11. headers: {"Authorization":"Basic <YOUR_BASIC_AUTH_HEADER>"}
  12. };
  13. httpOptions.headers['User-Agent'] = 'node ' + process.version;
  14. // Using Basic Auth {"username":"<USERNAME>","password":"<YOUR_API_TOKEN>"}
  15. const request = httpTransport.request(httpOptions, (res) => {
  16. let responseBufs = [];
  17. let responseStr = '';
  18. res.on('data', (chunk) => {
  19. if (Buffer.isBuffer(chunk)) {
  20. responseBufs.push(chunk);
  21. }
  22. else {
  23. responseStr = responseStr + chunk;
  24. }
  25. }).on('end', () => {
  26. responseStr = responseBufs.length > 0 ?
  27. Buffer.concat(responseBufs).toString(responseEncoding) : responseStr;
  28. callback(null, res.statusCode, res.headers, responseStr);
  29. });
  30. })
  31. .setTimeout(0)
  32. .on('error', (error) => {
  33. callback(error);
  34. });
  35. request.write("")
  36. request.end();
  37. })((error, statusCode, headers, body) => {
  38. console.log('ERROR:', error);
  39. console.log('STATUS:', statusCode);
  40. console.log('HEADERS:', JSON.stringify(headers));
  41. console.log('BODY:', body);
  42. });


Java

Replace in the below:

  1. public class SendRequest
  2. {
  3. public static void main(String[] args) {
  4. sendRequest();
  5. }
  6. private static void sendRequest() {
  7. // SAML (GET )
  8. try {
  9. // Create request
  10. Content content = Request.Get("https://YOUR_JIRA_BASEURL/rest/api/2/myself")
  11. // Add headers
  12. .addHeader("Authorization", "Basic <YOUR_BASIC_AUTH_HEADER>")
  13. // Fetch request and return content
  14. .execute().returnContent();
  15. // Print content
  16. System.out.println(content);
  17. }
  18. catch (IOException e) { System.out.println(e); }
  19. }
  20. }


PHP

Replace in the below:

  1. <?php
  2. // get cURL resource
  3. $ch = curl_init();
  4. // set url
  5. curl_setopt($ch, CURLOPT_URL, 'https://YOUR_JIRA_BASEURL/rest/api/2/myself');
  6. // set method
  7. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
  8. // return the transfer as a string
  9. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  10. // set headers
  11. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  12. 'Authorization: Basic <YOUR_BASIC_AUTH_HEADER>',
  13. ]);
  14. // send the request and save response to $response
  15. $response = curl_exec($ch);
  16. // stop if fails
  17. if (!$response) {
  18. die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
  19. }
  20. echo 'HTTP Status Code: ' . curl_getinfo($ch, CURLINFO_HTTP_CODE) . PHP_EOL;
  21. echo 'Response Body: ' . $response . PHP_EOL;
  22. // close curl resource to free up system resources
  23. curl_close($ch);


GO

Replace in the below:

  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net/http"
  6. )
  7. func sendRequest() {
  8. // Request (GET https://YOUR_JIRA_BASEURL/rest/api/2/myself)
  9. // Create client
  10. client := &http.Client{}
  11. // Create request
  12. req, err := http.NewRequest("GET", "https://YOUR_JIRA_BASEURL/rest/api/2/myself", nil)
  13. // Headers
  14. req.Header.Add("Authorization", "Basic <YOUR_BASIC_AUTH_HEADER>")
  15. // Fetch Request
  16. resp, err := client.Do(req)
  17. if err != nil {
  18. fmt.Println("Failure : ", err)
  19. }
  20. // Read Response Body
  21. respBody, _ := ioutil.ReadAll(resp.Body)
  22. // Display Results
  23. fmt.Println("response Status : ", resp.Status)
  24. fmt.Println("response Headers : ", resp.Header)
  25. fmt.Println("response Body : ", string(respBody))
  26. }


Service Now RESTMessageV2

Replace in the below:

  1. //Request - RESTMessageV2
  2. try {
  3. var rm = new sn_ws.RESTMessageV2();
  4. rm.setHttpMethod("GET");
  5. rm.setEndpoint("https://YOUR_JIRA_BASEURL/rest/api/2/myself");
  6. rm.setRequestHeader('Authorization','Basic <YOUR_BASIC_AUTH_HEADER>');
  7. var response = rm.execute();
  8. var responseBody = response.getBody();
  9. var httpStatus = response.getStatusCode();
  10. gs.debug("httpStatus: {0}", httpStatus);
  11. gs.debug("responseBody: {0}", responseBody);
  12. }
  13. catch(ex) {
  14. gs.error("Request REST error", ex);
  15. }


PHP - Wordpress 

Replace in the below:

  1. <?php
  2. // {@see https://codex.wordpress.org/HTTP_API}
  3. $response = wp_remote_get( 'https://YOUR_JIRA_BASEURL/rest/api/2/myself', array(
  4. 'headers' => array(
  5. 'Authorization' => 'Basic <YOUR_BASIC_AUTH_HEADER>',
  6. ),
  7. ) );
  8. if ( ! is_wp_error( $response ) ) {
  9. // The request went through successfully, check the response code against
  10. // what we're expecting
  11. if ( 200 == wp_remote_retrieve_response_code( $response ) ) {
  12. // Do something with the response
  13. // $body = wp_remote_retrieve_body( $response );
  14. // $headers = wp_remote_retrieve_headers( $response );
  15. } else {
  16. // The response code was not what we were expecting, record the message
  17. $error_message = wp_remote_retrieve_response_message( $response );
  18. }
  19. } else {
  20. // There was an error making the request
  21. $error_message = $response->get_error_message();
  22. }