i have an application frontend developed using React Js and Backend created using Express Js. Api calls are done using Axios.
The requirement is to authenticate and authorize a certain user with system privileges (role based).
Simple steps of the development
- Login using AZURE AD (Completed) using MSAL
- Parse response to backend to validate the tokens (requires help on how to do it) and if the token is valid the api routes can be accessed if not return response as failed authentication
I want to know what to pass from frontend MSAL response to backend express api and how to validate the response tokens and work with refresh tokens using passport js.
This is how i get the response from MSAL using AZURE AD (O365 LOGIN), i want to know what should i pass from the response to backend express js api?
import { useMsal } from '@azure/msal-react';
import { loginRequest } from '../../common/authConfig';
import { useIsAuthenticated } from '@azure/msal-react';
useEffect(() => {
const token = window.sessionStorage.getItem('token');
if (token == null && !isAuthenticated) {
handleLogin();
}
handAuth(isAuthenticated);
}, [isAuthenticated]);
const handAuth = (authenticated) => {
console.log(authenticated);
if (authenticated) {
instance
.acquireTokenSilent({
...loginRequest,
account: accounts[0],
})
.then((response) => {
console.log(response);
window.sessionStorage.setItem('token', response.idToken);
window.sessionStorage.setItem('email', response.account.username);
})
.then(() => {
const token = window.sessionStorage.getItem('token');
const email = window.sessionStorage.getItem('email');
console.log('new' + token);
console.log('email' + email);
});
}
};
const handleLogin = () => {
const accounts = instance.getAllAccounts();
if (accounts.length > 0) {
instance.setActiveAccount(accounts[0]);
}
instance
.handleRedirectPromise()
.then((authResult) => {
if (!authResult) {
instance.loginRedirect();
}
})
.catch((err) => {
console.log(err);
});
// instance.loginRedirect(loginRequest).catch((e) => {
// console.log(e);
// });
};
my server class code where i want to know how to validate the token and check if token is valid then grant access to the api/users route
const http = require('http');
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const HttpError = require('./models/http-error');
require('dotenv').config();
const server = express();
const uri = process.env.ATLAS_URI;
const port = process.env.PORT || 5000;
server.use(cors());
server.use(express.json());
const userRoutes = require('./routes/user-routes');
server.use('/api/users', userRoutes);
//#region Error Handing
server.use((req, res, next) => {
const error = new HttpError('Could not find this route.', 404);
throw error;
});