authts / react-oidc-context

Lightweight auth library based on oidc-client-ts for React single page applications (SPA). Support for hooks and higher-order components (HOC).
MIT License
643 stars 63 forks source link

Question: get auth object (accessToken) outside of React component #1071

Open vladimirsvicevicsrb opened 8 months ago

vladimirsvicevicsrb commented 8 months ago

Is it possible that we can auth object (specifically accessToken) outside of the React component?

The real use case would be that in my react project, I have a couple of services and each of them is called by backend api. Backend API accepts and verifies tokens. I need to pass the token in every request to the backend, and instead of passing accessToken to every service method, I would like to have a service that will server a wrapper around fetch call and will get access token on its own from the auth object, instead of me passing it for every service method.

Is there any class apart from useAuth hook that gives us the possibility to import auth objects outside of React component? Thanks

pamapa commented 8 months ago

Yes its possible see https://github.com/authts/react-oidc-context#call-a-protected-api: As not a child of AuthProvider...

vladimirsvicevicsrb commented 8 months ago

So, if I understand correctly, the only possibility is to store accessToken in localStorage by using here:

userStore: new WebStorageStateStore({ store: window.localStorage })
pamapa commented 7 months ago

So, if I understand correctly, the only possibility is to store accessToken in localStorage by using here:

userStore: new WebStorageStateStore({ store: window.localStorage })

no you can also store in sessionStorge or whatever and do it in a similar way...

meo9xit commented 2 months ago

So, if I understand correctly, the only possibility is to store accessToken in localStorage by using here:

userStore: new WebStorageStateStore({ store: window.localStorage })

Actually I have to add this, otherwise the access_token get from localStorage following this guide https://github.com/authts/react-oidc-context#call-a-protected-api is not match with the token I get from onSigninCallback.