Authentication Plugin for Vue 3
- Auth
- axios: Used as the default http client.
- Vuex: Used to store auth
state. - Vou Router: Used to redirect between pages.
- TypeScript: Written in TypeScript, optimize for Vue + TypeScript. But, also ship ESM and Common JS version on
dist.
Install the package just like regular npm package.
npm i @gravitano/vue-auth
# OR
yarn add @gravitano/vue-authInstall the plugin to your Vue app.
// main.js
import {createApp} from 'vue';
import Auth from '@gravitano/vue-auth'; // 👈 import the plugin
import store from '~/store'
import router from '~/router'
import axios from 'axios'
const app = createApp(App);
app.use(Auth); // 👈 use the plugin
// or with custom options
// 👇
app.use(Auth, {
options, // auth options
store, // vuex store instance
axios, // axios instance
router // vue router instance
}); // 👈 use the plugin
app.mount('#app');After that, you can access the plugin via $auth global property.
<template>
<div v-if="$auth.loggedIn">Logged In as : {{ $auth.user.name }}</div>
</template>If you are using composition API, you can also access the auth object by using inject method.
import {injectAuth} from '@gravitano/vue-auth'
// user is Ref
const {user} = injectAuth()
// access the user
console.log(user)To use the auth in composition API, just import and use the useAuth function.
import {useAuth} from '@gravitano/vue-auth';
const auth = useAuth();
// OR with object destruction
const {user} = useAuth();Login the user and save token to the auth storage.
auth.login({
email: '[email protected]',
password: 'admin',
});Fetch user data from API.
const user = await auth.fetchUser();
console.log(user);Manually Set User Token.
auth.setToken(token);Manually set the user data.
const userData = {
id: 1,
name: 'Admin',
};
auth.setUser(userData);Logout the current user.
auth.logout();Force logout the current user.
auth.forceLogout();Get the current user data.
console.log(auth.user);Get the current logged in state.
console.log(auth.loggedIn);First, create auth.ts file under your src/plugins folder.
import {authOptions} from '~/config';
import store, {AppRootState} from '~/store';
import {createAuth} from '@gravitano/vue-auth';
import axios from 'axios';
import router from '~/router';
export const useAuth = () => createAuth<AppRootState>(authOptions, axios, store, router);Then, in your component, just import and use it as regular composition function. For example:
<script setup lang="ts">
import {useAuth} from '~/plugins/auth'
// destruct user object from `useAuth` function
const {user} = useAuth();
console.log(user); // <-- user data
</script>This is the default options object:
import { AuthOptions } from '@gravitano/vue-auth'
export const defaultOptions: AuthOptions = {
endpoints: {
login: {
url: '/auth/login',
method: 'post',
},
logout: {
url: '/auth/logout',
method: 'delete',
},
user: {
url: '/auth/me',
method: 'get',
},
},
token: {
property: 'data.token',
type: 'Bearer',
storageName: 'auth.token',
autoDecode: false,
name: 'Authorization',
},
user: {
autoFetch: true,
property: 'data',
storageName: 'auth.user',
},
moduleName: 'auth',
expiredStorage: 'auth.expired',
redirect: {
home: '/',
login: '/auth/login',
},
registerAxiosInterceptors: true,
storage: {
driver: 'secureLs', // supported: cookie, local, secureLs (secure local storage)
},
};-
url: Login path. E.g./user/loginmethod: HTTP Method. E.g.GET,POST, etc.
-
url: Logout path. E.g./user/logoutmethod: HTTP Method. E.g.GET,POST, etc.
-
url: Endpoint for getting user data. E.g./my/profilemethod: HTTP Method. E.g.GET,POST, etc.
-
Token property path using dot notation.
- Type:
string - Default:
data.token
- Type:
-
Token type.
- Type:
string - Default:
Bearer
- Type:
-
Token storage name.
- Type:
string - Default:
auth.token
- Type:
-
Auto decodes token when possible. Usually used when using JWT Token.
- Type:
boolean - Default:
true
- Type:
-
Token header name.
- Type:
string - Default:
Authorization
- Type:
-
Fetch user data automatically when user successfully logged in.
- Type:
boolean - Default:
true
- Type:
-
Property path of user data.
- Type:
string - Default:
data
- Type:
-
Storage name for storing user data.
- Type:
string - Default:
auth.user
- Type:
Vuex's module name.
- Default:
auth - Type:
string
Storage name for storing token expiratin time.
- Type:
string - Default:
auth.expired
-
Homepage path.
- Type:
string - Default:
/
- Type:
-
Login path.
- Type:
string - Default:
/
- Type:
Register custom axios interceptors when true. Set the value to false if you want to use your own interceptors.
- Type:
boolean - Default:
true
-
- Type:
string - Default:
secureLs - Available Options:
local|secureLs|cookie
- Type:
To implement refresh token, update your auth options like so:
import { AuthOptions } from '@gravitano/vue-auth'
export const defaultOptions: AuthOptions = {
endpoints: {
login: {
url: '/auth/login',
method: 'post',
},
logout: {
url: '/auth/logout',
method: 'delete',
},
user: {
url: '/auth/me',
method: 'get',
},
+ refresh: {
+ url: '/auth/refresh_token',
+ method: 'get',
+ },
},
token: {
property: 'data.token',
type: 'Bearer',
storageName: 'auth.token',
autoDecode: false,
name: 'Authorization',
},
user: {
autoFetch: true,
property: 'data',
storageName: 'auth.user',
},
moduleName: 'auth',
expiredStorage: 'auth.expired',
redirect: {
home: '/',
login: '/auth/login',
},
registerAxiosInterceptors: true,
storage: {
driver: 'secureLs', // supported: cookie, local, secureLs (secure local storage)
},
+ refreshToken: {
+ enabled: true, // <-- make sure the value is set to true
+ property: 'data',
+ maxAge: 60 * 60 * 24 * 30, // default 30 days
+ storageName: 'auth.refresh_token',
+ name: 'refresh_token',
+ autoLogout: true,
+ },
};Indicates the refresh token is enabled or not.
- Type:
string - Default:
false
Path of refresh token property from the response.
- Type:
string - Default:
data.refresh_token
Maximum age of new token.
- Type:
number - Default:
60 * 60 * 24 * 30(30 Days)
Storage name for storing refresh token data.
- Type:
string - Default:
auth.refresh_token
Payload name to sent when refreshing token.
- Type:
string - Default:
refresh_token
When true, user will forced to logout and login again when refresh token failed.
- Type:
boolean - Default:
true