Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using vuejs how to secure the admin panel

Tags:

vue.js

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-dashboardpage 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.

like image 794
Phantom007 Avatar asked Mar 09 '23 21:03

Phantom007


2 Answers

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.

like image 82
For the Name Avatar answered Mar 12 '23 09:03

For the Name


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

  1. 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.

  2. 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.

like image 20
Austio Avatar answered Mar 12 '23 11:03

Austio