Sign In With Microsoft Azure, Firebase & React Redux [2020]

Krupesh Anadkat
Xebia Engineering Blog
11 min readOct 26, 2020

Most application we see today require users to sign in. Username & password was the best bet (like decades ago 🧐).. Making your apps support Single Sign On (SSO) is very common & “good to have” feature. Users are not going to memorize dozens of passwords.

Forget User comfort, but is it worth creating a backend infrastructure just so you can provide an authentication method to client applications?? One might argue that “we have already created several microservices, why not also throw in custom authentication?” Ok, Go ahead & do it, also tryout things like OTP based auth. But it will never be as trivial as “Just Click -I am in”

Change My Mind

Prerequisites

  1. Free Microsoft Azure account
  2. Free Google Firebase account
  3. Good at ReactJS & Redux (must)
  4. Some familiarity with Azure & Firebase (nice to have, not required)

I am going to follow hands-on approach, so buckle up! Also, using Firebase for implementing Sign In With Microsoft is not mandatory, but it makes life little easy in development.

1. Azure App Registration

There are several screenshots down below, assuming you have already logged into portal.azure.com. End goal is to obtain client id, tenant id & secret key

Figure 1 : Azure App Registration

Figure 1 : You can either search for “App registrations” at top or select it from Azure Services section. In App Registration dashboard you need to click on “+ New registration” button at top left.

Figure 3 : Azure App Registration

Figure 3 : Filling form for registering new app. I have written most of the things in screenshot itself, please follow the steps in order of numbers. For Supported account types I am focusing on to keep it single organization employee only login for this article. But feel free to tryout other options, setup is identical except one minor change (I will let you know when we get there 🕹).

Figure 4 : Azure App Registration

Figure 4 : After you click Register in previous step, you will land on this web page within a minute. Grab the client id & tenant id and keep it safe somewhere. The final thing is secret key. Click on “Certificates & secrets”.

Figure 5 : Azure App Registration

Figure 5 : First click on “+ New client secret”, a modal box will pop up at top. Fill the details as shown in figure. Click “Add” button at last.

Figure 6 : Azure App Registration

Figure 6 : Finally, grab the “value” of secret key just created. That is it for now in Azure, we will come back here to link firebase redirect url.

Fun Fact

2. Firebase Setup

Firebase project setup is lengthier than Azure setup. Here End goal is to link Azure app with Firebase auth app.

2a. Creating Firebase Project

In Firebase we first create a project & then inside it we create app. Unlike Azure, where we directly created (or registered) app. Here you can add multiple apps inside one project.

Figure 1 : Firebase Setup

Figure 1 : Assuming you are already logged into firebase console, click on “Create a project” button.

Figure 2 : Firebase Setup

Figure 2 : Add the project name, accept the terms & continue. I am not enabling analytics to keep it simple. Click “Create Project” and then “Continue” once project is created.

2b. Creating Firebase App

Figure 3 : Firebase Setup

Figure 3 : Once you are inside project (verify project title at top left blue background), choose Web from the three icons -iOS, Android & Web.

Figure 4 : Firebase Setup

Figure 4 : Enter the App name & “Register app”. Then you will see the SDK code, from that just grab the firebaseConfig & initialize lines as highlighted above. “Continue to console” to setup authentication.

We will look at Firebase Hosting service probably in my next article. (It is free & easy, they also put SSL certificate on your web app for free forever)

Figure 5 : Firebase Setup

Figure 5 : Click on “Develop” in side panel then “Authentication”. On the tabs menu select “Sign-in method”. Here you will see all popular sign in methods. Good news is, firebase app setup & react-redux code setup is identical for most of them :)

Figure 6 : Firebase Setup

Figure 6 : Enable the Microsoft Sign-in method and add Application Id (client id) & Application Secret (value of secret). Grab callback or redirect url, we need to put this in our Azure app. Click “save” & Firebase setup is done!

Azure Portal Last Step

Figure 7 : Azure App Registration

Figure 7 : If you have closed Azure portal, then go back to our registered app & on top right, choose the second option Redirect URIs.

Figure 8 : App Registration

