Super simple oauth2 helper. Works well with umbraco-authu.
Can be used in a browser (localstorage) or react-native (AsyncStorage) etc by setting persistenceGet
, persistenceSet
and persistenceClear
.
- ES6
- async/await
- fetch
npm install authur
import auth from 'authur';
auth.initialize({
origin: 'https://your-website.s1.umbraco.io',
authPath: '/oauth/token',
apiPath: '/umbraco/api',
persistenceGet: key => localStorage.getItem(key),
persistenceSet: (key, val) => localStorage.setItem(key, val),
persistenceClear: (storageKey) => localStorage.removeItem(storageKey),
debug: true,
events: {
onAuthStateChange: status => console.log('auth status changed to:', status))
}
})
const { ok, error } = await auth.authenticate({ username, password });
You can subscribe to auth state changes anywhere:
const unsubscribe = auth.onAuthStateChange(status => console.log('auth status changed to:', status));
// later
unsubscribe();
auth.signout();
Just a wrapper around fetch that:
- Appends a valid token to request and call signout() if 401 is returned from server
- Defaults to 'GET' if no options are passed
- Appends api path if it is set in
auth.initialize
const resp = await auth.fetch('/news/list');
const content = await resp.json();
Returns a valid token if possible. Will automagiclly refresh if needed.
const token = await auth.getToken()
const isAuthenticated = await auth.isAuthenticated()