Skip to content

Implementing a token refresh logic inside a middleware #11

@pke

Description

@pke

I'd like to implement an OpenID-Connect refresh logic inside a middleware that adds an Access Token to a request and reacts on 401 responses by fetching a new access token and repeating the request with the new token.

However, inside the middleware I only have access to the "next" middleware in the chain and not the "start" of the middleware chain, so middleware that would transform bodies would not work.

function middleware() {
  return function(url:string, options: RequestInit, next: FetchFunction) {
    const fetch = next
    if (accessToken) {
      options = {
        ...options,
        headers: {
          ...options.headers,
          "Authorization": "Bearer " + accessToken,
        },
      }
    }
    return next(url, options).then(response => {
      if (response.status === 401 && refreshToken) {
        return fetch(tokenURI, {
          method: "POST",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
          body: {
            grant_type: "refresh_token",
            client_id: clientId,
            client_secret: clientSecret,
            refresh_token: refreshToken,
          },
        })
      } else {
        return response
      }
    })
  }
}

I have a sendFormEncoded middleware that should take care of converting an object body to urlencoded but its not triggered in my request to fetch a new access token. Any idea how to hand in the original start of the middle ware chain into each middleware?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions