Implementing user authentication using JSON Web Tokens (JWT) in Vue.js involves several steps. Here's a basic guide to get you started:
Server-side Setup:
jsonwebtoken
to generate and verify JWTs.Install Axios:
Axios is a popular HTTP client for making requests to your server. Install it in your Vue.js project:
bashnpm install axios
Create a Vuex Store:
Vuex is a state management library for Vue.js. Create a Vuex store to manage the user authentication state.
javascript// store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
token: null,
},
mutations: {
setToken(state, token) {
state.token = token;
},
clearToken(state) {
state.token = null;
},
},
actions: {
setToken({ commit }, token) {
commit('setToken', token);
},
clearToken({ commit }) {
commit('clearToken');
},
},
getters: {
isAuthenticated: (state) => !!state.token,
},
});
Login Component:
Create a login component to handle user authentication.
vue<!-- components/Login.vue --> <template> <div> <input v-model="username" placeholder="Username" /> <input v-model="password" type="password" placeholder="Password" /> <button @click="login">Login</button> </div> </template> <script> import axios from 'axios'; export default { data() { return { username: '', password: '', }; }, methods: { async login() { try { const response = await axios.post('/api/login', { username: this.username, password: this.password, }); const token = response.data.token; this.$store.dispatch('setToken', token); // Redirect or perform other actions after successful login } catch (error) { console.error('Login failed', error); } }, }, }; </script>
API Requests with Axios:
Use Axios to send authenticated requests by including the JWT in the Authorization header.
javascript// Use Axios interceptor to include the token in every request
axios.interceptors.request.use((config) => {
const token = store.state.token;
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
Route Guards:
Implement route guards to protect routes that require authentication.
javascript// router/index.js
import Vue from 'vue';
import Router from 'vue-router';
import store from '../store';
Vue.use(Router);
const router = new Router({
routes: [
{
path: '/dashboard',
name: 'dashboard',
component: () => import('../views/Dashboard.vue'),
meta: { requiresAuth: true },
},
// Other routes
],
});
router.beforeEach((to, from, next) => {
if (to.matched.some((record) => record.meta.requiresAuth)) {
if (!store.getters.isAuthenticated) {
next({ path: '/login' });
} else {
next();
}
} else {
next();
}
});
export default router;
Now, when a user logs in, the server generates a JWT, which is stored in the Vuex store. The token is included in the Authorization header for authenticated requests. Route guards protect routes that require authentication. Adjust the code according to your specific backend implementation and requirements.