Skip to content

Instantly share code, notes, and snippets.

@felipefinhane
Forked from VitorLuizC/Home.vue
Created April 2, 2018 12:01
Show Gist options
  • Save felipefinhane/f8e72b823f97760b9d8106c7bc9dc8a1 to your computer and use it in GitHub Desktop.
Save felipefinhane/f8e72b823f97760b9d8106c7bc9dc8a1 to your computer and use it in GitHub Desktop.
Exemplo de Autenticação com JWT em Vue.js
import decode from 'jwt-decode';
import request from './request';
export async function signIn (email, password) {
const { token } = await request('POST', '/authenticate', {
email,
password
});
localStorage.set('token', token);
}
export function signOut () {
localStorage.removeItem('token');
}
export function isSignedIn () {
const token = localStorage.getItem('token');
if (!token) // Se não existe o token no LocalStorage
return false; // significa que o usuário não está assinado.
try {
const { exp: expiration } = decode(token);
const isExpired = !!expiration && Date.now() > expiration * 1000;
if (isExpired) // Se o token tem uma data de expiração e
return false; // essa data é menor que a atual o usuário
// não está mais assinado.
return true;
} catch (_) { // O "jwt-decode" lança erros pra tokens inválidos.
return false; // Com um token inválido o usuário não está assinado.
}
}
<template>
<h1>Página secreta!</h1>
</template>
const baseURL = 'http://localhost:3001/v1/';
function getHeaders () {
const token = localStorage.getItem('token');
return {
'Content-Type': 'application/json',
...token && {
'Authorization': `Bearer ${token}`
}
};
}
async function request (method, url, body) {
const options = {
method,
headers: getHeaders(),
...(method !== 'GET') && {
body: JSON.stringify(body)
}
};
const response = await fetch(baseURL + url, options);
return await response.json();
}
export { request as default, request, getHeaders }
import Vue from 'vue';
import Router from 'vue-router';
import { isSignedIn } from './auth';
Vue.use(Router);
export default new Router({
routes: [
{
path: '/home',
component: () => import('./Home'),
beforeEnter (_, __, next) { // Impede usuários não assinados
if (isSignedIn()) { // de acessar a página Home.
next();
return;
}
next('/sign-in')
}
},
{
path: '/sign-in',
component: () => import('./SignIn'),
beforeEnter (_, __, next) { // Impede usuários assinados de
if (!isSignedIn()) { // acessar a página de login.
next();
return;
}
next('/home')
}
}
]
})
<template>
<form @submit.prevent="onSubmit()">
<fieldset>
<label>E-Mail</label>
<input v-model="email" type="email">
</fieldset>
<fieldset>
<label>Senha</label>
<input v-model="password" type="password">
</fieldset>
<fielset>
<button type="submit">Entrar</button>
</fieldset>
</form>
</template>
<script>
import { signIn } from './auth';
export default {
methods: {
async onSubmit () {
await signIn(this.email, this.password);
this.$router.push('/home');
}
}
};
</script>
@AndreMyszko
Copy link

Cool, its hard to begin with it '-'
I am trying to proxy a spring security based api with vue router and vuex... JWT will help me with that?

@felipefinhane
Copy link
Author

Cool, its hard to begin with it '-'
I am trying to proxy a spring security based api with vue router and vuex... JWT will help me with that?

Sorry, but I don't use Spring Security, but I think yes. I find this article (https://www.tutorialspoint.com/spring_security/spring_security_with_jwt.htm)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment