Authenticating with OpenID Connect (OIDC) in TypeScript<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Authenticating with OpenID Connect (OIDC) in TypeScript

Posted on: October 31, 2017

Connecting to OpenID Connect (OIDC) and OAuth2 protocol support for browser-based applications is something that occurs more frequently. One well-known example is to use Google Auth to have your user authenticate instead of having to handle a custom password approach to your web application. My case was that I needed to authenticate against a private federated system.

Before going into detail, the project I am building is using React, Redux and TypeScript. In this article, I'll bring an open-source library named oicd-client-js. It's open source on Github and has a NPM package available.

First, you need to install the library, and second, you do not need any types for TypeScript -- the library contains the definition file. This is great because it means that it will be updated more frequently.

1npm install oidc-client --save

A word of caution, the library's documentation is very thin. While having some samples, most of them don't explain which settings are required to have it work. In this article, I won't call any function to log out else than flushing on the client side the local storage. If you look at the library, there are potential functions that could be called -- it never worked for me.

The first thing you need is to have your React component dispatching two events. One would be to log in, the other one to log out. I opted to have the dispatcher calling an action creator that looks like this:

1export function onAppLogin(): ThunkAction<void, AppRootReducer, {}> {
2 return (dispatch: Dispatch<Actions<void>>, getState: () => AppRootReducer, extra: {}) => {
3 dispatch(actionAppLoginStarted());
4 Auth.getInstance().login();
5 };
8export function onAppLogout(): ThunkAction<void, AppRootReducer, {}> {
9 return (dispatch: Dispatch<Actions<void>>, getState: () => AppRootReducer, extra: {}) => {
10 Auth.getInstance().logout().then(() => {
11 dispatch(actionAppLogout()); });
12 };

Both are actually calling the singleton Auth which contains a login and logout function. The Auth class is a singleton because it will be used in these two functions but also in a Redux's Middleware later. The way it works is that when we will call the login function that this one will invoke the third-party library and will receive from the server a URL that the client will need to navigate to. This is required in case the user is not authenticated yet with the OpenId server. When the navigation is done, the server will callback the application. This is where the Redux's Middleware will be interesting. Since Redux's Middleware listen to every action, if we have a custom middleware we are able to listen if we expect to do any work. This is why we will use a temporary entry inside a local storage to set a flag saying if we need to do any login or logout work. In the case of login, we will fetch the user's information and dispatch an action that will store the access token and user's name, email, etc into our store. For the logout, same thing. The middleware will remove the user from the store once this one is getting dismissed.

1import OIDC, { UserManagerSettings } from "oidc-client";
3export class Auth {
5 private static OidcSettings: UserManagerSettings = {
6 automaticSilentRenew: true,
7 authority: "",
8 client_id: "cdnadminpartner",
9 redirect_uri: window.location.protocol + "//" + + "/index",
10 post_logout_redirect_uri: window.location.protocol + "//" + + "/index",
11 silent_redirect_uri: window.location.protocol + "//" + + "/index",
12 response_type: "code token id_token", scope: "openid profile",
13 loadUserInfo: true,
14 userStore: new OIDC.WebStorageStateStore({ store: window.localStorage })
15 };
17 private static instance: Auth;
18 private static readonly KEY_FOLLOW = "my_app_follow_action_required";
19 private static readonly KEY_PROCESS_LOGIN = "login";
20 private static readonly KEY_PROCESS_LOGOUT = "logout";
22 private user: OIDC.UserManager;
24 public static getInstance(): Auth {
25 if (Auth.instance === undefined) {
26 Auth.instance = new Auth();
27 }
28 return Auth.instance;
29 }
31 public process(): Promise<UserFromMeechum | undefined> {
32 if (this.mustFollowAuthLogin()) {
33 return this.processSigninResponse()
34 .then((response) => { return response; });
35 } else if (this.mustFollowAuthLogout()) {
36 return this.processSignoutResponse() .
37 then((response) => {
38 return undefined;
39 });
40 } else {
41 return this.getUser();
42 }
43 }
45 public getUser(): Promise<any | null> { return this.user.getUser(); }
47 public login(): void { this.user.createSigninRequest() .then((response) => {
48 this.getStorage().setItem(Auth.KEY_FOLLOW, Auth.KEY_PROCESS_LOGIN);
49 window.location.href = response.url;
50 });
51 }
53 public logout(): Promise<void> {
54 return this.user .removeUser();
55 }
57 private constructor(private storage: StorageType = StorageType.LocalStorage) {
58 const level = Log.getOptions().logMaxLevelOfTracing;
59 const verboseLevel = TraceType.Verbose;
60 if (level >= verboseLevel) {
61 OIDC.Log.logger = console;
62 OIDC.Log.level = OIDC.Log.DEBUG;
63 }
64 this.user = new OIDC.UserManager(Auth.OidcSettings);
65 }
66 private processSigninResponse(): Promise<UserFromMeechum> {
67 this.getStorage().removeItem(Auth.KEY_FOLLOW);
68 return this.user.signinRedirectCallback();
69 }
71 private processSignoutResponse(): Promise<null> {
72 this.getStorage().removeItem(Auth.KEY_FOLLOW);
73 return this.user .processSignoutResponse()
74 .then((response) => { return null; });
75 }
77 private mustFollowAuthLogin(): boolean {
78 return window.localStorage.getItem(Auth.KEY_FOLLOW) === Auth.KEY_PROCESS_LOGIN;
79 }
81 private mustFollowAuthLogout(): boolean {
82 return window.localStorage.getItem(Auth.KEY_FOLLOW) === Auth.KEY_PROCESS_LOGOUT;
83 }

The middleware is getting hammered, like any middleware. However, the only task it does is to check for the localstorage to see if a flag for action is required or not. If not, it calls the next middleware. It's pretty fast. Otherwise, it goes the final step for the authentication.

Further work could be done in term of logout by calling createSignoutRequest for instance. I have created a Github issue and hope to get an answer by the time this article is published. At the moment, the problem is that the library response with "No end session endpoint url returned" which is awkward because if we look at the source code, the endpoint is optional. I do not set this one (and haven't found where it can be set). Nevertheless, the code of this article works well and you will have your token id and access id as well as all the user information.