swagger-api / swagger-api/swagger-codegen
[JavaScript] Dynamically compute auth header?
Nobody has claimed this yet.
- Dominant language
- Mustache
- Stars
- 17.8k
- Forks
- 6k
- PR merge metrics
- No merged PRs in 30d
Description
I have what I suspect to be an "Authentication 101" type question, but am unsure of the approach when using a generated JavaScript client in the context of a SPA (React, specifically). I configure my SDK client-side to pass along a JWT which works fine, and my API is setup to handle token expiration, but I'm wondering what should happen if the user forcibly removes their token from local storage? The scenario in my mind:
- User logs in successfully (token is supplied, put in local storage, and SDK client configured)
- User clears browser storage via DevTools, etc.
- User performs interaction that issues an XHR using the SDK client
- XHR succeeds because token is saved on the SDK client
Per the generated README.md, I configure my SDK client like this:
function authenticate(email, password) {
// Pass off to API and get a response...
const { jwt } = apiResponse.body;
window.localStorage.setItem('jwt', jwt);
// Configure the SDK to use the apiKey security definition
const defaultClient = MySdk.ApiClient.instance;
const jwtAuth = defaultClient.authentications['jwt'];
jwtAuth.apiKey = jwt; // Cached on client
}
My off-the-cuff idea would be to allow authentication keys to be set as functions which get invoked prior to firing off the XHR:
jwtAuth.apiKey = () => window.localStorage.getItem('jwt');
if (typeof jwtAuth.apiKey === 'function') {
return jwtAuth.apiKey();
} else {
return jwtAuth.apiKey
}
Other ideas that came to mind:
- Functionality might already exist for other custom (non-auth) headers?
- Tap into the React component lifecycle and check for existence (outside the scope of
swagger-codegen) - Add
superagentrequest interceptor
Any input on this is appreciated!
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the generated JavaScript client setup described in README.md, especially ApiClient.instance and its authentication handling. Trace how jwtAuth.apiKey is read before an XHR and define the desired behavior for a value removed from localStorage; done means the approach is implemented consistently in generated clients and documented.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, react
- Domain
- authentication, frontend
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 30/100