Gathering detailed insights and metrics for larapassport-spa-js
Gathering detailed insights and metrics for larapassport-spa-js
Gathering detailed insights and metrics for larapassport-spa-js
Gathering detailed insights and metrics for larapassport-spa-js
npm install larapassport-spa-js
Typescript
Module System
Node Version
NPM Version
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
10
35
Laravel Passport SDK for Single Page Applications using Authorization Code Grant Flow with PKCE.
This package has been inspired by @auth0/auth0-spa-js and laravel-passport-spa-js.
Using npm:
1npm install larapassport-spa-js
You need a working authentication server which is up and running (e.g.: http://localhost:8000).
Follow the official documention's steps to create a client.
Make sure that you have a public Passport client with the correct callback URL. The callback URL should reflect the origins that your SPA application is running on. The URL may also include a path, depending on where you're handling the callback (e.g.: http://localhost:3000/callback).
Also, make sure the CORS are set properly.
Take note of the Client ID value. You'll need this values in the next step.
Create an AuthClient
instance before rendering or initializing your application. You should only have one instance of the client.
1import createAuthClient from 'larapassport-spa-js'; 2 3//with async/await 4const authClient = await createAuthClient({ 5 domain: '<LARAVEL_PASSPORT_DOMAIN>', 6 client_id: '<LARAVEL_PASSPORT_CLIENT_ID>', 7 redirect_uri: '<MY_CALLBACK_URL>' 8}); 9 10//with promises 11createAuthClient({ 12 domain: '<LARAVEL_PASSPORT_DOMAIN>', 13 client_id: '<LARAVEL_PASSPORT_CLIENT_ID>', 14 redirect_uri: '<MY_CALLBACK_URL>' 15}).then(authClient => { 16 //... 17});
Using createAuthClient
does a couple of things automatically:
AuthClient
.getTokenSilently
to refresh the user session.getTokenSilently
, except login_required
.1//or, you can just instantiate the client on it's own 2import { AuthClient } from 'larapassport-spa-js'; 3 4const authClient = new AuthClient({ 5 domain: '<LARAVEL_PASSPORT_DOMAIN>', 6 client_id: '<LARAVEL_PASSPORT_CLIENT_ID>', 7 redirect_uri: '<MY_CALLBACK_URL>' 8});
You can also create the client directly using the AuthClient
constructor. This can be useful if:
getTokenSilently
on initialization.Make sure that your authentication server should have a login and logout web page. For that, you can use its Breeze package.
1<button id="login">Click to Login</button>
1//with async/await
2
3//redirect to the Login page
4document.getElementById('login').addEventListener('click', async () => {
5 await authClient.loginWithRedirect({
6 redirect_uri: '<MY_CALLBACK_URL>'
7 appState: '<a relative SPA path where you want to return to after login>'
8 });
9});
The appState
is an optional parameter.
When the browser is redirected from Authentication server back to your SPA, handleRedirectCallback
must be called in order to complete the login flow.
1//in your callback route (<MY_CALLBACK_URL>) 2window.addEventListener('load', async () => { 3 const redirectResult = await authClient.handleRedirectCallback(); 4 //logged in. you can get the user profile like this: 5 const user = await authClient.getUser(); 6 console.log(user); 7}); 8 9//with promises 10 11//redirect to the Login page 12document.getElementById('login').addEventListener('click', () => { 13 authClient.loginWithRedirect().catch(() => { 14 //error while redirecting the user 15 }); 16}); 17 18//in your callback route (<MY_CALLBACK_URL>) 19window.addEventListener('load', () => { 20 authClient.handleRedirectCallback().then(redirectResult => { 21 //logged in. you can get the user profile like this: 22 authClient.getUser().then(user => { 23 console.log(user); 24 }); 25 }); 26});
1<button id="call-api">Call an API</button>
1//with async/await 2document.getElementById('call-api').addEventListener('click', async () => { 3 const tokenResult = await authClient.getTokenSilently(); 4 const result = await fetch('https://your.api.authentication.server.example.com', { 5 method: 'GET', 6 headers: { 7 Accept: 'application/json', 8 Authorization: `Bearer ${tokenResult.access_token}` 9 } 10 }); 11 const data = await result.json(); 12 console.log(data); 13}); 14 15//with promises 16document.getElementById('call-api').addEventListener('click', () => { 17 authClient 18 .getTokenSilently() 19 .then(tokenResult => 20 fetch('https://your.api.authentication.server.example.com', { 21 method: 'GET', 22 headers: { 23 Accept: 'application/json', 24 Authorization: `Bearer ${tokenResult.access_token}` 25 } 26 }) 27 ) 28 .then(result => result.json()) 29 .then(data => { 30 console.log(data); 31 }); 32});
Make sure that you have a logout route in your authentication server which accepts GET method calls.
1<button id="logout">Logout</button>
1import createAuthClient from 'larapassport-spa-js'; 2 3document.getElementById('logout').addEventListener('click', () => { 4 authClient.logout(); 5});
You can redirect users back to your app after logging out. This logic must be implemented in your authentication server's logout method that handles a returnTo
parameter.
1authClient.logout({ 2 returnTo: 'https://your.spa.url.example.com/' 3});
You can revoke all access tokens and refresh tokens which belong to the Client ID. For that, you need to pass an allDevices
paramater:
1authClient.logout({ 2 allDevices: true 3});
The SDK can be configured to cache ID tokens and access tokens either in memory or in local storage. The default is in memory. This setting can be controlled using the cacheLocation
option when creating the AuthClient.
To use the in-memory mode, no additional options need are required as this is the default setting. To configure the SDK to cache data using local storage, set cacheLocation
as follows:
1await createAuthClient({ 2 domain: '<LARAVEL_PASSPORT_DOMAIN>', 3 client_id: '<LARAVEL_PASSPORT_CLIENT_ID>', 4 redirect_uri: '<MY_CALLBACK_URL>', 5 cacheLocation: 'localstorage' // valid values are: 'memory' or 'localstorage' 6});
Important: This feature will allow the caching of data **such as access tokens and refresh tokens ** to be stored in local storage. Exercising this option changes the security characteristics of your application and should not be used lightly. Extra care should be taken to mitigate against XSS attacks and minimize the risk of tokens being stolen from local storage.
Advanced options can be set by specifying the advancedOptions
property when configuring AuthClient
.
1createAuthClient({
2 domain: '<LARAVEL_PASSPORT_DOMAIN>',
3 client_id: '<LARAVEL_PASSPORT_CLIENT_ID>',
4 advancedOptions: {
5 defaultScope: 'foo' // change the scopes that are applied to every authz request.
6 }
7});
When you create the AuthClient
instance, you can pass several options. Some are required, others are optional and come with default value if not specified.
1const authClientOptions = { 2 /** 3 * REQUIRED 4 * Your Laravel Passport authentication domain url such as `'your.api.authentication.server.com'`. 5 */ 6 domain: string; 7 8 /** 9 * REQUIRED 10 * The Client ID from the Laravel Passport server. 11 */ 12 client_id: string; 13 14 /** 15 * REQUIRED 16 * The default URL where Laravel Passport will redirect your browser to with the 17 * authentication result. 18 */ 19 redirect_uri: string; 20 21 /** 22 * The default scope to be used on authentication requests. 23 * Defaults to '' (empty string). 24 */ 25 scope: string; 26 27 /** 28 * Number of days until the cookie laravelPassport.is.authenticated will expire. 29 * Defaults to 1. 30 */ 31 sessionCheckExpiryDays: number; 32 33 /** 34 * If true, the SDK will use a cookie when storing information about the auth 35 * transaction while the user is going through the authentication flow on the 36 * authorization server. The default is `false`, in which case the SDK will use 37 * session storage. 38 * Defaults to `false`. 39 */ 40 useCookiesForTransactions: boolean; 41}; 42 43const authClient = await createAuthClient(authClientOptions);
1$('#getToken').click(async () => { 2 const token = await authClient.getTokenSilently(); 3});
1$('#getUser').click(async () => { 2 const user = await authClient.getUser(); 3});
For support or to provide feedback, please raise an issue on the GitHub page.
This project is licensed under the MIT license. See the LICENSE file for more info.
No vulnerabilities found.
No security vulnerabilities found.