The Cookie Monster

  • Cookie Authentication in Angular2

We has sso for all our sites at work.

All use a single cookie that is updated/refreshed by a main server.

What I'm building

These are some of the feature I need and there are a number of ways and methods to handle them.

  1. The Cookie are checked and refreshed.
    1. On initalization. To not display anything if needed.
    2. The server expires the cookie. Eg When Data is fetched (Eg. An /api call to the server can respond with clearing the cookies).
  2. When the Cookie is not found/needs to login:
    1. The user is redirected to an external login page with a return url.
  3. Rolling loginCookie Sync, At a set interval. To keep the cookie sychronized. This is a different endpoint

Doing something everytime a component is activated

OnActivate is at the component level. Defines route lifecycle method routerOnActivate, which is called by the router at the end of a successful route navigation.

Sounds about right What are the other lifecycle methods hear you ask? Well.

# Router lifecycle methods
OnActivate
OnDeactivate

Use the routing and check authentication inside each destination component.

This means each component will require an explicit method. This results in the 'base' base not checking because it containes the routing.

import { Component } from '@angular/core';
import { OnActivate, ROUTER_DIRECTIVES, RouteSegment, RouteTree, Routes } from '@angular/router';

@Component({
    // ...
    directives: [ROUTER_DIRECTIVES]
})
export class AuthenticatedComponent implements OnActivate {
  routerOnActivate(curr: RouteSegment, prev?: RouteSegment, currTree?: RouteTree, prevTree?: RouteTree) :void {
    // Do some check in here.
  }
}

Do something everytime the route changes

On the component with the router hook into the chages event. The exact name of the method can be pulled out for the actual angular 2 source. See the ./node_modules/@angular/router/src/router.d.ts file.

import { Router /*...there will be other is init the router*/ } from '@angular/router';
// ...
export class AppComponent implements OnInit {
  constructor(private _router:Router) {
    _router.changes.subscribe(()=> console.log('route changed fired' );
  }
  //..
}

Just do it on initalization

Do work on the before the app initalizes the first component.

import { OnInit } from '@angular/core';
// ...
export class AppComponent implements OnInit {
  ngOnInit() {
    // Do magic here...
  }
}