Figure 8 : Click the “Add URI” button first then paste the callback url we got from Figure 6 Firebase Setup. Check both the boxes of token types at bottom. Finally “Save” it from top. This url we just added helps firebase to authenticate user and store the auth state with Local Persistence (default).

There is something called MSAL Js, MicroSoft Authentication Library in Azure AD(Active Directory). If you do not want firebase to handle Microsoft auth, you may try that but it can be very tricky for beginners.

Trying to Become Cloud Developer

3. React Redux MS Auth Project

We are going to initialize react app with with React CRA & I am using VS Code 👨🏻‍💻. Open terminal in desktop folder & run below commands.

npx create-react-app ms-auth-app
cd ms-auth-app
code .

In the src folder I have kept only App.js & index.js Removed all other files & references.

I prefer renaming all component files to JSX for better autocomplete suggestions in vs code. App.js to App.jsx & index.js to index.jsx

3a. Project Dependencies

Installing all of them in one go :

npm i react-router-dom redux redux-thunk react-redux firebase react-redux-firebase

Project Commit until this point

3b. Project Structure : “Rails-style” Organization

Assets are grouped by “type” or “capability”: any action will be found in the Actions folder, any reducer will be found in Reducers, & so on. In fact, the “real world” example from Redux on GitHub structures the app this very way.

Frontend
- Components
- component1.js
- component2.js
- component3.js
- Actions
- action1.js
- action2.js
- Reducers
- reducer1.js
- Util
- Store

Our project structure : (Project Commit until this point)

src
- index.jsx
- Components
- App.jsx
- Layout
- Navbar.jsx
- Routes
- Dashboard.jsx
- Login.jsx
- Actions
- auth.js
- Reducers
- auth.js
- index.js
- Util
- firebaseConfig.js
- Store
- store.js

3c. Coding Simple & Quick Frontend with Bootstrap

We are not going to write any css/scss (being writing frontend code 😄) & keep it fairly Simple! Adding only css cdn from bootstrap docs in index.html in public folder. Besides that I have added favicons from favicon.io

Line 7 to 14

I have seen young developers not care about meta tags, favicons & sometimes even title, publishing react CRA defaults in production. Please avoid doing it!

Project Commit until this point.

Now we need a navigation bar at top, Login & Dashboard route where users will eventually log into. Before that let’s setup routing using react-router-dom

Routing : I have put a minimal routing of just two routes in App.jsx with <Navbar /> component at top inside <BrowserRouter> <BrowserRouter/>

App.jsx with Minimal Routing

Navigation Bar : We want users to see only Login button at top if they are not logged in. For logged in users, Dashboard & Logout button at top. For now let me put all of them, after setting up our authentication we can place checks.

Navbar.jsx

Notice I have used <NavLink /> instead of <Link /> because NavLink adds active class to active path as compared to Link component. Also notice exact attribute in NavLink component where path="/"

Login.jsx & Dashboard.jsx

Below is the screenshot of how both the routes would look like. Notice the Sign in with Microsoft button in Login route. I have plugged in the svg file from Microsoft Brand Guideline

Login & Dashboard Routes

Below is the Login.jsx functional component code. I have kept the brand svg in same folder as Login.jsx, one could even keep svgs, pngs.. in Assets directory of project.

Login.jsx

Dashboard.jsx functional component code below, much similar to Login component to keep things lite and minimal. (Project Commit Until Now)

Dashboard.jsx
Almost 8 hours into writing this blog :D

Actions, Reducer, & Firebase 🧠

We have completed building all of our UI, now it’s time to build the core of our application. Below is my approach for building any react redux project.

Refresher on Redux State Management :

From Official Redux Docs : https://redux.js.org/tutorials/essentials/part-1-overview-concepts

How to approach React Redux State Management Project?

  1. Plan the State Data Structure that you want to keep in redux store.
  2. Write down all the Actions user could perform that will eventually modify store data.
  3. Write Action Creators based on 2.
  4. Now the life becomes easy while making Reducers at last.

Jr. developers tend to jump on writing action creators & forget about planning Store State & Action types beforehand. Please try to avoid doing that.

