Skip to content

Listen for storage to receive auth hash from popup #935

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions docs-src/silent-refresh.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@ This simple implementation within silent-refresh.html is sufficient in most case
var checks = [/[\?|&|#]code=/, /[\?|&|#]error=/, /[\?|&|#]token=/, /[\?|&|#]id_token=/];

function isResponse(str) {
var count = 0;
if (!str) return false;
for(var i=0; i<checks.length; i++) {
if (str.match(checks[i])) return true;
Expand All @@ -77,12 +76,24 @@ This simple implementation within silent-refresh.html is sufficient in most case

var message = isResponse(location.hash) ? location.hash : '#' + location.search;

(window.opener || window.parent).postMessage(message, location.origin);
if (window.parent && window.parent !== window) {
// if loaded as an iframe during silent refresh
window.parent.postMessage(message, location.origin);
} else if (window.opener && window.opener !== window) {
// if loaded as a popup during initial login
window.opener.postMessage(message, location.origin);
} else {
// last resort for a popup which has been through redirects and can't use window.opener
localStorage.setItem('auth_hash', message);
localStorage.removeItem('auth_hash');
}
</script>
</body>
</html>
```
The above example checks if the message in the URL (either hash or query string) is indeed a message returned with a response from an authentication provider and not an arbitrary value and then attempts to forward this message to a parent widow either by `.parent` (when this html is loaded in an iframe as a result of silent refresh) or by `.opener` (when the html is loaded into a popup during initial login) or finally using a storage event (as a fallback for complex cases, e.g. initial login in a popup with a cross-domain auth provider).


Please make sure that this file is copied to your output directory by your build task. When using the CLI you can define it as an asset for this. For this, you have to add the following line to the file ``.angular-cli.json``:

```JSON
Expand Down
42 changes: 27 additions & 15 deletions projects/lib/src/oauth-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1059,7 +1059,7 @@ export class OAuthService extends AuthConfig implements OnDestroy {
return this.initLoginFlowInPopup(options);
}

public initLoginFlowInPopup(options?: { height?: number; width?: number }) {
public initLoginFlowInPopup(options?: { height?: number; width?: number }): Promise<boolean> {
options = options || {};
return this.createLoginUrl(
null,
Expand All @@ -1081,6 +1081,21 @@ export class OAuthService extends AuthConfig implements OnDestroy {
this.calculatePopupFeatures(options)
);
let checkForPopupClosedTimer: any;

const tryLogin = (hash: string) => {
this.tryLogin({
customHashFragment: hash,
preventClearHashAfterLogin: true,
customRedirectUri: this.silentRefreshRedirectUri,
}).then(() => {
cleanup();
resolve(true);
}, err => {
cleanup();
reject(err);
});
};

const checkForPopupClosed = () => {
if (!windowRef || windowRef.closed) {
cleanup();
Expand All @@ -1098,6 +1113,7 @@ export class OAuthService extends AuthConfig implements OnDestroy {

const cleanup = () => {
window.clearInterval(checkForPopupClosedTimer);
window.removeEventListener('storage', storageListener);
window.removeEventListener('message', listener);
if (windowRef !== null) {
windowRef.close();
Expand All @@ -1109,26 +1125,22 @@ export class OAuthService extends AuthConfig implements OnDestroy {
const message = this.processMessageEventMessage(e);

if (message && message !== null) {
this.tryLogin({
customHashFragment: message,
preventClearHashAfterLogin: true,
customRedirectUri: this.silentRefreshRedirectUri
}).then(
() => {
cleanup();
resolve();
},
err => {
cleanup();
reject(err);
}
);
window.removeEventListener('storage', storageListener);
tryLogin(message);
} else {
console.log('false event firing');
}
};

const storageListener = (event: StorageEvent) => {
if (event.key === 'auth_hash') {
window.removeEventListener('message', listener);
tryLogin(event.newValue);
}
};

window.addEventListener('message', listener);
window.addEventListener('storage', storageListener);
});
});
}
Expand Down
14 changes: 12 additions & 2 deletions projects/sample/src/silent-refresh.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
];

function isResponse(str) {
var count = 0;
if (!str) return false;
for (var i = 0; i < checks.length; i++) {
if (str.match(checks[i])) return true;
Expand All @@ -21,7 +20,18 @@
? location.hash
: '#' + location.search;

(window.opener || window.parent).postMessage(message, location.origin);
if (window.parent && window.parent !== window) {
// if loaded as an iframe during silent refresh
window.parent.postMessage(message, location.origin);
} else if (window.opener && window.opener !== window) {
// if loaded as a popup during initial login
window.opener.postMessage(message, location.origin);
} else {
// last resort for a popup which has been through redirects and can't use window.opener
localStorage.setItem('auth_hash', message);
localStorage.removeItem('auth_hash');
}

</script>
</body>
</html>