I have just started learning VueJS. I am using vuejs to call an external api that does CRUD operations for my application. The CRUD operations are made in the admin panel (http://domain.com/admin-dashboard) which requires a username and password. The external api endpoint provides an api/auth
endpoint that accepts a username and a password and if the details are correct provides a JWT token. This token should be used when making the api request for the CRUD operations by passing the token in Authorization header Bearer xxx (where xxx is the token id)
Well everything works fine till here. But the problem is how do I stop someone from accessing the /admin-dashboard
page using vuejs? Earlier the traditional way of doing this in php is something like this:
<?php
session_start();
if(empty($_SESSION['is_logged_in'])){
// Redirect to login page
header('Location login.php');
exit();
}
This way i can be sure that no unauthorized user can access the dashboard. But now since my entire app is based on vuejs, how do I secure the admin-dashboard
page?
Any help will be appreciated.
If you are using Vue-Router, you can add a before hook to the routes to ensure authorization. You can pass some kind of variable along with your token and set it in localStorage or in Vuex state.
router.beforeEach((to, from, next) => {
if(/admin/.test(to.path)) { // Using regex to test the URL path
if(store.state.user.is_admin){ // Assuming is_admin is a boolean in Vuex state
next() // Allows it to proceed
} else {
next('/login') // Or make a 403 page or whatever
}
}
}
Of course you must secure the backend, as other comments have said, but your question was particularly about how to not allow navigation on the frontend.
If you don't want data leakage, then everything on the backend api should be authenticated and authorized exactly like before you moved to vue.
So you should do two things
FRONT: Setup a route constraint in vue to redirect if someone is not authorized OR just display 'not authorized'. You can do this by returning a context along with the user that lets you know the context or have an api request to get the admin info and return a not authorized if they are not and display the notice based on that request. Pros and cons to either.
BACK: In your server check that the user has access before getting into the meat of the request. I have not used php in a long time, but in rails we just setup a before_action in the controller that checks current_user against whatever requirements we have for them to access.
Hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With