1.Store State Planning : We will get basic user’s profile info from firebase built in reducer & we would like to track Login or Logout errors. Redux Store State planning docs has very easy language, try to read from that too.

Kept this in Utils folder

2. Action Types : Actions are simple to think. What will user do & what can happen based on that?

src/Actions/auth.js

To go for next step i.e. writing Action Creators, we first need to setup firebase config & Microsoft Auth Provider 🕹. Remember we grabbed some code of firebase SDK while registering new firebase app??

You can get back that config details from Firebase Project Console > Project Settings (sidebar gear icon at top left) > General Tab > scroll to bottom.

src/Util/firebaseConfig.js

If you have used Xebia’s email id to create Azure app then most likely your Tenant Id will match with what I have show in above code snippet. Most of the stuff is from firebase configuration sdk. Below is the consent prompt (line 23) shown to user while logging in.

Example of Consent Prompt for User Info

3. Action Creators (Thunked): One for Logging In & One for Logging Out.

Completed src/Actions/auth.js

Notice on line 12 & 25 in above snippet, we not only get dispatch & getState of store but also getFirebase method. This is due to react-redux-firebase library that we will use while creating store. Firebase has several signIn methods like

firebase.auth().signInWithPopup(provider)
firebase.auth().signInWithRedirect(provider)
firebase.auth().signInWithEmailAndPassword(email, password)

You can read more about each of them in Firebase docs. When we use Microsoft, Google, Facebook, Apple, .. SSOs we will use their OAuth Provider, in our case we are using Microsoft Provider.

For Signing Out user, it has a generic method. Below is straight from docs.

firebase.auth().signOut().then(function() {
// Sign-out successful.
}).catch(function(error) {
// An error happened.
});

4. Auth Reducer : It is small and simpler in this project because we are not dealing with any kind of CRUD on data like Posts, Messages.. Firebase built-in reducer will handle most of the stuff for us.

Completed src/Reducers/auth.js

Now let’s combine firebase reducer & our auth reducer, put it in index.js inside Reducers folder (Project Commit Until Now)

Completed src/Reducers/index.js

Creating Redux Store

The second last step of this article! We are also integrating Redux DevTools chrome extension to see our store state & actions dispatching.

src/index.jsx

The only difference between when we generally create store & here is : you would see getFirebase method (line 13) added to thunk middleware.

The way we have got Provider from react-redux to helps us connect components to store & access data or dispatch actions; similarly, we have got ReactReduxFirebaseProvider that helps us get firebase auth data (or Firestore data : not in scope of this article, just wanted to give you tickle! 😁)

src/index.jsx

You can refer React Redux Firebase docs to know more about its provider & props. I learnt most of it from there. We have completed creating our store, final index.jsx file looks like below: (Project Commit Until Now)

Completed src/index.jsx
Yeah, I Get That :D

LAST Thing : Connect Store, Login Action & Logout Action with UI

Login.jsx : I have simply connected store & added Login button handler i.e dispatching handleLogin() thunked action creator. In render method I am checking if user’s auth status is loaded and if a uid property is present, if yes then redirect to Dashboard

Below is how store would look like after user logs in from login route:

Chrome Redux Devtools

Dashboard.jsx : Just like Login, we will first connect with store, get auth state in props & redirect if user is not found in auth state, else show user info for instance his/her displayName:

Completed src/Components/Routes/Dashboard.jsx

Note that our mini project has protected route! If user is not logged in, we will force user to goto Login route (Line 7 to 9 above)

Navbar.jsx : Now that our Login & Dashboard is connected, we want navbar to connect with store & be able to dispatch handleLogout() to logout user. Also based on auth status ( auth.uid) we are choosing what to render on navbar.

Completed src/Components/Layout/Navbar.jsx
You Know What I Mean, HiFi !

I hope you learned something from this post. We have completed it together 🍻 Feel proud & take a moment to thank yourself to reach end (very few will reach here :)

Post your doubts in comment section below, also you can try asking via comments on article code gists, I will try to respond back in less than 4–5 hours.

--

--