Skip to content

Improve docs around adding authorization header mechanism able to refresh tokens #552

Open
@lossyrob

Description

@lossyrob

Currently the way to add an Authorization header to a Client is to add a static token in the headers parameter. This works, however if the token can expire, the user has to stay on top of checking token expiration any time they want to use the client and call client._stac_io.update(headers=...).

I propose we add an authorization parameter to Client and StacApiIO that can either take a string or a function. This parameter would provide the Authorization: header for each request. If it's a string, just use that string - this would be the same as supplying it in the headers parameter, but would take precedence over any Authorization key in the headers. If the value were a function, it would call that function to get the value of the Authorization header for each request made by StacApiIO. That way, I could write a function that checks the expiration of the token and uses a new one in case it's about to expire. E.g.:

import os
import time
from typing import Optional

from azure.identity import DefaultAzureCredential
from azure.core.credentials import AccessToken
import pystac_client

class TokenProvider:
    _token: Optional[AccessToken]

    def __init__(self, app_id: str):
        self.app_id = app_id
        self._credential = DefaultAzureCredential()
        self._token = None
        
    def get_token(self) -> str:
        if self._token is None or self._token.expires_on < time.time() - 5:
            self._token = self._credential.get_token(self.app_id)
        return f"Bearer {self._token}"
        
tp = TokenProvider(os.environ["APP_ID"])

client = pystac_client.Client.open("https://foo.westeurope.cloudapp.azure.com/stac", authorization=tp.get_token)

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentationenhancementNew feature or requesthelp wantedExtra attention is needed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions