How to modularize Javascript authentication code in MFE context in a VueJS - javascript

I'm working on a large,single-page VueJS application that's been broken down into several micro front-ends, and I'm currently implementing the authentication for communication with the orchestration layer and it's stumping me. The application is organized as a container application that bootstraps and mounts several other VueJS applications underneath it using single-spa
We use Azure-AD and the MSAL library for authentication and to refresh the Bearer token before each API request, and currently the application I'm working had previously stored the AD client info itself and created the authenticationContext on initialization, something like
export class Authentiation {
authenticationContext;
refreshToken;
constructor() {
this.authenticationContext = new msal.PublicClientApplication(msalConfig)
// code to initialize the
}
async acquireToken() {
// code which refreshes the token
}
}
Now, the initial authentication code has been moved into the container application since it will authenticate the user first and only then mount the apps once the user is inside. Each application, though, needs to be able to refresh the Bearer token whenever it communicates with its OL layer. Currently, it's just running the initialization again and pulling the AuthenticationContext out of local storage using the supplied keys
The goal is to modify it so that a the authentication context from the container is passed down to whatever application is being mounted up, without the need to store the AD client and context information in the app itself
What's required is that every repository within the application would have an API object injected into it, and would use this API when making requests, and the API would contain the authentication context for being able to refresh the Bearer token on each call, and this is where I'm stumped
I had thought about creating an Authentication Singleton that the API could use when being injected into a repository, but since the authenticationContext is unknown at the time, it feels weird to set it after the fact, ie something like
let authContext = new Authentication()
// setup single-spa bootstrap code
// this function is called when the container application bootstraps this Vue application
export const bootstrap = (props) =>
vueLifecycles.bootstrap(props).then(async () => {
authContext.setContext(props.authentication)
})
Then when the API gets intialized, it would have an authContext that would invoke authContext.acquireToken() to get a Bearer token to set for each refresh. But, something feels incorrect about doing this way and I'm not 100% if it's the way to go.
To summarize, applications that were once handling authentication on their own are now being passed the authentication context as a prop during load, and I'm confused about how to implement this to properly set this context as part of the API
Another team had actually stored the acquireToken function in the a Vuex store but that, to me, does not seem appropriate since it ties this code specifically to Vue

Related

Vue component with API call in Laravel + Inertia

I can't undestand how to create a new Vue component inside my app created with Laravel and Inertia.
The problem is that I can't make a call from the component to an API (in the routes/api.php file) that is protected by an auth middleware (like auth:api).
There is a practical example:
I manage a list of customers in my app. Then I manage invoices. So, in the invoice creation form I must select one of the customers in my database. I want to make a componente (like <SelectCustomer v-model="form.customer" /> maybe) where inside itself I can make an API call that return the list of all customers to populate my select.
Obviously, that API is reserved only for the logged user, so has a middleware guard.
It's possible to make an axios call - maybe - in the component's methods? but with what informations? maybe I must obtain a bearer token?

How to prevent firebase db access from chrome console or other methods

So I have a single page frontend only app. Right now I have something like this
// db.js
import firebase from "firebase/app"
import "firebase/firestore";
var firebaseConfig = {
...
};
export const db = firebase
.initializeApp(firebaseConfig)
.firestore();
in main.js I was experimenting with putting the db instance in the global window scope just to see if I could go to the chrome web console and access it to submit a doc and indeed I can
// main.js
import { db } from './db'
window.db = db;
and then from chrome console
db.collection("test").add({'somekey': 'Can I add this doc?'})
How do I prevent someone from doing this without having a real backend to check auth? I like the reactivity of vue + firebase. If I don't expose the db variable to global scope is that enough? I was reading this post:
https://forum.vuejs.org/t/how-to-access-vue-from-chrome-console/3606/2
because any variable you create inside your main.js fiel will still not be globally available due to how webpack
One of the great things about Firestore is that you can access it directly from within your web page. That means that within that web page, you must have all configuration data to find the relevant Google servers, and find your Firebase project on those servers. In your example, that data is part of firebaseConfig.
Since you app needs this configuration, any malicious user can also get this data from your app. There is no way to hide this: if you app needs, a sufficiently motivated malicious user will be able to find it. And once someone has the configuration, they can use it to access your database.
The way to control access to the database, is by using Firebase's server-side security rules. Since these are enforced on the server, there is no way to bypass them, neither by your code, nor by the code that a malicious user writes.
You can use these security rules to ensure that all data is valid, for example making sure that all the required fields are there, and that there's no data that your app doesn't use.
But the common approach is to also ensure that all data access is authorized. This requires that your users are authenticated with Firebase Authentication. You can either require your users to sign in with their credentials, or you can anonymously sign them in. In the latter case they don't need to enter any credentials, but you can still ensure for example that each user can only write data to their own area of the data, and that they can only read their own data.

