fresh icon indicating copy to clipboard operation
fresh copied to clipboard

shouldApplyToken: Add ability to skip adding authentication header

Open passsy opened this issue 2 months ago • 1 comments

Currently, fresh_dio automatically adds the authentication header to all requests made through a dio instance with the interceptor. However, some endpoints should not include authentication headers, such as:

  • Login/registration endpoints
  • Public endpoints (health checks, public content)
  • Password reset flows
  • Guest/anonymous access endpoints
  • Token refresh endpoint itself (in some API designs)

Add a new optional callback could be added to determine if the token should be applied:

Fresh.oAuth2(
  tokenHeader: (token) {
    return {'Authorization': 'Bearer ${token.accessToken}'};
  },
  shouldApplyToken: (requestOptions) {
    // Don't apply token if explicitly skipped
    if (requestOptions.extra['skipAuth'] == true) {
      return false;
    }

    // Do path based checks
    if (requestOptions.path.contains(`/auth/`) {
      return false;
    }

    return true;
  },
);

passsy avatar Oct 18 '25 01:10 passsy

Hi @passsy 👋 Thanks for filing the issue!

Thoughts on the following API:

Fresh.oAuth2(
  tokenHeader: (token) {
    return {'Authorization': 'Bearer ${token.accessToken}'};
  },
  // Optional (returns true by default for all requests)
  isTokenRequired: (options) {
    // Don't apply token if explicitly skipped
    if (options.extra['skipAuth'] == true) {
      return false;
    }

    // Do path based checks
    if (options.path.contains(`/auth/`) {
      return false;
    }

    return true;
  },
);

felangel avatar Oct 19 '25 20:10 felangel