Skip to content

Feature: automatic token refresh on 401 responses #56

Description

@ZialeHub

Problem

OAuth2, OIDC, and Keycloak access tokens expire. When a token expires mid-session, every subsequent request receives a 401 Unauthorized. Currently the library surfaces this as an error and the caller must manually reconnect, losing all pagination/filter/sort state.

Proposed feature

Add transparent token refresh: when a request returns 401, automatically invoke the connector's connect() method to obtain a new token and retry the original request once.

Configuration

ApiBuilder::new(url)
    .auto_refresh(true)   // default: false for backwards compat
    .build()

Or via the Authorization trait's connect() default implementation, which could store a refresh closure.

Proposed design

Add an optional refresh callback to Api:

pub struct Api<P, F, S, R> {
    // existing fields ...
    refresh: Option<Arc<dyn Fn() -> BoxFuture<'static, Result<AuthorizationType>> + Send + Sync>>,
}

On 401:

  1. Call refresh() to obtain a new AuthorizationType
  2. Update self.authorization (requires interior mutability — Arc<RwLock<AuthorizationType>>)
  3. Rebuild the request headers with the new token
  4. Retry once (do not loop — a second 401 is a real error)

Proc macro integration

#[derive(Oauth2)], #[derive(OIDC)], #[derive(Keycloak)] should automatically wire up the refresh closure from the connector struct's credentials, so the refresh is fully transparent.

Related

  • Token caching issue (store and reuse unexpired tokens before refreshing)

Metadata

Metadata

Assignees

No one assigned

    Labels

    B-ideaDiscussion; or implementation attempt, to be reviewed before further workrustPull requests that update rust code

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions