Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Demystifying Token Authentication in NgRx (ngIndia)

Sam Julien
February 29, 2020

Demystifying Token Authentication in NgRx (ngIndia)

So, you've got a shiny new Angular application and you're thrilled to be managing your state with NgRx. You've got your store, reducers, and actions set up, but your boss asks you an innocent question during your first demo: "How do I log in?" You stare blankly, realizing that you've completely forgotten about authentication. Isn't it the same as in a regular Angular application? How does real-world authentication in NgRx work, anyway?

I've got your back in this talk. You'll learn not only the HOW of token-based authentication in NgRx, but also the WHY. We'll talk about managing app-wide authentication state through the store, how to determine what should end up in state, maintaining Good Action Hygiene with authentication, the role of Effects, and keeping your application safe using authentication best practices.

Sam Julien

February 29, 2020
Tweet

More Decks by Sam Julien

Other Decks in Technology

Transcript

  1. Demystifying Token
    Authentication in NgRx

    View Slide

  2. @samjulien

    View Slide

  3. "Great, but how do I log in?”
    @samjulien

    View Slide

  4. View Slide

  5. View Slide

  6. Authentication is a Big Scary Subject.
    @samjulien

    View Slide

  7. …with lots of jargon.
    @samjulien

    View Slide

  8. …with lots of jargon vocab.
    @samjulien

    View Slide

  9. NgRx is a Big Scary Subject.
    @samjulien

    View Slide

  10. …with lots of jargon.
    @samjulien

    View Slide

  11. …with lots of jargon vocab.
    @samjulien

    View Slide

  12. View Slide

  13. Is auth the same in NgRx as vanilla Angular?
    @samjulien

    View Slide

  14. Auth in NgRx looks different
    than auth in vanilla Angular.
    @samjulien

    View Slide

  15. Feature development in NgRx
    looks different than feature
    development in vanilla Angular.
    @samjulien

    View Slide

  16. @samjulien
    Sam Julien
    @samjulien
    @samjulien

    View Slide

  17. @samjulien
    Sam Julien
    @samjulien
    Sr. Developer Advocate Engineer at Auth0
    @samjulien

    View Slide

  18. @samjulien
    Sam Julien
    @samjulien
    Sr. Developer Advocate Engineer at Auth0
    GDE & Angular Collaborator
    @samjulien

    View Slide

  19. @samjulien
    Sam Julien
    @samjulien
    Sr. Developer Advocate Engineer at Auth0
    GDE & Angular Collaborator
    UpgradingAngularJS.com, Thinkster, & Egghead
    @samjulien

    View Slide

  20. Auth in NgRx looks different
    than auth in vanilla Angular.
    @samjulien

    View Slide

  21. Feature development in NgRx
    looks different than feature
    development in vanilla Angular.
    @samjulien

    View Slide

  22. View Slide

  23. @samjulien

    View Slide

  24. @samjulien

    View Slide

  25. Start login
    Handle redirect
    Log in to provider
    @samjulien

    View Slide

  26. Handle redirect
    Success
    Error
    @samjulien

    View Slide

  27. @samjulien

    View Slide

  28. Auth Service
    @samjulien

    View Slide

  29. Auth Service
    Components
    @samjulien

    View Slide

  30. Auth Service
    Components
    Data Services
    @samjulien

    View Slide

  31. @samjulien

    View Slide

  32. Auth Service
    Components
    Data Services
    @samjulien

    View Slide

  33. Reducers
    Components
    Effects
    Auth Service
    @samjulien

    View Slide

  34. Auth Service
    Components
    Data Services
    @samjulien

    View Slide

  35. Reducers
    Components
    Effects
    Auth Service
    @samjulien

    View Slide

  36. View Slide

  37. View Slide

  38. View Slide

  39. View Slide

  40. Reducers
    Components
    Effects
    Auth Service
    @samjulien

    View Slide

  41. @samjulien

    View Slide

  42. State Side Effects
    @samjulien

    View Slide

  43. State
    Side Effects
    @samjulien

    View Slide

  44. State What do I need to keep track of?
    Side Effects
    @samjulien

    View Slide

  45. State What do I need to keep track of?
    Side Effects What events don’t directly change state?
    @samjulien

    View Slide

  46. State
    Side Effects
    @samjulien

    View Slide

  47. State Video Game Collection
    Side Effects
    @samjulien

    View Slide

  48. State Video Game Collection
    Side Effects Call the API to get the collection.
    @samjulien

    View Slide

  49. State
    Side Effects
    @samjulien

    View Slide

  50. State Game Ownership
    Side Effects
    @samjulien

    View Slide

  51. State Game Ownership
    Side Effects Call the API to add to the collection.
    @samjulien

    View Slide

  52. State
    @samjulien

    View Slide

  53. What do I need to keep track of?
    @samjulien

    View Slide

  54. Where do I keep it?
    @samjulien

    View Slide

  55. The Store

    View Slide

  56. What goes in the store?
    @samjulien

    View Slide

  57. Start login
    Handle redirect
    Log in to provider
    @samjulien

    View Slide

  58. Handle redirect
    Success
    Error
    @samjulien

    View Slide

  59. Success
    @samjulien

    View Slide

  60. Success
    User Token
    Authenticated
    @samjulien

    View Slide

  61. Success
    User Token
    Authenticated
    Redirect
    @samjulien

    View Slide

  62. @samjulien

    View Slide

  63. Auth Service
    @samjulien

    View Slide

  64. export class AuthService {
    isAuthenticated: boolean = null;
    private userProfileSubject$ = new
    BehaviorSubject(null);
    userProfile$ = this.userProfileSubject$.asObservable();
    private tokenSubject$ = new
    BehaviorSubject(null);
    accessToken$ = this.userProfileSubject$.asObservable();
    }
    @samjulien

    View Slide

  65. export class AuthService {
    isAuthenticated: boolean = null;
    private userProfileSubject$ = new
    BehaviorSubject(null);
    userProfile$ = this.userProfileSubject$.asObservable();
    private tokenSubject$ = new
    BehaviorSubject(null);
    accessToken$ = this.userProfileSubject$.asObservable();
    }
    @samjulien

    View Slide

  66. export class AuthService {
    isAuthenticated: boolean = null;
    private userProfileSubject$ = new
    BehaviorSubject(null);
    userProfile$ = this.userProfileSubject$.asObservable();
    private tokenSubject$ = new
    BehaviorSubject(null);
    accessToken$ = this.userProfileSubject$.asObservable();
    }
    @samjulien

    View Slide

  67. export class AuthService {
    isAuthenticated: boolean = null;
    private userProfileSubject$ = new
    BehaviorSubject(null);
    userProfile$ = this.userProfileSubject$.asObservable();
    private tokenSubject$ = new
    BehaviorSubject(null);
    accessToken$ = this.userProfileSubject$.asObservable();
    }
    @samjulien

    View Slide

  68. export class AuthService {
    isAuthenticated: boolean = null;
    private userProfileSubject$ = new
    BehaviorSubject(null);
    userProfile$ = this.userProfileSubject$.asObservable();
    private tokenSubject$ = new
    BehaviorSubject(null);
    accessToken$ = this.userProfileSubject$.asObservable();
    }
    @samjulien

    View Slide

  69. export class AuthService {
    isAuthenticated: boolean = null;
    private userProfileSubject$ = new
    BehaviorSubject(null);
    userProfile$ = this.userProfileSubject$.asObservable();
    private tokenSubject$ = new
    BehaviorSubject(null);
    accessToken$ = this.userProfileSubject$.asObservable();
    }
    @samjulien

    View Slide

  70. export class AuthService {
    isAuthenticated: boolean = null;
    private userProfileSubject$ = new
    BehaviorSubject(null);
    userProfile$ = this.userProfileSubject$.asObservable();
    private tokenSubject$ = new
    BehaviorSubject(null);
    accessToken$ = this.userProfileSubject$.asObservable();
    }
    @samjulien

    View Slide

  71. @samjulien

    View Slide

  72. export interface State {
    isAuthenticated: boolean;
    userProfile: UserProfile;
    accessToken: AccessToken;
    }
    @samjulien

    View Slide

  73. export interface State {
    isAuthenticated: boolean;
    userProfile: UserProfile;
    accessToken: AccessToken;
    }
    @samjulien

    View Slide

  74. export interface State {
    isAuthenticated: boolean;
    userProfile: UserProfile;
    accessToken: AccessToken;
    }
    @samjulien

    View Slide

  75. export interface State {
    isAuthenticated: boolean;
    userProfile: UserProfile;
    accessToken: AccessToken;
    }
    @samjulien

    View Slide

  76. Don’t keep access tokens in local storage!
    @samjulien

    View Slide

  77. export interface State {
    isAuthenticated: boolean;
    userProfile: UserProfile;
    accessToken: AccessToken;
    }
    @samjulien

    View Slide

  78. What messages do we need about state?
    @samjulien

    View Slide

  79. What actions do we need?
    @samjulien

    View Slide

  80. Actions

    View Slide

  81. @samjulien

    View Slide

  82. @samjulien

    View Slide

  83. Events State Changes
    @samjulien

    View Slide

  84. Events
    @samjulien

    View Slide

  85. Start login
    Handle redirect
    Log in to provider
    @samjulien

    View Slide

  86. Handle redirect
    Success
    Error
    @samjulien

    View Slide

  87. export const logIn = createAction(
    ‘[Auth] Start Log In’
    );
    @samjulien
    export const logOut = createAction(
    '[Auth] Log out'
    );

    View Slide

  88. export const logIn = createAction(
    ‘[Auth] Start Log In’
    );
    @samjulien
    export const logOut = createAction(
    '[Auth] Log out'
    );

    View Slide

  89. export const logIn = createAction(
    ‘[Auth] Start Log In’
    );
    @samjulien
    export const logOut = createAction(
    '[Auth] Log out'
    );

    View Slide

  90. export const handleRedirect = createAction(
    ‘[Auth] Handle redirect’
    );
    @samjulien

    View Slide

  91. export const handleRedirectSuccess = createAction(
    '[Auth] Handle redirect success',
    props<{ targetRoute: string }>()
    );
    @samjulien
    export const handleRedirectError = createAction(
    '[Auth] Handle redirect error’,
    props<{ error: string }>()
    );

    View Slide

  92. export const handleRedirectSuccess = createAction(
    '[Auth] Handle redirect success',
    props<{ targetRoute: string }>()
    );
    @samjulien
    export const handleRedirectError = createAction(
    '[Auth] Handle redirect error’,
    props<{ error: string }>()
    );

    View Slide

  93. Events State Changes
    @samjulien

    View Slide

  94. State Changes
    @samjulien

    View Slide

  95. Start login
    Handle redirect
    Log in to provider
    @samjulien

    View Slide

  96. Handle redirect
    Success
    Error
    @samjulien

    View Slide

  97. Success
    @samjulien

    View Slide

  98. Success
    User Token
    Authenticated
    @samjulien

    View Slide

  99. Success
    User Token
    Authenticated
    Redirect
    @samjulien

    View Slide

  100. export interface State {
    isAuthenticated: boolean;
    userProfile: UserProfile;
    accessToken: AccessToken;
    }
    @samjulien

    View Slide

  101. export const loadUser = createAction(
    '[Auth] Load user’
    );
    export const loadUserSuccess = createAction(
    '[Auth] Load user success',
    props<{ user: User }>()
    );
    @samjulien

    View Slide

  102. export const loadUser = createAction(
    '[Auth] Load user’
    );
    export const loadUserSuccess = createAction(
    '[Auth] Load user success',
    props<{ user: User }>()
    );
    @samjulien

    View Slide

  103. export const loadUser = createAction(
    '[Auth] Load user’
    );
    export const loadUserSuccess = createAction(
    '[Auth] Load user success',
    props<{ user: User }>()
    );
    @samjulien

    View Slide

  104. export const checkAuth = createAction('[Auth] Check auth’);
    export const checkAuthSuccess = createAction(
    '[Auth] Check auth success',
    props<{ isAuthenticated: boolean }>()
    );
    export const setNotAuthenticated = createAction(
    '[Auth] Not authenticated',
    props<{ isAuthenticated: boolean }>()
    );
    @samjulien

    View Slide

  105. export const checkAuth = createAction('[Auth] Check auth’);
    export const checkAuthSuccess = createAction(
    '[Auth] Check auth success',
    props<{ isAuthenticated: boolean }>()
    );
    export const setNotAuthenticated = createAction(
    '[Auth] Not authenticated',
    props<{ isAuthenticated: boolean }>()
    );
    @samjulien

    View Slide

  106. export const checkAuth = createAction('[Auth] Check auth’);
    export const checkAuthSuccess = createAction(
    '[Auth] Check auth success',
    props<{ isAuthenticated: boolean }>()
    );
    export const setNotAuthenticated = createAction(
    '[Auth] Not authenticated',
    props<{ isAuthenticated: boolean }>()
    );
    @samjulien

    View Slide

  107. export const checkAuth = createAction('[Auth] Check auth’);
    export const checkAuthSuccess = createAction(
    '[Auth] Check auth success',
    props<{ isAuthenticated: boolean }>()
    );
    export const setNotAuthenticated = createAction(
    '[Auth] Not authenticated',
    props<{ isAuthenticated: boolean }>()
    );
    @samjulien

    View Slide

  108. export const getToken = createAction('[Auth] Get token’);
    export const getTokenSuccess = createAction(
    '[Auth] Get token success',
    props<{ accessToken: Token }>()
    );
    export const getTokenFailure = createAction(
    '[Auth] Get token failure',
    props<{ error: string }>()
    );
    @samjulien

    View Slide

  109. export const getToken = createAction('[Auth] Get token’);
    export const getTokenSuccess = createAction(
    '[Auth] Get token success',
    props<{ accessToken: Token }>()
    );
    export const getTokenFailure = createAction(
    '[Auth] Get token failure',
    props<{ error: string }>()
    );
    @samjulien

    View Slide

  110. export const getToken = createAction('[Auth] Get token’);
    export const getTokenSuccess = createAction(
    '[Auth] Get token success',
    props<{ accessToken: Token }>()
    );
    export const getTokenFailure = createAction(
    '[Auth] Get token failure',
    props<{ error: string }>()
    );
    @samjulien

    View Slide

  111. export const getToken = createAction('[Auth] Get token’);
    export const getTokenSuccess = createAction(
    '[Auth] Get token success',
    props<{ accessToken: Token }>()
    );
    export const getTokenFailure = createAction(
    '[Auth] Get token failure',
    props<{ error: string }>()
    );
    @samjulien

    View Slide

  112. We’ve got messages about
    changing state, but where does
    state actually change?
    @samjulien

    View Slide

  113. Reducers

    View Slide

  114. Defining Reducers
    @samjulien

    View Slide

  115. export const reducer = createReducer(
    initialState,
    // on()...
    );
    @samjulien

    View Slide

  116. on(
    AuthActions.checkAuthSuccess,
    AuthActions.setNotAuthenticated,
    (state, { isAuthenticated }) => {
    return {
    ...state,
    isAuthenticated,
    };
    }
    )
    @samjulien

    View Slide

  117. on(
    AuthActions.checkAuthSuccess,
    AuthActions.setNotAuthenticated,
    (state, { isAuthenticated }) => {
    return {
    ...state,
    isAuthenticated,
    };
    }
    )
    @samjulien

    View Slide

  118. on(
    AuthActions.checkAuthSuccess,
    AuthActions.setNotAuthenticated,
    (state, { isAuthenticated }) => {
    return {
    ...state,
    isAuthenticated,
    };
    }
    )
    @samjulien

    View Slide

  119. on(
    AuthActions.loadUserSuccess,
    (state, { user }) => {
    return {
    ...state,
    user,
    };
    }),
    @samjulien

    View Slide

  120. on(
    AuthActions.loadUserSuccess,
    (state, { user }) => {
    return {
    ...state,
    user,
    };
    }),
    @samjulien

    View Slide

  121. on(
    AuthActions.loadUserSuccess,
    (state, { user }) => {
    return {
    ...state,
    user,
    };
    }),
    @samjulien

    View Slide

  122. on(
    AuthActions.getTokenSuccess,
    (state, { accessToken }) => {
    return {
    ...state,
    accessToken,
    };
    }
    )
    @samjulien

    View Slide

  123. on(
    AuthActions.getTokenSuccess,
    (state, { accessToken }) => {
    return {
    ...state,
    accessToken,
    };
    }
    )
    @samjulien

    View Slide

  124. on(
    AuthActions.getTokenSuccess,
    (state, { accessToken }) => {
    return {
    ...state,
    accessToken,
    };
    }
    )
    @samjulien

    View Slide

  125. How do we read state in components?
    @samjulien

    View Slide

  126. Selectors

    View Slide

  127. @samjulien

    View Slide

  128. Auth Service
    Components
    @samjulien

    View Slide

  129. @samjulien

    View Slide

  130. Reducers
    Components
    Effects
    Auth Service
    @samjulien

    View Slide

  131. Reducers
    Components
    Effects
    Auth Service
    @samjulien
    Selectors

    View Slide

  132. Defining Selectors
    @samjulien

    View Slide

  133. @samjulien
    export const selectUser =
    (state: State) => state.user;
    export const selectIsAuthenticated =
    (state: State) => state.isAuthenticated;
    export const selectAccessToken =
    (state: State) => state.accessToken;

    View Slide

  134. @samjulien
    export const selectUser =
    (state: State) => state.user;
    export const selectIsAuthenticated =
    (state: State) => state.isAuthenticated;
    export const selectAccessToken =
    (state: State) => state.accessToken;

    View Slide

  135. @samjulien
    export const selectUser =
    (state: State) => state.user;
    export const selectIsAuthenticated =
    (state: State) => state.isAuthenticated;
    export const selectAccessToken =
    (state: State) => state.accessToken;

    View Slide

  136. @samjulien
    export const selectUser =
    (state: State) => state.user;
    export const selectIsAuthenticated =
    (state: State) => state.isAuthenticated;
    export const selectAccessToken =
    (state: State) => state.accessToken;

    View Slide

  137. @samjulien
    export const selectUser = createSelector(
    selectAuthStatus,
    fromAuthStatus.selectUser
    );
    export const selectAccessToken =
    createSelector(
    selectAuthStatus,
    fromAuthStatus.selectAccessToken
    );

    View Slide

  138. @samjulien
    export const selectUser = createSelector(
    selectAuthStatus,
    fromAuthStatus.selectUser
    );
    export const selectAccessToken =
    createSelector(
    selectAuthStatus,
    fromAuthStatus.selectAccessToken
    );

    View Slide

  139. @samjulien
    export const selectUser = createSelector(
    selectAuthStatus,
    fromAuthStatus.selectUser
    );
    export const selectAccessToken =
    createSelector(
    selectAuthStatus,
    fromAuthStatus.selectAccessToken
    );

    View Slide

  140. @samjulien
    export const selectIsAuthenticated =
    createSelector(
    selectAuthStatus,
    fromAuthStatus.selectIsAuthenticated
    );

    View Slide

  141. What about the auth calls?
    @samjulien

    View Slide

  142. Auth Service

    View Slide

  143. State Side Effects
    @samjulien

    View Slide

  144. View Slide

  145. Reducers
    Components
    Effects
    Auth Service
    @samjulien

    View Slide

  146. @samjulien

    View Slide

  147. export class AuthService {
    handleRedirectCallback$ =
    from(this.authClient.handleRedirectCallback());
    }
    @samjulien

    View Slide

  148. export class AuthService {⠀
    handleRedirect() {⠀
    }⠀
    }⠀
    @samjulien

    View Slide

  149. export class AuthService {
    handleRedirect() {
    if (weHaveACode) {
    let targetRoute: string;
    const authComplete$ = this.handleRedirectCallback$.pipe(
    tap(response => {
    targetRoute = this.processUrl(response);
    }),
    concatMap(() => {
    return combineLatest([
    this.getUser$(),
    this.isAuthenticated$
    ]);
    })
    );
    authComplete$.subscribe(([user, loggedIn]) => {
    this.router.navigate([targetRoute]);
    });
    }
    }
    }
    @samjulien

    View Slide

  150. export class AuthService {
    handleRedirect() {
    if (weHaveACode) {
    let targetRoute: string;
    const authComplete$ = this.handleRedirectCallback$.pipe(
    tap(response => {
    targetRoute = this.processUrl(response);
    }),
    concatMap(() => {
    return combineLatest([
    this.getUser$(),
    this.isAuthenticated$
    ]);
    })
    );
    authComplete$.subscribe(([user, loggedIn]) => {
    this.router.navigate([targetRoute]);
    });
    }
    }
    }
    @samjulien

    View Slide

  151. export class AuthService {
    handleRedirect() {
    if (weHaveACode) {
    let targetRoute: string;
    const authComplete$ = this.handleRedirectCallback$.pipe(
    tap(response => {
    targetRoute = this.processUrl(response);
    }),
    concatMap(() => {
    return combineLatest([
    this.getUser$(),
    this.isAuthenticated$
    ]);
    })
    );
    authComplete$.subscribe(([user, loggedIn]) => {
    this.router.navigate([targetRoute]);
    });
    }
    }
    }
    @samjulien

    View Slide

  152. export class AuthService {
    handleRedirect() {
    if (weHaveACode) {
    let targetRoute: string;
    const authComplete$ = this.handleRedirectCallback$.pipe(
    tap(response => {
    targetRoute = this.processUrl(response);
    }),
    concatMap(() => {
    return combineLatest([
    this.getUser$(),
    this.isAuthenticated$
    ]);
    })
    );
    authComplete$.subscribe(([user, loggedIn]) => {
    this.router.navigate([targetRoute]);
    });
    }
    }
    }
    @samjulien

    View Slide

  153. export class AuthService {
    handleRedirect() {
    if (weHaveACode) {
    let targetRoute: string;
    const authComplete$ = this.handleRedirectCallback$.pipe(
    tap(response => {
    targetRoute = this.processUrl(response);
    }),
    concatMap(() => {
    return combineLatest([
    this.getUser$(),
    this.isAuthenticated$
    ]);
    })
    );
    authComplete$.subscribe(([user, loggedIn]) => {
    this.router.navigate([targetRoute]);
    });
    }
    }
    }
    @samjulien

    View Slide

  154. export class AuthService {
    handleRedirect() {
    if (weHaveACode) {
    let targetRoute: string;
    const authComplete$ = this.handleRedirectCallback$.pipe(
    tap(response => {
    targetRoute = this.processUrl(response);
    }),
    concatMap(() => {
    return combineLatest([
    this.getUser$(),
    this.isAuthenticated$
    ]);
    })
    );
    authComplete$.subscribe(([user, loggedIn]) => {
    this.router.navigate([targetRoute]);
    });
    }
    }
    }
    @samjulien

    View Slide

  155. export class AuthService {
    handleRedirect() {
    if (weHaveACode) {
    let targetRoute: string;
    const authComplete$ = this.handleRedirectCallback$.pipe(
    tap(response => {
    targetRoute = this.processUrl(response);
    }),
    concatMap(() => {
    return combineLatest([
    this.getUser$(),
    this.isAuthenticated$
    ]);
    })
    );
    authComplete$.subscribe(([user, loggedIn]) => {
    this.router.navigate([targetRoute]);
    });
    }
    }
    }
    @samjulien

    View Slide

  156. export class AuthService {
    handleRedirect() {
    if (weHaveACode) {
    let targetRoute: string;
    const authComplete$ = this.handleRedirectCallback$.pipe(
    tap(response => {
    targetRoute = this.processUrl(response);
    }),
    concatMap(() => {
    return combineLatest([
    this.getUser$(),
    this.isAuthenticated$
    ]);
    })
    );
    authComplete$.subscribe(([user, loggedIn]) => {
    this.router.navigate([targetRoute]);
    });
    }
    }
    }
    @samjulien

    View Slide

  157. export class AuthService {
    handleRedirect() {
    if (weHaveACode) {
    let targetRoute: string;
    const authComplete$ = this.handleRedirectCallback$.pipe(
    tap(response => {
    targetRoute = this.processUrl(response);
    }),
    concatMap(() => {
    return combineLatest([
    this.getUser$(),
    this.isAuthenticated$
    ]);
    })
    );
    authComplete$.subscribe(([user, loggedIn]) => {
    this.router.navigate([targetRoute]);
    });
    }
    }
    }
    @samjulien

    View Slide

  158. export class AuthService {
    handleRedirect() {
    if (weHaveACode) {
    let targetRoute: string;
    const authComplete$ = this.handleRedirectCallback$.pipe(
    tap(response => {
    targetRoute = this.processUrl(response);
    }),
    concatMap(() => {
    return combineLatest([
    this.getUser$(),
    this.isAuthenticated$
    ]);
    })
    );
    authComplete$.subscribe(([user, loggedIn]) => {
    this.router.navigate([targetRoute]);
    });
    }
    }
    }
    @samjulien

    View Slide

  159. @samjulien

    View Slide

  160. export class AuthService {
    handleRedirectCallback$ =
    from(this.authClient.handleRedirectCallback());
    }
    @samjulien

    View Slide

  161. export class AuthService {
    handleRedirectCallback$ =
    from(this.authClient.handleRedirectCallback());
    getUser$(options) {
    return from(this.authClient.getUser(options));
    }
    login() {
    this.authClient.loginWithRedirect();
    }
    logout() {
    this.authClient$.logout();
    }
    } @samjulien

    View Slide

  162. export class AuthService {
    handleRedirectCallback$ =
    from(this.authClient.handleRedirectCallback());
    getUser$(options) {
    return from(this.authClient.getUser(options));
    }
    login() {
    this.authClient.loginWithRedirect();
    }
    logout() {
    this.authClient$.logout();
    }
    } @samjulien

    View Slide

  163. export class AuthService {
    handleRedirectCallback$ =
    from(this.authClient.handleRedirectCallback());
    getUser$(options) {
    return from(this.authClient.getUser(options));
    }
    login() {
    this.authClient.loginWithRedirect();
    }
    logout() {
    this.authClient$.logout();
    }
    } @samjulien

    View Slide

  164. export class AuthService {
    handleRedirectCallback$ =
    from(this.authClient.handleRedirectCallback());
    getUser$(options) {
    return from(this.authClient.getUser(options));
    }
    login() {
    this.authClient.loginWithRedirect();
    }
    logout() {
    this.authClient$.logout();
    }
    } @samjulien

    View Slide

  165. export class AuthService {
    handleRedirectCallback$ =
    from(this.authClient.handleRedirectCallback());
    getUser$(options) {
    return from(this.authClient.getUser(options));
    }
    login() {
    this.authClient.loginWithRedirect();
    }
    logout() {
    this.authClient$.logout();
    }
    } @samjulien

    View Slide

  166. The authentication service is a
    thin wrapper for the SDK.
    @samjulien

    View Slide

  167. View Slide

  168. State Side Effects
    @samjulien

    View Slide

  169. Side Effects
    @samjulien

    View Slide

  170. How do we handle events don’t
    directly change state?
    @samjulien

    View Slide

  171. Effects

    View Slide

  172. Start login
    Handle redirect
    Log in to provider
    @samjulien

    View Slide

  173. Handle redirect
    Success
    Error
    @samjulien

    View Slide

  174. Success
    @samjulien

    View Slide

  175. Success
    User Token
    Authenticated
    @samjulien

    View Slide

  176. Success
    User Token
    Authenticated
    Redirect
    @samjulien

    View Slide

  177. login$ = createEffect(
    () =>
    this.actions$.pipe(
    ofType(AuthActions.login),
    tap(() => this.authService.login())
    ),
    { dispatch: false }
    );
    @samjulien

    View Slide

  178. login$ = createEffect(
    () =>
    this.actions$.pipe(
    ofType(AuthActions.login),
    tap(() => this.authService.login())
    ),
    { dispatch: false }
    );
    @samjulien

    View Slide

  179. login$ = createEffect(
    () =>
    this.actions$.pipe(
    ofType(AuthActions.login),
    tap(() => this.authService.login())
    ),
    { dispatch: false }
    );
    @samjulien

    View Slide

  180. login$ = createEffect(
    () =>
    this.actions$.pipe(
    ofType(AuthActions.login),
    tap(() => this.authService.login())
    ),
    { dispatch: false }
    );
    @samjulien

    View Slide

  181. handleRedirect$ = createEffect(() =>
    this.actions$.pipe(
    ofType(AuthActions.handleRedirect),
    exhaustMap(() => {
    @samjulien
    )
    );
    ... })

    View Slide

  182. handleRedirect$ = createEffect(() =>
    this.actions$.pipe(
    ofType(AuthActions.handleRedirect),
    exhaustMap(() => {
    @samjulien
    )
    );
    ... })

    View Slide

  183. handleRedirect$ = createEffect(() =>
    this.actions$.pipe(
    ofType(AuthActions.handleRedirect),
    exhaustMap(() => {
    @samjulien
    )
    );
    ... })

    View Slide

  184. handleRedirect$ = createEffect(() =>
    this.actions$.pipe(
    ofType(AuthActions.handleRedirect),
    exhaustMap(() => {
    @samjulien
    )
    );
    ... })

    View Slide

  185. exhaustMap(() => {
    @samjulien
    ...

    View Slide

  186. exhaustMap(() => {
    @samjulien
    // handle redirect and process tokens
    this.authService.handleRedirect.pipe(
    map(({ redirectUrl }) =>
    AuthActions.handleRedirectSuccess(
    { redirectUrl }
    )),
    catchError(({ error }) =>
    AuthActions.handleRedirectFailure(
    { error }
    ))
    );

    View Slide

  187. exhaustMap(() => {
    @samjulien
    // handle redirect and process tokens
    this.authService.handleRedirect.pipe(
    map(({ redirectUrl }) =>
    AuthActions.handleRedirectSuccess(
    { redirectUrl }
    )),
    catchError(({ error }) =>
    AuthActions.handleRedirectFailure(
    { error }
    ))
    );

    View Slide

  188. exhaustMap(() => {
    @samjulien
    // handle redirect and process tokens
    this.authService.handleRedirect.pipe(
    map(({ redirectUrl }) =>
    AuthActions.handleRedirectSuccess(
    { redirectUrl }
    )),
    catchError(({ error }) =>
    AuthActions.handleRedirectFailure(
    { error }
    ))
    );

    View Slide

  189. exhaustMap(() => {
    @samjulien
    // handle redirect and process tokens
    this.authService.handleRedirect.pipe(
    map(({ redirectUrl }) =>
    AuthActions.handleRedirectSuccess(
    { redirectUrl }
    )),
    catchError(({ error }) =>
    AuthActions.handleRedirectFailure(
    { error }
    ))
    );

    View Slide

  190. exhaustMap(() => {
    @samjulien
    // handle redirect and process tokens
    this.authService.handleRedirect.pipe(
    map(({ redirectUrl }) =>
    AuthActions.handleRedirectSuccess(
    { redirectUrl }
    )),
    catchError(({ error }) =>
    AuthActions.handleRedirectFailure(
    { error }
    ))
    );

    View Slide

  191. exhaustMap(() => {
    @samjulien
    // handle redirect and process tokens
    this.authService.handleRedirect.pipe(
    map(({ redirectUrl }) =>
    AuthActions.handleRedirectSuccess(
    { redirectUrl }
    )),
    catchError(({ error }) =>
    AuthActions.handleRedirectFailure(
    { error }
    ))
    );

    View Slide

  192. handleRedirectSuccess$ = createEffect(
    () =>
    this.actions$.pipe(
    ofType(AuthActions.handleRedirectSucess),
    tap(({ redirectUrl }) =>
    this.router.navigate([redirectUrl]))
    ),
    { dispatch: false }
    );
    @samjulien

    View Slide

  193. handleRedirectSuccess$ = createEffect(
    () =>
    this.actions$.pipe(
    ofType(AuthActions.handleRedirectSucess),
    tap(({ redirectUrl }) =>
    this.router.navigate([redirectUrl]))
    ),
    { dispatch: false }
    );
    @samjulien

    View Slide

  194. handleRedirectSuccess$ = createEffect(
    () =>
    this.actions$.pipe(
    ofType(AuthActions.handleRedirectSucess),
    tap(({ redirectUrl }) =>
    this.router.navigate([redirectUrl]))
    ),
    { dispatch: false }
    );
    @samjulien

    View Slide

  195. handleRedirectSuccess$ = createEffect(
    () =>
    this.actions$.pipe(
    ofType(AuthActions.handleRedirectSucess),
    tap(({ redirectUrl }) =>
    this.router.navigate([redirectUrl]))
    ),
    { dispatch: false }
    );
    @samjulien

    View Slide

  196. checkAuth$ = createEffect(() =>
    this.actions$.pipe(
    ofType(AuthActions.checkAuth, AuthActions.handleRedirectSuccess),
    concatMap(() =>
    this.authService.isAuthenticated$.pipe(
    map(isAuthenticated =>
    isAuthenticated
    ? AuthActions.checkAuthSuccess({ isAuthenticated })
    : AuthActions.setNotAuthenticated({ isAuthenticated })
    )
    )
    )
    )
    );
    @samjulien

    View Slide

  197. checkAuth$ = createEffect(() =>
    this.actions$.pipe(
    ofType(AuthActions.checkAuth, AuthActions.handleRedirectSuccess),
    concatMap(() =>
    this.authService.isAuthenticated$.pipe(
    map(isAuthenticated =>
    isAuthenticated
    ? AuthActions.checkAuthSuccess({ isAuthenticated })
    : AuthActions.setNotAuthenticated({ isAuthenticated })
    )
    )
    )
    )
    );
    @samjulien

    View Slide

  198. checkAuth$ = createEffect(() =>
    this.actions$.pipe(
    ofType(AuthActions.checkAuth, AuthActions.handleRedirectSuccess),
    concatMap(() =>
    this.authService.isAuthenticated$.pipe(
    map(isAuthenticated =>
    isAuthenticated
    ? AuthActions.checkAuthSuccess({ isAuthenticated })
    : AuthActions.setNotAuthenticated({ isAuthenticated })
    )
    )
    )
    )
    );
    @samjulien

    View Slide

  199. checkAuth$ = createEffect(() =>
    this.actions$.pipe(
    ofType(AuthActions.checkAuth, AuthActions.handleRedirectSuccess),
    concatMap(() =>
    this.authService.isAuthenticated$.pipe(
    map(isAuthenticated =>
    isAuthenticated
    ? AuthActions.checkAuthSuccess({ isAuthenticated })
    : AuthActions.setNotAuthenticated({ isAuthenticated })
    )
    )
    )
    )
    );
    @samjulien

    View Slide

  200. checkAuth$ = createEffect(() =>
    this.actions$.pipe(
    ofType(AuthActions.checkAuth, AuthActions.handleRedirectSuccess),
    concatMap(() =>
    this.authService.isAuthenticated$.pipe(
    map(isAuthenticated =>
    isAuthenticated
    ? AuthActions.checkAuthSuccess({ isAuthenticated })
    : AuthActions.setNotAuthenticated({ isAuthenticated })
    )
    )
    )
    )
    );
    @samjulien

    View Slide

  201. checkAuth$ = createEffect(() =>
    this.actions$.pipe(
    ofType(AuthActions.checkAuth, AuthActions.handleRedirectSuccess),
    concatMap(() =>
    this.authService.isAuthenticated$.pipe(
    map(isAuthenticated =>
    isAuthenticated
    ? AuthActions.checkAuthSuccess({ isAuthenticated })
    : AuthActions.setNotAuthenticated({ isAuthenticated })
    )
    )
    )
    )
    );
    @samjulien

    View Slide

  202. checkAuth$ = createEffect(() =>
    this.actions$.pipe(
    ofType(AuthActions.checkAuth, AuthActions.handleRedirectSuccess),
    concatMap(() =>
    this.authService.isAuthenticated$.pipe(
    map(isAuthenticated =>
    isAuthenticated
    ? AuthActions.checkAuthSuccess({ isAuthenticated })
    : AuthActions.setNotAuthenticated({ isAuthenticated })
    )
    )
    )
    )
    );
    @samjulien

    View Slide

  203. checkAuth$ = createEffect(() =>
    this.actions$.pipe(
    ofType(AuthActions.checkAuth, AuthActions.handleRedirectSuccess),
    concatMap(() =>
    this.authService.isAuthenticated$.pipe(
    map(isAuthenticated =>
    isAuthenticated
    ? AuthActions.checkAuthSuccess({ isAuthenticated })
    : AuthActions.setNotAuthenticated({ isAuthenticated })
    )
    )
    )
    )
    );
    @samjulien

    View Slide

  204. on(
    AuthActions.checkAuthSuccess,
    AuthActions.setNotAuthenticated,
    (state, { isAuthenticated }) => {
    return {
    ...state,
    isAuthenticated,
    };
    }
    )
    @samjulien

    View Slide

  205. loadUser$ = createEffect(() =>
    this.actions$.pipe(
    ofType(AuthActions.loadUser, AuthActions.checkAuthSuccess),
    exhaustMap(() =>
    this.authService.getUser$().pipe(
    map(user => {
    return AuthActions.loadUserSuccess({ user });
    })
    )
    )
    )
    );
    @samjulien

    View Slide

  206. loadUser$ = createEffect(() =>
    this.actions$.pipe(
    ofType(AuthActions.loadUser, AuthActions.checkAuthSuccess),
    exhaustMap(() =>
    this.authService.getUser$().pipe(
    map(user => {
    return AuthActions.loadUserSuccess({ user });
    })
    )
    )
    )
    );
    @samjulien

    View Slide

  207. loadUser$ = createEffect(() =>
    this.actions$.pipe(
    ofType(AuthActions.loadUser, AuthActions.checkAuthSuccess),
    exhaustMap(() =>
    this.authService.getUser$().pipe(
    map(user => {
    return AuthActions.loadUserSuccess({ user });
    })
    )
    )
    )
    );
    @samjulien

    View Slide

  208. loadUser$ = createEffect(() =>
    this.actions$.pipe(
    ofType(AuthActions.loadUser, AuthActions.checkAuthSuccess),
    exhaustMap(() =>
    this.authService.getUser$().pipe(
    map(user => {
    return AuthActions.loadUserSuccess({ user });
    })
    )
    )
    )
    );
    @samjulien

    View Slide

  209. loadUser$ = createEffect(() =>
    this.actions$.pipe(
    ofType(AuthActions.loadUser, AuthActions.checkAuthSuccess),
    exhaustMap(() =>
    this.authService.getUser$().pipe(
    map(user => {
    return AuthActions.loadUserSuccess({ user });
    })
    )
    )
    )
    );
    @samjulien

    View Slide

  210. on(
    AuthActions.loadUserSuccess,
    (state, { user }) => {
    return {
    ...state,
    user,
    };
    }),
    @samjulien

    View Slide

  211. Success
    User Token
    Authenticated
    @samjulien

    View Slide

  212. User
    Token
    Authenticated
    @samjulien

    View Slide

  213. User
    Token
    Authenticated
    @samjulien

    View Slide

  214. Reducers
    Components
    Effects
    Auth Service
    @samjulien

    View Slide

  215. Effects are the brain of the authentication flow.
    @samjulien

    View Slide

  216. View Slide

  217. Let’s Review

    View Slide

  218. View Slide

  219. View Slide

  220. Auth in NgRx looks different
    than auth in vanilla Angular.
    @samjulien

    View Slide

  221. Feature development in NgRx
    looks different than feature
    development in vanilla Angular.
    @samjulien

    View Slide

  222. View Slide

  223. Start login
    Handle redirect
    Log in to provider
    @samjulien

    View Slide

  224. Handle redirect
    Success
    Error
    @samjulien

    View Slide

  225. @samjulien

    View Slide

  226. Auth Service
    @samjulien

    View Slide

  227. Auth Service
    Components
    Data Services
    @samjulien

    View Slide

  228. @samjulien

    View Slide

  229. State Side Effects
    @samjulien

    View Slide

  230. Auth Service
    Components
    Data Services
    @samjulien

    View Slide

  231. Reducers
    Components
    Effects
    Auth Service
    @samjulien

    View Slide

  232. View Slide

  233. View Slide

  234. View Slide

  235. View Slide

  236. Reducers
    Components
    Effects
    Auth Service
    @samjulien

    View Slide

  237. View Slide

  238. View Slide

  239. samj.im/ngindia
    @samjulien

    View Slide

  240. samj.im/ngindia
    Thank you!
    @samjulien

    View Slide