How does Express and React Routes work on initial GET request from browser?

I'm new to the react world and to the fullstack world as a whole but I've searched endlessly for an answer to the following and some guidance would be really appreciated.
I'm creating an app using React and Express. It requires authentication so I was planning on using Passport to help. The client side JS uses React Routers to navigate through the website. That's all fine but my issue is with the initial GET request made by the browser.
I'll first describe my specific app requirements and then generalize what I don't understand.
As I said, my application requires OAuth2 authentication. If you try to GET a path on my website and you're not logged in, it should just load the login page. If you are logged in, then load as normal and find your path. Similar to facebook, I'd like the login URL to be the same as the "feed" page. So similar to how facebook.com '/' route is either the login page or your new feed depending on whether you are signed in, I want the same thing.
From what I understand, Passport authenticates on the back end by checking the request header. So I understand that I should have some kind of middleware that says "if user is signed in, continue down the routes otherwise render sign in page" ... How is this done? What would the code look like? My only experience with Express was from an intro class which used res.render to send back an HTML file and pass it through some template engine like handlebars. But I have no idea how it'd work with react routes. Would i still use res.render()? Something else?
Let's say my index.html has the root div to inject the react into. If I had to guess, I'd send back that index.html page with the .js file with the routes and somehow on the backend send back the route I want it to match on my react routes (either the login one or the user requested)??
More generally, I guess I'm just confused how the initial request to a website using react routes is done. 1) How does the server interact with everything to render what I asked for? 2) What would the code look like for that. My only experience with React is from a basic Udemy course that just used "react-scripts start" to render the page.
After spending the entire day Googling this question it led me to SSR which is a rabbit-hole of its own and I'm not even sure if its what I need to help me. Is it?
I'm clearly missing some fundamental knowledge as this is really tripping me up so if you have any resources to learn more just post them. Thanks!
I understand your struggle as I've had to go through it myself when combining front-end with back-end, specifically React and Node. So first things first, we know that the browser/client will always initiate a request to the server, so how does React Router take control of the routes? Well its plain simple actually, all you have to do is return the entire react app from any route from your express server. The code will look something like this:
const express = require('express');
const app = express();
app.get('/*', (req, res, next) => {
// Return React App index.html
});
app.listen(3000);
Once the react app renders on the user browser (don't worry about paths, as react will automatically render according to the URL based on the code you wrote in the client side, it will also take care of authentication vs feed page when it will scan for your local storage, cookies, etc), it will take control of routing, instead of a request going to the express server. But what happens when we request data from our server, well it returns react app on each route so we need to setup an api route to handle any data requests.
app.get('/api/v1/*', (req, res, next) {
// Return some data in json format
});
Hopefully, this gives you insight about what you were looking for.
I think the fundamental gap you're struggling with stems from that lot of those 'intro courses' shove the entire browser client into the application server to get things up and running quickly, as in, the Node server renders the entire React app AND operates as an API...
// Ajax request from React app to: http://example.com/api
app.use('/api/*'),()=> {
res.send({ <!-- some JSON object -->})
})
// User visits in browser: http://example.com/**/*
app.use('/*',()=>{
res.render(<!-- entire React App sent to browser -->)
})
The first request (assuming the user doesn't visit /api/* ) will just send down the React bundle. Further user navigation within the client would generally send XHR requests (or open WebSockets) from the React app to Express routes running on the same node program.
In many situations it makes sense to have these parts of your program separated, as by having react delivered from a completely different location than where it requests data. There's many reasons for this, but optimizing computing resources to their differing demands of CPU, memory, network .etc and manageability of code/deployment are the big reasons for me.
For example...
User visits: http://example.com *
Nginx, Apache, a 'cloud proxy' .etc direct the traffic to a static React bundle, which has no authentication and never makes contact with your Node server.
If the user has Authenticate previously they will have token in local storage (if you're using JWTs for Authentication) and your React app will be configured to always check for these tokens when you first it is initially loaded.
If the user has a token it will send an Ajax request in the background with the token as a Header Bearer and will send back user data, then redirect them to an 'Authenticated page' like the FB feed you mention.
If they don't have a token or the token Authentication fails then React will redirect them to the Login or Registration page
React
React basically high jacks the browser's native 'location' functionality (whats displayed after you domain name). So any events after the initial page load (buttons clicks and such) are handled entirely by React internally and uses those routes to determine what to display or what data to fetch from the API through Ajax (XHR).
If the user performs a hard page reload then that request will go back to the server and it will perform the whole cycle over again
React Router
Allows you to do 2 things simultaneously...
Manipulate the browser Location and History objects.
Use that History and Location information elsewhere by detecting changes and sending off events.
SSR
I've only toyed around with SSR so I can speak to it, but its provides extremely low latency for initial renders, doing it in 1 network request, so you want to use it areas of your program where thats important.
Not sure if this answers you question, but let me know if you would like me to elaborate on anything or provide some more detailed resources.
SSR is a little bit confuses for developer that has less experience, let forget it for now.
It will be more easier for you to assume that frontend JavaScript (React) and backend Javascript (NodeJS) are two separate apps, and they communicate to each other via API.
here the code that show Login component and Feed component depending on whether you are signed in
import React, { Component } from "react";
import axios from "axios";
class Home extends Component {
constructor() {
const accessToken = localStorage.getItem("accessToken");
this.state = {
accessToken,
feeds: []
};
}
componentDidMount() {
if (this.state.accessToken) {
axios(`api/feeds?accessToken=${this.state.accessToken}`).then(({ data }) => {
this.setState({
feeds: data
});
});
}
}
render() {
if (this.state.accessToken) {
return <FeedsComponent feeds={this.state.feeds} />;
}
return <LoginComponent />;
}
}
and this is your backend
const express = require("express");
const app = express();
app.get('/api/feeds', (req, res, ) => {
const feeds = [
{},
{}
]
res.status(200).json(feeds);
});
app.listen(3001);
just keep in mind that they are two separate apps, the can be in two different folder, different server, different port.
Simply point Express to the folder containing your React files or build files.
app.use(express.static(__dirname + '/dist'));
where 'dist' contains the build files
See docs for more details

Access React app from other React app on the same page

I have a situation where I have written the front-end of my website as micro-services. Every functional section of my website is a react-habitat application bundled with css and html. I have done this so I can re-use these sections wherever I want on the site.
My problem is however in the checkout area I need to pass the customerId from the login application (on successful response) into the delivery address application so I can bring back the default address. I don't want to create a new application and duplicate the code for login and delivery address applications because I will need to use them elsewhere on the website.
So my question is. How can I pass this customerId from my login application to my delivery address application without a page reload? Is there a way to access a react application method from outside of that react application?
Login click handler:
clickHandler(e) {
e.preventDefault();
let payload = {"email":this.props.email, "password":this.props.password};
AuthenticationApp.login(payload).then((response) => {
if (this.props.referrer === "checkout") {
$("#checkout_login-register-tab").addClass("done");
$("#checkout_login-delivery-tab").removeClass("todo");
// Temporary hack to reload page until we can pass new user session into delivery/billing react app from here.
location.reload();
}
this.props.updateParentState({isLoggedIn: true});
})
.catch(function(response){
console.log("res2 - catch", response)
});
}
I have forced a page reload here so the delivery address application re-renders and picks up customerId from the service. I need a way to re-render the delivery application at this stage (from this separate application), either by accessing a function somehow or forcing the application to reset? Is this possible or is there a workaround other than a page reload?
You can do something like this:
loadDeliveryApp(data) {
ReactDOM.render(<DeliveryApp data={data} />, document.getElementById('delivery-app'))
ReactDOM.unmountComponentAtNode(document.getElementById("login-app"))
}
clickHandler(e) {
e.preventDefault()
// your login stuff
loadDeliveryApp(data)
}
Here is the working demo.
https://codepen.io/madhurgarg71/pen/dzgxMd
I'm the original creator of React Habitat.. all your applications can talk to each other via either a flux observer or something like redux.
I suggest flux for react habitat normally as the individual stores keep it light weight instead of one BIG store in redux where you might have dead code in a habitat situation.
You will need to create one common store that both your applications import so that if one changes it, the other will get the update. I can put a demo together later if that helps.

Communicating with a web widget-Meteor, React, Node

I'm building a chat dashboard and widget with which a customer should be able to put the widget into their page. Some similar examples would be Intercom or Drift.
Currently, the "main" application is written in Meteor.js (it's front end is in React). I've written a <Widget /> component and thrown it inside a /widget directory. Inside this directory, I also have an index.jsx file, which simply contains the following:
import React from 'react';
import ......
ReactDOM.render(
<Widget/>,
document.getElementById('widget-target')
);
I then setup a webpack configuration with an entry point at index.jsx and when webpack is run spits out a bundle.js in a public directory.
This can then be included on another page by simply including a script and div:
<script src="http://localhost:3000/bundle.js" type="text/javascript"></script>
<div id="widget-target"></div>
A few questions:
What is wrong with this implementation? Are their any security issues to be aware of? Both the examples linked earlier seem make use of an iframe in one form or another.
What is the best way to communicate with my main meteor application? A REST API? Emit events with Socket.io? The widget is a chat widget, so I need to send messages back and forth.
How can I implement some sort of unique identifier/user auth for the user and the widget? Currently, the widget is precompiled.
1 What is wrong with this implementation? Are their any security issues to be aware of? Both the examples linked earlier seem make use of an iframe in one form or another.
As #JeremyK mentioned, you're safer within an iFrame. That being said, there's a middle route that many third parties (Facebook, GA, ...) are using, including Intercom:
ask users to integrate your bundled code within their webpage. It's then up to you to ensure you're not introducing a security vulnerability on their site. This code will do two things:
take care of setting up an iframe, where the main part of your service is going to happen. You can position it, style it etc. This ensure that all the logic happening in the iframe is safe and you're not exposed.
expose some API between your customer webpage and your iframe, using window messaging.
the main code (the iframe code) is then loaded by this first script asynchronously, and not included in it.
For instance Intercom ask customers to include some script on their page: https://developers.intercom.com/docs/single-page-app#section-step-1-include-intercom-js-library that's pretty small (https://js.intercomcdn.com/shim.d97a38b5.js). This loads extra code that sets the iFrame and expose their API that will make it easy to interact with the iFrame, like closing it, setting user properties etc.
2 What is the best way to communicate with my main meteor application? A REST API? Emit events with Socket.io? The widget is a chat widget, so I need to send messages back and forth.
You've three options:
Build your widget as an entire Meteor app. This will increase the size of the code that needs to be loaded. In exchange for the extra code, you can communicate with your backend through the Meteor API, like Meteor.call, get the reactivity of all data (for instance if you send a response to a user through your main Meteor application, the response would pop up on the client with no work to do as long as they are on the same database (no need to be on the same server)), and the optimistic UI. In short you've all what Meteor offers here, and it's probably going to be easier to integrate with your existing backend that I assume is Meteor.
Don't include Meteor. Since you're building a chat app, you'll probably need socket.io over a traditional REST API. For sure you can do a mix of both
Use Meteor DDP. (it's kind of like socket.io, but for Meteor. Meteor app use that for all requests to the server) This will include less things that the full Meteor and probably be easier to integrate to your Meteor backend than a REST API / socket.io, and will be some extra work over the full Meteor.
3 How can I implement some sort of unique identifier/user auth for the user and the widget?
This part should probably do some work on the customer website (vs in your iframe) so that you can set cookies on his page, and send that data to your iframe that's gonna talk to your server and identify the user. Wether you use artwells:accounts-guest (that's based on meteor:accounts-base) is going to depend on wether you decide to include Meteor in your iframe.
If you don't have Meteor in your iframe, you can do something like:
handle user creation yourself, by simply doing on your server
.
const token = createToken();
Users.insert({ tokens: [token] });
// send the token back to your iframe
// and set is as a cookie on your customer website
then for each call to your server, on your iframe:
.
let token;
const makeRequest = async (request) => {
token = token || getCookieFromCustomerWebsite();
// pass the token to your HTTP / socket.io / ... request.
// in the header of whatever
return await callServer(token, request);
};
in the server have a middleware that sets the user. Mine looks like:
.
const loginAs = (userId, cb) => {
DDP._CurrentInvocation.withValue(new DDPCommon.MethodInvocation({
isSimulation: false,
userId,
}), cb);
};
// my middleware that run on all API requests for a non Meteor client
export const identifyUserIfPossible = (req, res, next) => {
const token = req.headers.authorization;
if (!token) {
return next();
}
const user = Users.findOne({ tokens: token });
if (!user) {
return next();
}
loginAs(user._id, () => {
next();
// Now Meteor.userId() === user._id from all calls made on that request
// So you can do Meteor.call('someMethod') as you'd do on a full Meteor stack
});
};
Asking your customers to embed your code like this doesn't follow the principles of Security by Design.
From their point of view, you are asking them to embed your prebundled code into their website, exposing their site up to any hidden security risks (inadvertent or deliberately malicious) that exist in your code which would have unrestricted access to their website's DOM, localstorage, etc.
This is why using an iframe is the prefered method to embed third party content in a website, as that content is sandboxed from the rest of it's host site.
Further, following the security principle of 'Least Privilege' they (with your guidance/examples) can set the sandbox attribute on the iframe, and explicitly lockdown via a whitelist the privileges the widget will have.
Loading your widget in an iframe will also give you more flexibility in how it communicates with your servers. This could now be a normal meteor client, using meteor's ddp to communicate with your servers. Your other suggestions are also possible.
User auth/identification depends on the details of your system. This could range from using Meteor Accounts which would give you either password or social auth solutions. Or you could try an anonymous accounts solution such as artwells:accounts-guest.
html5rocks article on sandboxed-iframes

Categories

Resources