I have a site with web components based architecture, where each web component may be a separate Vue app with it's own API layer integrated via Axios. I need to implement Auth middleware for all HTTP requests, coming from either root app or web component app. I cannot use Axios built-in interceptors mechanism as there will be multiple instances of Axios. Is there a way I can do it with global JS methods? I know there is some browser extension based API out there, but that doesn't seem like something I am looking for.
Just in case anybody else is interested, I have solved it with service worker. You can subscribe to fetch events and respond according to your auth logics. Your service worker code will look something like following:
self.addEventListener('fetch', async (event) => {
const isAuthorised = await checkIsAuthorized(); // your auth API layer
if (!isAuthorised) {
const response = new Response(null, {
status: 401,
statusText: 'Unauthorised',
});
event.respondWith(response);
return;
}
event.respondWith(fetch(event.request));
});
Service worker is able to intercept axios requests from shadow DOM as well, so it's a good match for web components case.
Besides, there is a nice article by Bartosz Polnik on implementing auth layer using service worker.
Related
I'm attempting to create some route guarding using the new Next.Js 12 middleware feature. My authentication is based on a JWT token set on a cookie. I had previously implemented this using the API backend on Next.Js with no issues, and still when hitting the API routes the cookie will persist on the request no problem.
My issue appears when it will request a static page from the server. No cookies are attached so I can not determine if a User is authenticated and always redirect to a log in page. So for example the request to http://localhost:3000/ (Homepage) will not send any cookies to the middleware. But, http://localhost:3000/api/user will send a cookie to the middleware. Is there a setting I have missed in the documentation to allow this to happen?
Not sure if at all helpful but here is my _middleware.ts file that sits on the root of the pages.
import type { NextFetchEvent, NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
const middleware = (req: NextRequest, ev: NextFetchEvent) => {
console.log(req.cookies);
console.log(req.cookies['user']);
console.log(req.nextUrl.pathname);
if (req.nextUrl.pathname === '/') {
return NextResponse.redirect('http://localhost:3000/login');
}
};
export default middleware;
Next.js > 12.2
req.cookies.get("user")
Before Next.js 12.2,
req.cookies?.user
I had a same problem. I use tag for routing and it works but im not sure that it is a good choice.
I'm hoping someone can tell me if I'm barking up the wrong tree. I have built a basic web app using Vue CLI and included the PWA support. Everything seems to work fine, I get the install prompt etc.
What I want to do, is cache various pages (routes) that user hasn't visited before, but so that they can when offline.
The reason here is that I'm planning to build an app for an airline and part of that app will act as an in flight magazine, allowing users to read various articles, however the aircrafts do not have wifi so the users need to download the app in the boarding area and my goal is to then pre cache say the top 10 articles so they can read them during the flight.
Is this possible? and is PWA caching the right way to go about it? Has anyone does this sort of thing before?
Thanks in advance
To "convert" your website to an PWA, you just need few steps.
You need to know that the service worker is not running on the main thread and you cant access for example the DOM inside him.
First create an serviceworker.
For example, go to your root directory of your project and add a javascript file called serviceworker.js this will be your service worker.
Register the service worker.
To register the service worker, you will need to check if its even possible in this browser, and then register him:
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/serviceworker.js').then(function(registration) {
// Registration was successful
console.log('ServiceWorker registration successful with scope');
}, function(err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
});
}
In vue.js you can put this inside mounted() or created() hook.
If you would run this code it will say that the service worker is successfully registered even if we havent wrote any code inside serviceworker.js
The fetch handler
Inside of serviceworker.js its good to create a variable for example CACHE_NAME. This will be the name of your cache where the cached content will be saved at.
var CACHE_NAME = "mycache_v1";
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.open(CACHE_NAME).then(function(cache) {
return cache.match(event.request).then(function (response) {
return response || fetch(event.request).then(function(response) {
cache.put(event.request, response.clone());
return response;
});
});
})
);
});
Everytime you make a network request your request runs through the service worker fetch handler here first. You need to response with event.respondWith()
Next step is you first open your cache called mycache_v1 and take a look inside if there is a match with your request.
Remember: cache.match() wont get rejected if there is no match, it just returns undefined because of that there is a || operator at the return statement.
If there is a match available return the match out of the cache, if not then fetch() the event request.
In the fetch() you save the response inside the cache AND return the response to the user.
This is called cache-first approach because you first take a look inside the cache and in case there is no match you make a fallback to the network.
Actually you could go a step further by adding a catch() at your fetch like this:
return response || fetch(event.request).then(function(response) {
cache.put(event.request, response.clone());
return response;
})
.catch(err => {
return fetch("/offline.html")
});
In case there is nothing inside the cache AND you also have no network error you could response with a offline page.
You ask yourself maybe: "Ok, no cache available and no internet, how is the user supposed to see the offline page, it requires internet connection too to see it right?"
In case of that you can pre-cache some pages.
First you create a array with routes that you want to cache:
var PRE_CACHE = ["/offline.html"];
In our case its just the offline.html page. You are able to add css and js files aswell.
Now you need the install handler:
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
return cache.addAll(PRE_CACHE);
})
);
});
The install is just called 1x whenever a service worker gets registered.
This just means: Open your cache, add the routes inside the cache. Now if you register you SW your offline.html is pre-cached.
I suggest to read the "Web fundamentals" from the google guys: https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook
There are other strategies like: network-first
To be honest i dont know exactly how the routing works with SPAs because SPA is just 1 index.html file that is shipped to the client and the routing is handled by javascript you will need to check it out witch is the best strategie for your app.
Beeing new to vue testing, I'm trying to make an integration test for our Vue SPA with axios & mocha.
I want some of the tests to make real api calls to our server without mocking, to figure out if it really works from the beginning to the end. The server API is a Laravel 7 app with laravel/sanctum and cookie based session authentication.
I can make real axios calls directly in the test file like this:
import authApi from '../../src/components/connections/auth';
describe('AxiosCallTest', () => {
it('makes an axios call', function(done) {
this.timeout(5000);
authApi.get('/sanctum/csrf-cookie').then((response) => {
console.log('response: ', JSON.stringify(response));
done();
}).catch(() => {
done();
});
});
});
// -> response: {"data":"","status":204,"statusText":"No Content","headers":{"cache-control":"no-cache, private"},"config":{"url":"/sanctum/csrf-cookie","method":"get","headers":{"Accept":"application/json","X-Requested-With":"XMLHttpRequest"},"baseURL":"http://testing.backend.vipany.test/api/auth","transformRequest":[null],"transformResponse":[null],"timeout":30000,"withCredentials":true,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1,"axios-retry":{"retryCount":0,"lastRequestTime":1591774391768}},"request":{"upload":{"_ownerDocument":{"location":{"href":"http://localhost/","origin":"http://localhost","protocol":"http:","host":"localhost","hostname":"localhost","port":"","pathname":"/","search":"","hash":""}}},"_registeredHandlers":{},"_eventHandlers":{}}}
I've read and tried a lot and now have 2 problems:
handling cookies for CSRF Token Cookies and Session Cookies (used for authentication), as on conventional requests the browser handles this out of the box.
waiting on axios calls in vue components, as I can't use mocha's done() function in the components itself, as I did in this example. I can only find examples with mocking requests with moxios or similiar. But I don't want to mock the axios calls.
Does anyone know a good article about these issues or has already solved it?
Thanks a lot
update:
I've found an article to get the cookie out of the axios request and tried it myself to get the X-XSRF-TOKEN out of the response (I've checked it in the browser: HttpOnly: false, secure: false), but it does not work:
console.log('response X-XSRF-TOKEN: ', response.config.headers['X-XSRF-TOKEN']);
// -> undefined
Found out that cypress and nightwatch are the right tools for end-to-end testing (e2).
Didn't know the right terms (e2e or end-to-end testing) and the right tools.
Switched to cypress.io - absolutly great.
vue-cli even has first hand plugins to integrate cypress or nightwatch: https://cli.vuejs.org/core-plugins/e2e-cypress.html
We have a vue firebase service worker that needs to call back to the main vue app. According to my research you can do this with the postMessage() function like so:
// firebase-messaging-sw.js
addEventListener('fetch', event => {
event.waitUntil(
(async function() {
// Exit early if we don't have access to the client.
// Eg, if it's cross-origin.
if (!event.clientId) return
// Get the client.
const client = await clients.get(event.clientId)
// Exit early if we don't get the client.
// Eg, if it closed.
if (!client) return
// Send a message to the client.
client.postMessage({
msg: 'Hey I just got a fetch from you!',
url: event.request.url
})
})()
)
})
You handle the message in the main app so:
// main.js
navigator.serviceWorker.addEventListener('message', event => {
console.log('Url', event.data.url)
console.log('msg', event.data.msg)
})
The problem is that postMessage() needs to be called on a client object and you get the client object on the fetch event, but vue does not seem to fetch anything as it is a single page application.
So how can I get the client?
and how do I message the main app?
The client does not need to make a fetch request in order to allow the Service Worker to communicate with it. You can use the Clients API inside the Service Worker. You can also initiate a completely separate postMessage message from the client in the beginning after the app has started.
Clients API: https://developer.mozilla.org/en-US/docs/Web/API/Clients
I also suggest you check out this example: https://serviceworke.rs/message-relay.html
I am struggling with finding answer for where to ideally put API calls in vue modules. I am not building an SPA. For example my auth block has several components for login, password reset, account verifiction etc. Each block uses axios for API calls. Axios already provides promises, which are async.
The question is about the best pracitces. Do API calls belong in a Vuex actions? Are there any pros/cons of such approach?
Is there any drawback of keeping axios calls within the components they belong to?
I do API calls in services, not Vuex or components. Basically, mixing the API calls in with the store code is a bit too multi-responsibility, and components should be about providing for the view not fetching data.
As an example of a simple service (using Vue.http but same for an Axios call),
FileService .js
import Vue from 'vue'
export default {
getFileList () {
return Vue.http.get('filelist.txt')
.then(response => {
// massage the response here
return filelist;
})
.catch(err => console.error('getFileList() failed', err) )
},
}
I use it in another service as below (the number of layers is up to you).
Note, the outer service is checking the store to see if the fetch already happened.
DataService.js
import FileService from './file.service'
checkFiles (page) {
const files = store.state.pages.files[page]
if (!files || !files.length) {
return store.dispatch('waitForFetch', {
resource: 'files/' + page,
fetch: () => FileService.getFileList(),
})
} else {
return Promise.resolve() // eslint-disable-line no-undef
}
},
waitForFetch is an action that invokes the fetch function passed in to it (as provided by FileService). It basically provides wrapper services to the fetch, like timeout and dispatching success and failure actions depending on the outcome.
The component never knows about the API result (although it may initiate it), it just waits on data to appear in the store.
As for drawback of just calling the API in the component, it depends on testability, app complexity. and team size.
Testability - can mock out a service in unit tests.
App complexity - can handle timeout / success / failure orthogonally to the API call.
Team size - bigger teams, dividing up the task into smaller bites.