diff --git a/addons/core/addon/authenticators/oidc.js b/addons/core/addon/authenticators/oidc.js index b23bea9bd..f159fa87f 100644 --- a/addons/core/addon/authenticators/oidc.js +++ b/addons/core/addon/authenticators/oidc.js @@ -38,4 +38,49 @@ export default class OIDCAuthenticator extends BaseOIDCAuthenticator { const adapter = this.store.adapterFor('auth-token'); return adapter.buildURL('auth-token', tokenID, {}, 'findRecord'); } + + /** + * Intercepts the authenticate response, if any, and assigns the returned + * token to all future requests via `addTokenToAuthorization`. + * Returns the response data as normal. + * @override + */ + authenticate() { + return super.authenticate(...arguments).then((data) => { + const token = data?.attributes?.token; + this.addTokenToAuthorization(token); + return data; + }); + } + + /** + * When restoring the session (say, on load), assigns the session token + * to all future requests via `addTokenToAuthorization`. + * @override + * @param {object} data + * @return {object} + */ + restore(data) { + const token = data?.attributes?.token; + this.addTokenToAuthorization(token); + return super.restore(data); + } + + /** + * Assigns a token string all future requests via the `Authorization` header + * on the application adapter prototype. Only application and adapters that + * extend the application adapter receive this header (which is most). + * + * TODO: if cookies were requested, this step should be skipped. + * + * @param {string} token + */ + addTokenToAuthorization(token) { + const adapterPrototype = this.store.adapterFor('application').constructor + .prototype; + const headers = adapterPrototype?.headers; + if (!headers) adapterPrototype.headers = {}; + adapterPrototype.headers.Authorization = null; + adapterPrototype.headers.Authorization = `Bearer ${token}`; + } }