-
-
Save felipefinhane/f8e72b823f97760b9d8106c7bc9dc8a1 to your computer and use it in GitHub Desktop.
Exemplo de Autenticação com JWT em Vue.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<h1>Página secreta!</h1> | |
</template> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') | |
} | |
} | |
] | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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)