From e9b216bc679ef16ada09b78f81e1a6fedcd0c2ee Mon Sep 17 00:00:00 2001 From: fearnycompknowhow <73258164+fearnycompknowhow@users.noreply.github.com> Date: Wed, 16 Jun 2021 08:12:17 -0500 Subject: [PATCH] App State Observable (#168) --- FAQ.md | 53 +++++++++++++++++++ .../src/lib/auth.service.spec.ts | 35 ++++++++++++ .../auth0-angular/src/lib/auth.service.ts | 15 +++++- .../e2e/integration/playground.spec.ts | 7 ++- .../playground/src/app/app.component.html | 27 ++++++++++ .../playground/src/app/app.component.spec.ts | 12 ++++- projects/playground/src/app/app.component.ts | 15 +++++- 7 files changed, 158 insertions(+), 6 deletions(-) diff --git a/FAQ.md b/FAQ.md index faea0936..3d8be6db 100644 --- a/FAQ.md +++ b/FAQ.md @@ -6,6 +6,7 @@ 2. [User is not logged in after successful sign in with redirect](#2-user-is-not-logged-in-after-successful-sign-in-with-redirect) 3. [User is redirected to `/` after successful sign in with redirect](#3-user-is-redirected-to--after-successful-sign-in-with-redirect) 4. [Getting an infinite redirect loop between my application and Auth0](#4-getting-an-infinite-redirect-loop-between-my-application-and-auth0) +5. [Preserve application state through redirects](#5-preserve-application-state-through-redirects) ## 1. User is not logged in after page refresh @@ -61,3 +62,55 @@ this.authService.loginWithRedirect({ In situations where the `redirectUri` points to a _protected_ route, your application will end up in an infinite redirect loop between your application and Auth0. The `redirectUri` should always be a **public** route in your application (even if the entire application is secure, our SDK needs a public route to be redirected back to). This is because, when redirecting back to the application, there is no user information available yet. The SDK first needs to process the URL (`code` and `state` query parameters) and call Auth0's endpoints to exchange the code for a token. Once that is successful, the user is considered authenticated. + +## 5. Preserve application state through redirects + +To preserve application state through the redirect to Auth0 and the subsequent redirect back to your application (if the user authenticates successfully), you can pass in the state that you want preserved to the `loginWithRedirect` method: + +```ts +import { Component } from '@angular/core'; +import { AuthService } from '@auth0/auth0-angular'; + +@Component({ + selector: 'app-root', + templateUrl: './app.component.html', + styleUrls: ['./app.component.css'], +}) +export class AppComponent { + constructor(public auth: AuthService) {} + + loginWithRedirect(): void { + this.auth.loginWithRedirect({ + appState: { + myValue: 'My State to Preserve', + }, + }); + } +} +``` + +After Auth0 redirects the user back to your application, you can access the stored state using the `appState$` observable on the `AuthService`: + +```ts +import { Component, OnInit } from '@angular/core'; +import { AuthService } from '@auth0/auth0-angular'; + +@Component({ + selector: 'app-root', + templateUrl: './app.component.html', + styleUrls: ['./app.component.css'], +}) +export class AppComponent { + constructor(public auth: AuthService) {} + + ngOnInit() { + this.auth.appState$.subscribe((appState) => { + console.log(appState.myValue); + }); + } +} +``` + +> By default, this method of saving application state will store it in Session Storage; however, if `useCookiesForTransactions` is set, a Cookie will be used instead. + +> This information will be removed from storage once the user is redirected back to your application after a successful login attempt (although it will continue to be accessible on the `appState$` observable). diff --git a/projects/auth0-angular/src/lib/auth.service.spec.ts b/projects/auth0-angular/src/lib/auth.service.spec.ts index e2c1f3a5..479cc131 100644 --- a/projects/auth0-angular/src/lib/auth.service.spec.ts +++ b/projects/auth0-angular/src/lib/auth.service.spec.ts @@ -400,6 +400,23 @@ describe('AuthService', () => { }); }); + it('should record the appState in the appState$ observable if it is present', (done) => { + const appState = { + myValue: 'State to Preserve', + }; + + (auth0Client.handleRedirectCallback as jasmine.Spy).and.resolveTo({ + appState, + }); + + const localService = createService(); + + localService.appState$.subscribe((recievedState) => { + expect(recievedState).toEqual(appState); + done(); + }); + }); + it('should record errors in the error$ observable', (done) => { const errorObj = new Error('An error has occured'); @@ -695,6 +712,24 @@ describe('AuthService', () => { ) .subscribe(); }); + + it('should record the appState in the appState$ observable if it is present', (done) => { + const appState = { + myValue: 'State to Preserve', + }; + + (auth0Client.handleRedirectCallback as jasmine.Spy).and.resolveTo({ + appState, + }); + + const localService = createService(); + localService.handleRedirectCallback().subscribe(() => { + localService.appState$.subscribe((recievedState) => { + expect(recievedState).toEqual(appState); + done(); + }); + }); + }); }); describe('buildAuthorizeUrl', () => { diff --git a/projects/auth0-angular/src/lib/auth.service.ts b/projects/auth0-angular/src/lib/auth.service.ts index 2bf46b61..86ac636b 100644 --- a/projects/auth0-angular/src/lib/auth.service.ts +++ b/projects/auth0-angular/src/lib/auth.service.ts @@ -52,6 +52,7 @@ export class AuthService implements OnDestroy { private errorSubject$ = new ReplaySubject(1); private refreshState$ = new Subject(); private accessToken$ = new ReplaySubject(1); + private appStateSubject$ = new ReplaySubject(1); // https://stackoverflow.com/a/41177163 private ngUnsubscribe$ = new Subject(); @@ -137,6 +138,12 @@ export class AuthService implements OnDestroy { */ readonly error$ = this.errorSubject$.asObservable(); + /** + * Emits the value (if any) that was passed to the `loginWithRedirect` method call + * but only **after** `handleRedirectCallback` is first called + */ + readonly appState$ = this.appStateSubject$.asObservable(); + constructor( @Inject(Auth0ClientService) private auth0Client: Auth0Client, private configFactory: AuthClientConfig, @@ -333,7 +340,13 @@ export class AuthService implements OnDestroy { if (!isLoading) { this.refreshState$.next(); } - const target = result?.appState?.target ?? '/'; + const appState = result?.appState; + const target = appState?.target ?? '/'; + + if (appState) { + this.appStateSubject$.next(appState); + } + this.navigator.navigateByUrl(target); }), map(([result]) => result) diff --git a/projects/playground/e2e/integration/playground.spec.ts b/projects/playground/e2e/integration/playground.spec.ts index 549cdbbb..caa2c360 100644 --- a/projects/playground/e2e/integration/playground.spec.ts +++ b/projects/playground/e2e/integration/playground.spec.ts @@ -48,8 +48,11 @@ describe('Smoke tests', () => { cy.get('#logout').should('be.visible').click(); }); - it('do redirect login and show user and access token', () => { + it('do redirect login and show user, access token and appState', () => { + const appState = 'Any Random String'; + cy.visit('/'); + cy.get('[data-cy=app-state-input]').type(appState); cy.get('#login').should('be.visible').click(); cy.url().should('include', 'https://brucke.auth0.com/login'); loginToAuth0(); @@ -66,6 +69,8 @@ describe('Smoke tests', () => { cy.get('[data-cy=accessToken]').should('have.text', token); }); + cy.get('[data-cy=app-state-result]').should('have.value', appState); + cy.get('#logout').should('be.visible').click(); cy.get('#login').should('be.visible'); }); diff --git a/projects/playground/src/app/app.component.html b/projects/playground/src/app/app.component.html index ae46fc21..df83ff0f 100644 --- a/projects/playground/src/app/app.component.html +++ b/projects/playground/src/app/app.component.html @@ -27,6 +27,22 @@

Authentication

data-cy="login-popup" /> + +
+
+ + + +
+
+