Skip to content

Instantly share code, notes, and snippets.

@tlimpanont
Last active July 9, 2017 17:39
Show Gist options
  • Save tlimpanont/797717de26afb9385ad8ac36b8d794dc to your computer and use it in GitHub Desktop.
Save tlimpanont/797717de26afb9385ad8ac36b8d794dc to your computer and use it in GitHub Desktop.
authentication with auth0 and vue js
export const AUTH_CONFIG = {
clientId: 'CLIENT_ID',
domain: 'CLIENT_DOMAIN',
callbackUrl: 'CALLBACK_URL',
apiUrl: 'API_IDENTIFIER'
}
import auth0 from 'auth0-js'
import { AUTH_CONFIG } from './auth0-variables'
import EventEmitter from 'EventEmitter'
import router from './../router'
export default class AuthService {
// Initiating our Auth0Lock
lock = new Auth0Lock(
AUTH_CONFIG.clientId,
AUTH_CONFIG.domain, {
auth: {
redirectUrl: AUTH_CONFIG.callbackUrl,
responseType: 'token id_token',
params: {
scope: 'openid' // Learn about scopes: https://auth0.com/docs/scopes
}
}
}
)
authenticated = this.isAuthenticated()
authNotifier = new EventEmitter()
constructor() {
this.login = this.login.bind(this)
this.setSession = this.setSession.bind(this)
this.logout = this.logout.bind(this)
this.isAuthenticated = this.isAuthenticated.bind(this)
}
auth0 = new auth0.WebAuth({
domain: AUTH_CONFIG.domain,
clientID: AUTH_CONFIG.clientId,
redirectUri: AUTH_CONFIG.callbackUrl,
audience: `https://${AUTH_CONFIG.domain}/userinfo`,
responseType: 'token id_token',
scope: 'openid'
})
login() {
this.lock.show();
}
handleAuthentication() {
// Listening for the authenticated event
this.lock.on("authenticated", (authResult) => {
// Use the token in authResult to getUserInfo() and save it to localStorage
this.lock.getUserInfo(authResult.accessToken, (error, profile) => {
if (error) {
router.replace('home');
console.log(err);
alert(`Error: ${err.error}. Check the console for further details.`);
return;
}
this.setSession(authResult, profile);
router.replace('private');
});
});
}
setSession(authResult, profile) {
let expiresAt = authResult.idTokenPayload.exp * 1000;
localStorage.setItem('access_token', authResult.accessToken)
localStorage.setItem('id_token', authResult.idToken)
localStorage.setItem('expires_at', expiresAt)
localStorage.setItem('profile', JSON.stringify(profile));
this.authNotifier.emit('authChange', { authenticated: true })
}
logout() {
// Clear access token and ID token from local storage
localStorage.removeItem('access_token')
localStorage.removeItem('id_token')
localStorage.removeItem('expires_at')
localStorage.removeItem('profile')
this.userProfile = null
this.authNotifier.emit('authChange', false)
// navigate to the home route
router.replace('home')
}
isAuthenticated() {
// Check whether the current time is past the
// access token's expiry time
// let expiresAt = JSON.parse(localStorage.getItem('expires_at'))
// return new Date().getTime() < expiresAt
let expiresAt = localStorage.getItem('expires_at')
return new Date().getTime() < expiresAt
}
}
import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/Home'
import Callback from '@/components/Callback'
import AuthService from '../auth/AuthService'
import Private from '@/components/Private'
Vue.use(Router)
const router = new Router({
mode: 'history',
routes: [
{
path: '/private',
name: 'Private',
component: Private,
meta: { requiresAuth: true }
},
{
path: '/home',
name: 'Home',
component: Home
},
{
path: '/callback',
name: 'Callback',
component: Callback
},
{
path: '*',
redirect: '/home'
}
]
})
router.beforeEach((to, from, next) => {
const { login, logout, authenticated, authNotifier } = new AuthService();
if (to.matched.some(record => record.meta.requiresAuth)) {
// this route requires auth, check if logged in
// if not, redirect to login page.
if (!authenticated) {
next({
path: '/home',
})
} else {
next()
}
} else {
next() // make sure to always call next()!
}
})
export default router
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment