I am a full stack web developer, I go throw many different problems. Today I am going to explain the one problem toughest problem and how to tackle it in the simple and fastest way for Frontend Developer mostly, If you are a backend developer this is may one quick glance article for you.
I will Explain the authentication with Nodejs, Express, Auth0, and deployment with Heroku and Netlify with all free tier plan.
$ sign denotes the terminal command
# sign denotes the task to preform
Just-Learning-by-doing follow the steps
This is going to be the long article I think But, I will try to explain in depth in some areas and short tas well as Possible. I will make Index in End of the article if needed
# Lets Open Terminal to start the process and enter the command as below:
$ mkdir Serverless
$ cd Serverless
we created a Folder named Serverless
The Serverless folder is the main folder that will Contain Client and Server Folder Separately.
We Will Start From Creating Client-Side Project: Enter the command to init Vue CLI to create a client in terminal:-
$ vue create client
# Manually select features
Vue CLI v4.5.6? Please pick a preset:Default ([Vue 2] babel, eslint)Default (Vue 3 Preview) ([Vue 3] babel, eslint)❯ Manually select features
# Select Babel, Router, Vuex, Linter/Formater
Vue CLI v4.5.6? Please pick a preset: Manually select features? Check the features needed for your project:❯◉ Choose Vue version◉ Babel◯ TypeScript◯ Progressive Web App (PWA) Support◉ Router◉ Vuex◯ CSS Pre-processors◉ Linter / Formatter◯ Unit Testing◯ E2E Testing
# As I Choose Vue2 I will Stick to Vue 2, for now, feel free to use Vue 3
Vue CLI v4.5.6? Please pick a preset: Manually select features? Check the features needed for your project: Choose Vue version, Babel, Router,Vuex, Linter? Choose a version of Vue.js that you want to start the project with (Use arrowkeys)❯ 2.x3.x (Preview)
# N
Vue CLI v4.5.6? Please pick a preset: Manually select features? Check the features needed for your project: Choose Vue version, Babel, Router,Vuex, Linter? Choose a version of Vue.js that you want to start the project with 2.x? Use history mode for router? (Requires proper server setup for index fallbackin production) (Y/n) n
# ESLint with error prevention only
Vue CLI v4.5.6? Please pick a preset: Manually select features? Check the features needed for your project: Choose Vue version, Babel, Router,Vuex, Linter? Choose a version of Vue.js that you want to start the project with 2.x? Use history mode for router? (Requires proper server setup for index fallbackin production) No? Pick a linter / formatter config: (Use arrow keys)❯ ESLint with error prevention onlyESLint + Airbnb configESLint + Standard configESLint + Prettier
# Lint on save
Vue CLI v4.5.6? Please pick a preset: Manually select features? Check the features needed for your project: Choose Vue version, Babel, Router,Vuex, Linter? Choose a version of Vue.js that you want to start the project with 2.x? Use history mode for router? (Requires proper server setup for index fallbackin production) No? Pick a linter / formatter config: Basic? Pick additional lint features: (Press <space> to select, <a> to toggle all, <i> to invert selection)◉ Lint on save❯◯ Lint and fix on commit
# In dedicated config files
Vue CLI v4.5.6? Please pick a preset: Manually select features? Check the features needed for your project: Choose Vue version, Babel, Router,Vuex, Linter? Choose a version of Vue.js that you want to start the project with 2.x? Use history mode for router? (Requires proper server setup for index fallbackin production) No? Pick a linter / formatter config: Basic? Pick additional lint features: Lint on save? Where do you prefer placing config for Babel, ESLint, etc.? (Use arrow keys)❯ In dedicated config filesIn package.json
# N
Vue CLI v4.5.6? Please pick a preset: Manually select features? Check the features needed for your project: Choose Vue version, Babel, Router,Vuex, Linter? Choose a version of Vue.js that you want to start the project with 2.x? Use history mode for router? (Requires proper server setup for index fallbackin production) No? Pick a linter / formatter config: Basic? Pick additional lint features: Lint on save? Where do you prefer placing config for Babel, ESLint, etc.? In dedicated config files? Save this as a preset for future projects? (y/N) N
Vue CLI v4.5.6✨ Creating project in /Users/csangale/Desktop/Serverlesslogin/client.🗃 Initializing git repository…⚙️ Installing CLI plugins. This might take a while…..setting up Git hooksdone...🚀 Invoking generators…📦 Installing additional dependencies…...⚓ Running completion hooks…📄 Generating README.md…🎉 Successfully created project client.👉 Get started with the following commands:$ cd client$ npm run serveApp running at:- Local: http://localhost:8080/- Network: …Note that the development build is not optimized.To create a production build, run npm run build.
Check it out here: http://localhost:8080
Tip: Then ctrl + c to Stop
Open it in your fav Code Editor (i will be recommended VSCode) &
Check the folderStructure for better understanding…
# Delete these files :
Serverlesslogin/Client/src/components/HelloWorld.vueServerlesslogin/Client/src/assets/logo.pngServerlesslogin/Client/src/views/About.vue
Add This Code to
Serverlesslogin/Client/src/views/Home.vue<template><div class=”home”></div></template><script>export default {name: ‘home’,components: {}}</script>
Run in terminal
$ npm run serve
Check it out here: http://localhost:8080
Tip: You must always have a parent <div> element that encloses the rest of the HTML after the template tag.
We now install bootstrap for design: Run cmd in terminal
$ npm install bootstrap —- save
# open main.js
main.js is the entry point for the Application open main.js file in the editor
Serverlesslogin/Client/src/main.js
now Import bootstrap in main.js: Add this code to import bootstrap in main.js
import Vue from ‘vue’;import App from ‘./App.vue’;import router from ‘./router’;import store from ‘./store’;import ‘bootstrap/dist/css/bootstrap.min.css’;Vue.config.productionTip = false;new Vue({router,store,render: (h) => h(App),}).$mount(‘#app’);
now goto Home.vue file at
Serverlesslogin/Client/src/views/Home.vue
and add this code for a bootstrap template
<template><div class=”jumbotron”><h1>Username</h1><p>This is Serverless login demo template with Auth0, Vue, Express, Node</p><p><router-link class=”btn btn-primary” role=”button” to=”/dashboard”>Goto Dashboard</router-link></p></div></template><script>export default {name: “home”};</script>
In Router/index.js for navigation to work we need to add code
Serverlesslogin/Client/src/router/index.js
This will make the navigation work
import Vue from ‘vue’;import VueRouter from ‘vue-router’;import Home from ‘../views/Home.vue’;import Dashboard from ‘../views/Dashboard.vue’;Vue.use(VueRouter);const routes = [{path: ‘/’,name: ‘Home’,component: Home,},{path: ‘/dashboard’,name: ‘dashboard’,component: Dashboard,},];const router = new VueRouter({mode: ‘history’,routes,});export default router;
Tip: mode: ‘history’, will remove the # sign in Vue URL
# Dashboard.vue
Serverlesslogin/Client/src/views/Dashboard.vue
This file will be secure in the login process, i.e only login/authenticated user can open this file
<template><div class=”jumbotron”><h1>Username</h1><p>{{description}}</p><p><router-link class=”btn btn-primary” role=”button” to=”/”>Goto Home</router-link></p><p>{{info}}</p><p>{{email}}</p></div></template><script>export default {name: “dashboard”,data: () => {return {info: “Demo Information”,email: “serverlesss@demo.com”,description: “This is Backend Information Secure”};}};</script>
Now the template is created for the initial process. We will go to auth0.com and create the account.
Check the auth0.com for better understanding see you soon
## auth0
# login in auth0.com
after login
at https://manage.auth0.com/dashboard
# goto on left side applications then press big orange button CREATE APPLICATION on right side
# Select- Single Page Web Applications
# Give name: Vue CDS | or give any name you like
Then click the Create button
after then goto setting tab next
# enter the code in the following fields:
Allowed Callback URLs :
http://localhost:8080/dashboard
Allowed Logout URLs:
http://localhost:8080
Allowed Web Origins:
http://localhost:8080
save changes with the blue button below.
we will come back to at https://manage.auth0.com/dashboard after few steps…
#Install Auth0 SPA package
open the terminal again and enter the command as instructed
$npm install @auth0/auth0-spa-js
ow we will create wrapper foe authentication
create a new folder & index.js file as:
Serverless/Client/src/auth
Serverless/Client/src/auth/index.js
$ mkdir auth
$ cd auth
$ touch index.js
Serverless/Client/src/auth/index.js
#add this code in index.js
import Vue from "vue";import createAuth0Client from "@auth0/auth0-spa-js";/** Define a default action to perform after authentication */const DEFAULT_REDIRECT_CALLBACK = () =>window.history.replaceState({}, document.title, window.location.pathname);let instance;/** Returns the current instance of the SDK */export const getInstance = () => instance;/** Creates an instance of the Auth0 SDK. If one has already been created, it returns that instance */export const useAuth0 = ({onRedirectCallback = DEFAULT_REDIRECT_CALLBACK,redirectUri = window.location.origin,...options}) => {if (instance) return instance;// The 'instance' is simply a Vue objectinstance = new Vue({data() {return {loading: true,isAuthenticated: false,user: {},auth0Client: null,popupOpen: false,error: null};},methods: {/** Authenticates the user using a popup window */async loginWithPopup(o) {this.popupOpen = true;try {await this.auth0Client.loginWithPopup(o);} catch (e) {// eslint-disable-next-lineconsole.error(e);} finally {this.popupOpen = false;}this.user = await this.auth0Client.getUser();this.isAuthenticated = true;},/** Handles the callback when logging in using a redirect */async handleRedirectCallback() {this.loading = true;try {await this.auth0Client.handleRedirectCallback();this.user = await this.auth0Client.getUser();this.isAuthenticated = true;} catch (e) {this.error = e;} finally {this.loading = false;}},/** Authenticates the user using the redirect method */loginWithRedirect(o) {return this.auth0Client.loginWithRedirect(o);},/** Returns all the claims present in the ID token */getIdTokenClaims(o) {return this.auth0Client.getIdTokenClaims(o);},/** Returns the access token. If the token is invalid or missing, a new one is retrieved */getTokenSilently(o) {return this.auth0Client.getTokenSilently(o);},/** Gets the access token using a popup window */getTokenWithPopup(o) {return this.auth0Client.getTokenWithPopup(o);},/** Logs the user out and removes their session on the authorization server */logout(o) {return this.auth0Client.logout(o);}},/** Use this lifecycle method to instantiate the SDK client */async created() {// Create a new instance of the SDK client using members of the given options objectthis.auth0Client = await createAuth0Client({domain: options.domain,client_id: options.clientId,audience: options.audience,redirect_uri: redirectUri});try {// If the user is returning to the app after authentication..if (window.location.search.includes("code=") &&window.location.search.includes("state=")) {// handle the redirect and retrieve tokensconst { appState } = await this.auth0Client.handleRedirectCallback();// Notify subscribers that the redirect callback has happened, passing the appState// (useful for retrieving any pre-authentication state)onRedirectCallback(appState);}} catch (e) {this.error = e;} finally {// Initialize the internal authentication statethis.isAuthenticated = await this.auth0Client.isAuthenticated();this.user = await this.auth0Client.getUser();this.loading = false;}}});return instance;};// Create a simple Vue plugin to expose the wrapper object throughout the applicationexport const Auth0Plugin = {install(Vue, options) {Vue.prototype.$auth = useAuth0(options);}};
now we add some secure information for auth0-spa-js
#create auth_config.json
Serverless/Client/auth_config.json
add this code
{"domain": "your-domain.auth0.com","clientId": "yourclientid"}
To Find your auth_config values:
goto auth0-dashboard https://manage.auth0.com/dashboard
goto application select application “Vue CDS” or name you gave before
copy/paste the values for ‘Client ID’ and ‘Domain’ in auth_config.json File
*make sure to add auth0_config.json file to .gitignore
#then open main.js
import the auth_config.json and Auth0Plugin to main.js
import Vue from 'vue';import App from './App.vue';import router from './router';import store from './store';import 'bootstrap/dist/css/bootstrap.min.css';// Import the Auth0 configurationimport { domain, clientId } from '../auth_config.json';// Import the plugin hereimport { Auth0Plugin } from './auth';// Install the authentication plugin hereVue.use(Auth0Plugin, {domain,clientId,onRedirectCallback: (appState) => {router.push(appState && appState.targetUrl? appState.targetUrl: window.location.pathname);},});Vue.config.productionTip = false;new Vue({router,store,render: (h) => h(App),}).$mount('#app');
Now we will add a login button in the navbar which will actually work
# open
Serverless/Client/src/components/Navbar.vue
add this code again merge it in
<template><div class="cover-container d-flex w-100 h-100 p-3 mx-auto flex-column"><header class="header mb-auto"><nav class="navbar navbar-light navbar-expand"><div class="container-fluid"><a class="navbar-brand" href="#">Severless</a><buttondata-toggle="collapse"class="navbar-toggler"data-target="#navcol-1"><span class="sr-only">Toggle navigation</span><span class="navbar-toggler-icon"></span></button><div class="collapse navbar-collapse" id="navcol-1"><ulclass="nav navbar-nav border rounded d-flex flex-fill justify-content-center justify-content-md-end"><router-link class="nav-link" to="/">Home</router-link><router-link class="nav-link" to="/dashboard">Dashboard</router-link><!-- Check that the SDK client is not currently loading before accessing is methods --><div v-if="!$auth.loading"><!-- show login when not authenticated --><a v-if="!$auth.isAuthenticated" @click="login" class="nav-link">Login</a><a v-if="$auth.isAuthenticated" @click="logout" class="nav-link">Logout</a></div></ul></div></div></nav></header></div></template>
<script>export default {name: 'Nav',methods: {// Log the user inlogin() {this.$auth.loginWithRedirect();},// Log the user outlogout() {this.$auth.logout({returnTo: window.location.origin});}}}</script>
now try to login
*change the callback URL in the auth0 dashboard to
http://localhost:8080 from http://localhost:8080/dashboard
Accessing user information
Auth0 lets you access the information of the logged-in user in your templates with the following:
{{ $auth.user }}
# change the folling code to see in action
Serverless/Client/src/views/Home.vue
<template><div class=”jumbotron”><h1 v-if=”$auth.isAuthenticated”>Username: {{ $auth.user.name }}</h1><p>This is Serverless login demo template with Auth0, Vue, Express, Node</p><p><router-link class=”btn btn-primary” role=”button” to=”/dashboard”>Goto Dashboard</router-link></p></div></template><script>export default {name: ‘home’,};</script>
and in
src/views/Dashboard.vue
<template><div class=”jumbotron”><h1 v-if=”$auth.isAuthenticated”>Username: {{ $auth.user.name }}</h1><p>{{ description }}</p><p><router-link class=”btn btn-primary” role=”button” to=”/”>Goto Home</router-link></p><p>{{ info }}</p><p>{{ email }}</p></div></template><script>export default {name: ‘dashboard’,data: () => {return {info: ‘Demo Information’,email: ‘serverlesss@demo.com’,description: ‘This is Backend Information Secure’,};},};</script>
The next step is to install a Route Guard so get ready for action
Set up a Route Guard
We are now not going to create a backend, we will create the frontend first then switch to backend when all things will be at the place in frontend. In the Backend setup, we will come back and fix a few things like secured the data and call the information from the backend server. For now, follow the steps as instructed
# Create new file authGuard.js File in
Serverless/Client/src/auth/authGuard.js
and add the following code
import { getInstance } from "./index";export const authGuard = (to, from, next) => {const authService = getInstance();const fn = () => {// If the user is authenticated, continue with the routeif (authService.isAuthenticated) {return next();}// Otherwise, log inauthService.loginWithRedirect({ appState: { targetUrl: to.fullPath } });};// If loading has already finished, check the auth state using `fn()`if (!authService.loading) {return fn();}// Watch for the loading property to change before checking isAuthenticatedauthService.$watch("loading", loading => {if (loading === false) {return fn();}});};
This will use for a call next() or redirect the user this will help in guard the route
# open the index.js File in the router folder
Serverless/Client/src/router/index.js
# & add the following code
mport Vue from 'vue';import VueRouter from 'vue-router';import Home from '../views/Home.vue';import Dashboard from '../views/Dashboard.vue';import { authGuard } from '../auth/authGuard';Vue.use(VueRouter);const routes = [{path: '/',name: 'Home',component: Home,},{path: '/dashboard',name: 'dashboard',component: Dashboard,beforeEnter: authGuard,},];const router = new VueRouter({mode: 'history',routes,});export default router;
Logout first if you are logged in and try to access the dashboard via route or clicking the nav or button you will redirect to the login page, once you are login then you will have access to the dashboard
…but the data is still accessible to any user. I will show below step
right-click and select the View Page Source to open the app.js file at
http://localhost:8080/js/app.js
and find/search for “ This is Backend Information Secure ”
this information is still accessible to any user (login/logout user)
If we need to secure that information we need to store that information on the backend securely. Which we will do in the backend part next
we till now had install Vue 2 CLI, added bootstrap for design, setup auth0, added auth guards for redirection to the login page.
Start backend Authentication setup
Now you had almost created the Vue app for client-side frontend
#now goto Serverless folder
#and create the Server Folder
Serverless/Server
open the server folder in terminal
$ npm init -y
that will fastforword the npm process as our article is already got longer then it should be
$ npm install body-parser cors express nodemon
added the nodemon script included in the following code:
{"name": "server","version": "1.0.0","description": "","main": "index.js","scripts": {"start": "nodemon server.js","test": "echo \"Error: no test specified\" && exit 1"},"keywords": [],"author": "","license": "ISC","dependencies": {"body-parser": "^1.19.0","cors": "^2.8.5","express": "^4.17.1","nodemon": "^2.0.4"}}
# open the Serverless/Server in Editor
# create the server.js
Serverless/Server/server.js
# and paste the code in that file
const express = require('express');const bodyParser = require('body-parser');const cors = require('cors');const app = express();const port = 8000;app.use(bodyParser.json());app.use(cors());app.use(express.urlencoded({ extended: true }));app.get('/', (req, res) => {res.send(`Hi! Server is listening on port ${port}`);});// listen on the portapp.listen(port);
#now
$ npm start
now nodemon server will start at : http://localhost:8000
Tip: ctrl + c to stop the nodemon server
Now to create the secure server-side API login in auth0 & go to auth0 dashboard: https://manage.auth0.com
#select the APIs on left side
# Now click on Create API orange button
Add information as below:
Name:
Vue CDS API
Identifier:
*A logical identifier for this API. We recommend using a URL but note that this doesn’t have to be a publicly available URL, Auth0 will not call your API at all. This field cannot be modified.
Signing Algorithm
RS256
# goto Serverless/Server
$ npm install express-jwt jwks-rsa
#open server.js file at Serverless/Server/server.js
const express = require('express');const bodyParser = require('body-parser');const cors = require('cors');const app = express();const port = 8000;const jwt = require('express-jwt'); // NEWconst jwksRsa = require('jwks-rsa'); // NEWapp.use(bodyParser.json());app.use(cors());app.use(express.urlencoded({ extended: true }));// NEW// Set up Auth0 configurationconst authConfig = {domain: 'YOUR_DOMAIN',audience: 'YOUR_API_IDENTIFIER',};// NEW// Create middleware to validate the JWT using express-jwtconst checkJwt = jwt({// Provide a signing key based on the key identifier in the header and the signing keys provided by your Auth0 JWKS endpoint.secret: jwksRsa.expressJwtSecret({cache: true,rateLimit: true,jwksRequestsPerMinute: 5,jwksUri: `https://${authConfig.domain}/.well-known/jwks.json`,}),// Validate the audience (Identifier) and the issuer (Domain).audience: authConfig.audience,issuer: `https://${authConfig.domain}/`,algorithms: ['RS256'],});app.get('/', (req, res) => {res.send(`Hi! Server is listening on port ${port}`);});// listen on the portapp.listen(port);
# Now modify domain, audience, Identifier inside authConfig
# open auth0 dashboard at https://manage.auth0.com/dashboard
inside APIs on the left sidebar, select the Vue CDS API (or Your given name) on Quick Start select node.js tab below to get a domain, audience, Identifier
# then and goto client-side Serverless/Client/auth_config.json and change the auth_config.json to your matching field as backend domain, clientId, audience
{"domain": "YOUR_DOMAIN","clientId": "YOUR_CLIENT_ID","audience": "YOUR_API_IDENTIFIER"}
# then open Serverless/Client/src/main.js add the audience
import Vue from 'vue';import App from './App.vue';import router from './router';import store from './store';import 'bootstrap/dist/css/bootstrap.min.css';// Import the Auth0 configurationimport { domain, clientId, audience } from '../auth_config.json';// Import the plugin hereimport { Auth0Plugin } from './auth';// Install the authentication plugin hereVue.use(Auth0Plugin, {domain,clientId,audience,onRedirectCallback: (appState) => {router.push(appState && appState.targetUrl? appState.targetUrl: window.location.pathname);},});Vue.config.productionTip = false;new Vue({router,store,render: (h) => h(App),}).$mount('#app');
Now open Serverless/Server/server.js File
we will now add fake data from the server to client-side frontend vue
and route path to access the data
const express = require('express');const bodyParser = require('body-parser');const cors = require('cors');const app = express();const port = 8000;const jwt = require('express-jwt'); // NEWconst jwksRsa = require('jwks-rsa'); // NEWapp.use(bodyParser.json());app.use(cors());app.use(express.urlencoded({ extended: true }));// NEW// Set up Auth0 configurationconst authConfig = {domain: 'YOUR_DOMAIN',audience: 'YOUR_API_IDENTIFIER',};// NEW// Create middleware to validate the JWT using express-jwtconst checkJwt = jwt({// Provide a signing key based on the key identifier in the header and the signing keys provided by your Auth0 JWKS endpoint.secret: jwksRsa.expressJwtSecret({cache: true,rateLimit: true,jwksRequestsPerMinute: 5,jwksUri: `https://${authConfig.domain}/.well-known/jwks.json`,}),// Validate the audience (Identifier) and the issuer (Domain).audience: authConfig.audience,issuer: `https://${authConfig.domain}/`,algorithms: ['RS256'],});//fake data to send to client sidelet details = [{info: 'Demo Information',email: 'serverlesss@demo.com',description: 'This is Backend Information Secure',},];// get all eventsapp.get('/details', (req, res) => {res.send(details);});app.get('/', (req, res) => {res.send(`Hi! Server is listening on port ${port}`);});// listen on the portapp.listen(port);
Start the nodemon server to test it working
$ npm run start
# goto URL: http://localhost:8000/details
# open client-side Vue app
$ npm install axios
# we will create DetailService.js file in Serverless/Client/src/Services/DetailService.js
// Serverless/Client/src/services/DetailService.jsimport axios from 'axios';export default {async getDetails() {let res = await axios.get('http://localhost:8000/details');return res.data;},};
add this code in Dashboard.vue
<template><div class="jumbotron"><h1 v-if="$auth.isAuthenticated">Username: {{ $auth.user.name }}</h1><div v-for="detail in details" :detail="detail" :key="detail.id"><p>{{ detail.description }}</p><p><router-link class="btn btn-primary" role="button" to="/">Goto Home</router-link></p><p>{{ detail.info }}</p><p>{{ detail.email }}</p></div></div></template><script>import DetailService from '@/services/DetailService.js';export default {name: 'dashboard',data() {return {detail: {},details: [],};},created() {this.getDetailsData(); // NEW - call getDetailsData() when the instance is created}, // NEWmethods: {async getDetailsData() {// NEW - Use the detailService to call the getDetails() methodDetailService.getDetails().then(((details) => {this.$set(this, 'details', details);}).bind(this));},},};</script>
open URL to test http://localhost:8080/dashboard login if not already login
Now add the Authorization token part
Goto Server Side Folder And fill the audience, domain if not already and add checkJwt middleware to get details API
const express = require('express');const bodyParser = require('body-parser');const cors = require('cors');const app = express();const port = 8000;const jwt = require('express-jwt'); // NEWconst jwksRsa = require('jwks-rsa'); // NEWapp.use(bodyParser.json());app.use(cors());app.use(express.urlencoded({ extended: true }));// NEW// Set up Auth0 configurationconst authConfig = {domain: 'YOUR_DOMAIN',audience: 'YOUR_API_IDENTIFIER',};// NEW// Create middleware to validate the JWT using express-jwtconst checkJwt = jwt({// Provide a signing key based on the key identifier in the header and the signing keys provided by your Auth0 JWKS endpoint.secret: jwksRsa.expressJwtSecret({cache: true,rateLimit: true,jwksRequestsPerMinute: 5,jwksUri: `https://${authConfig.domain}/.well-known/jwks.json`}),// Validate the audience (Identifier) and the issuer (Domain).audience: authConfig.audience,issuer: `https://${authConfig.domain}/`,algorithms: ['RS256'],});//fake data to send to client sidelet details = [{info: 'Demo Information',email: 'serverlesss@demo.com',description: 'This is Backend Information Secure',},];// get all eventsapp.get('/details', checkJwt, (req, res) => {res.send(details);});app.get('/', (req, res) => {res.send(`Hi! Server is listening on port ${port}`);});// listen on the portapp.listen(port);
# At Client Side in Serverless/Client/src/services/DetailService.js add this code
// Serverless/Client/src/services/DetailService.jsimport axios from 'axios';export default {async getDetails(accessToken) {let res = await axios.get('http://localhost:8000/details', {headers: {Authorization: `Bearer ${accessToken}`,},});return res.data;},};
# GotoServerless/Client/src/views/ Dashboard.vue js File
<template><div class="jumbotron"><h1 v-if="$auth.isAuthenticated">Username: {{ $auth.user.name }}</h1><div v-for="detail in details" :detail="detail" :key="detail.id"><p>{{ detail.description }}</p><p><router-link class="btn btn-primary" role="button" to="/">Goto Home</router-link></p><p>{{ detail.info }}</p><p>{{ detail.email }}</p></div></div></template><script>import DetailService from '@/services/DetailService.js';export default {name: 'dashboard',data() {return {detail: {},details: [],};},created() {this.getDetailsData(); // NEW - call getDetailsData() when the instance is created}, // NEWmethods: {async getDetailsData() {const accessToken = await this.$auth.getTokenSilently();// NEW - Use the detailService to call the getDetails() methodDetailService.getDetails(accessToken).then(((details) => {this.$set(this, 'details', details);}).bind(this));},},};</script>
Yeah!! That's it for now !! Your data is completely secure in the backend. Not any unauthenticated user cant able to see that data.
TO BE CONTINUE ..STAY TUNED