Sobes.tech
Junior

What is a token?

sobes.tech AI

Answer from AI

A token in the context of authentication and authorization is an opaque string of data issued by the server after successful user (or client) authentication. It represents the user's or client's credentials for subsequent access to protected resources without needing to re-enter login and password.

Token types:

  • Bearer Token: The most common type, transmitted in the Authorization header as Bearer <token>. The token recipient (server) must grant access to whoever "bears" the token, without additional authentication checks.
  • JWT (JSON Web Token): A structured, self-contained token containing information about the user or session in encoded form. It consists of three parts separated by dots: header, payload, and signature. It can be signed (JWS) or encrypted (JWE).

Our test scenarios for working with tokens include:

  1. Obtaining a token: Checking the correctness of the authentication request and successful token retrieval.
  2. Using a token: Checking access to protected resources with a valid token.
  3. Invalid/expired token: Checking access denial when using an incorrect, fake, or expired token.
  4. Absence of token: Checking access denial when attempting access without a token.
  5. Token refresh: If used, testing the mechanism of obtaining a new Access Token using a Refresh Token.
  6. Token revocation: Checking successful token revocation and subsequent access denial.

For automation, we use:

  • HTTP client libraries (e.g., requests in Python, Axios in JavaScript) for sending requests with tokens.
  • Parsing responses to extract tokens.
  • Saving the token in a variable for subsequent use.
import requests

# Example of obtaining a token (request to fictitious_auth_endpoint)
url = "https://api.example.com/auth"
payload = {
    "username": "testuser",
    "password": "password123"
}

try:
    response = requests.post(url, json=payload)
    response.raise_for_status() # Check for HTTP errors (4xx, 5xx)
    token_data = response.json()
    auth_token = token_data.get("access_token") # Extract token from response

    if auth_token:
        print(f"Successfully received token: {auth_token}")

        # Example of using the token (request to protected_resource)
        protected_url = "https://api.example.com/protected"
        headers = {
            "Authorization": f"Bearer {auth_token}" # Passing token in header
        }
        protected_response = requests.get(protected_url, headers=headers)
        protected_response.raise_for_status()
        print("Access to protected resource successful!")
        print(protected_response.json())
    else:
        print("Failed to get token from response.")

except requests.exceptions.RequestException as e:
    print(f"Request failed: {e}")

Overall, the token provides a secure and stateless way to manage access, reducing the load on the authentication server with each request to protected resources.