Force user to a page after sign-in and user that already log-in before - vue.js

I currently have a service authentication up and running (using jwt to auth).
I'm working on a quiz service that force user to create some required information and force them to take a quiz to understand how to use our tool.
Because lacking of Frontend exp, I'm wondering how this quiz service will integrate with the auth service
Right now, for Backend side during auth service I will give them back the permission in the token if I call the function to check if the user pass the test & have a profile created. Otherwise I give them back the token with permission = []
But for the Frontend side, what is the solution to re-direct use to Quiz page (after sign-in and what about user that already log-in before)

check this documentation programatic navigation
once authenticated redirect the user back using [vue2 code]
this.$router.push({name:'Quiz',params:{id:this.$route.query.next})
In the authentication page you may pass the quiz link as next query parameter eg
example.com/login?next=< quizID >
Navigation guard documentation
You can use route guards to redirect unauthenticated users to the login page, do remember to pass the quiz id as a query parameter.
your guard will be similar to this
router.beforeEach((to, from, next) => {
if (to.name === 'Quiz' && !isAuthenticated) next({ name: 'Login', query: { next: to.params.quizID }})
else next()
})
This was assuming you have set your routes has a route named Quiz and takes :id and a route named login, similar to this.
{
path: '/quiz/:id',
name: 'Quiz',
.....
},
{
path: '/login',
name: 'Login',
......
},
Alternatively, you could have set up a dialog box on the quiz page that handles authication.

Related

Vue-Router: Protecting private routes with authentication the right way

I have a /profile route that should only be accessible by an authenticated user. From research, the recommended approach is to use vue-router's navigation guard:
Here is the route object:
{
path: '/profile',
name: 'MyProfile',
component: () => import('#/views/Profile.vue'),
meta: { requiresAuth: true }
},
And here is the router's navigation guard:
router.beforeEach((to, from, next) => {
if (to.matched.some((record) => record.meta.requiresAuth)) {
if (isAuthenticated()) {
next()
}
else {
alert('Auth required!')
next('/login')
}
}
})
The isAuthenticated() function above sends a jwt token (stored in cookie) to the /jwt/validate endpoint which validates the token and returns a 200 OK response:
export function isAuthenticated() {
axios.post(`${baseUrl}/token/validate`, {}, { withCredentials: true })
.then(resp => resp.statusText == 'OK')
.catch(err => false)
}
With this approach, every time we visit the /profile route, we are making a POST request to the /token/validate endpoint. And this works quite well. However, is it too excessive to make this request every time?
My Solutions
I wonder if there is some way to store the data locally in memory. I thought of two possible solutions:
Option 1: Storing the data on vuex store, however I have learned that the vuex store object is accessible via the browser's console. This means that anyone can modify the access logic to gain access to protected routes.
Option 2: Store it inside a custom Vue.prototype.$user object, however this is similarly accessible via console and therefore has the same security risk as option 1.
Essentially, my question is: is there an option to access a protected route without having to validate the jwt token on the server-side every time?
You should query the server for if the token is valid once when the user initially loads the application. After that, there is usually no reason to check again. If the session expires on the server, then any other API calls you do should return a 401 response (or any other way that you choose to return an error) and your application can act on that.and your application can act on that.
If your profile route is getting data from the server to display and the server is properly validating the user for that request, then it doesn't matter if the user tries to manipulate the Vuex store or Vue state because they won't be able to load the data.
Doing authentication in the vue router is really more for convenience than for actual security.
Don't waste time trying to prevent a malicious user from exploring the Vue application - that is guaranteed to be a losing battle since all of the code is loaded into the browser.
If you really insist on some kind of protection, you can split the application using webpack chunks that are loaded dynamically and configure your web server to only serve those chunks to properly authenticated and authorize users. That said, I would expect such configuration to be difficult and error prone, and I don't recommend it.

How to handle permissions for route from database?

In Vue, when I want to restrict some pages for some users, in router I define a permission in meta, like this:
routes: [
{
path: 'transport',
name: 'transport',
component: Transport,
meta: { permission: "edit_transport" }
},
]
When user logins I have its JWT where I can find what permission he/she has and in route.beforeEach, I check if user has this permission, he/she can visit a page.
router.beforeEach((to, from, next) => {
let token = window.localStorage.getItem('user_token');
if(to.meta.permission == 'edit_transport') {
//if user's token has edit_tranport permission let him visit the page
}
})
But, now I have this permissions In database, there is a table where admin defines permission for page:
id permision page
_____________________________________
1 edit_transport transport
2 write_post create_post
This means, for example user needs edit_transport permission to visit transport page.
My solution is: first I have to take all this permissions from database and save them in vuex store, and then access this store data in route.beforeEach and check what permission page needs and then check if user has this permission
router.beforeEach((to, from, next) => {
let token = window.localStorage.getItem('user_token');
let pagepermission = store.permissions[to.name]
if (token.has(pagepermission)) {
// let user visit the page
} else {
// redirect
}
})
So, is it a good way or is there any other way better then this?
This is a good check to do on the client side, if you are also protecting routes / endpoints on the back end I think that would be the most well rounded solution.
I'm not sure what you're using on the backend but if its Node, you could use something like Passport to manage roles - as a middleware to routes and endpoints.

Aurelia cancel navigation in navigation strategy

I have a login route that will redirect the user to an external Open ID Connect login page. Once there, if the user clicks the back button, they hit the same route that redirected them, thus being redirected again. Is there a way to cancel Aurelia's navigation or prevent the current route from being remembered in the history?
config.mapRoute({
name: "login",
nav: false,
// If I exclude the module id, I get the desired behavior but errors are thrown from Aurelia.
moduleId: "components/login/login",
route: "login",
navigationStrategy: (instruction: NavigationInstruction) => {
// This promise constructs the redirect url then sets the window.location.href.
// Unfortunately, Aurelia seems to be finishing its business before the page is redirected because this login route is recorded in history.
return this.userManager.signinRedirect();
}
});
I know its been a while so you probably found an answer elsewhere, but you can try
router.navigate('new url', { replace: true });

Disable login route if a user is logged in with Hapi.js

Basically I have a login/register landing page of my app. After a user logs in or registers I don't want them to be able to access this route anymore. I'm not sure how to achieve this with Hapi.js. The login page doesn't use any auth strategies so it has no idea if a user is logged in or not.
The approach I normally use for this is not disabling the route per se, but redirecting logged-in users away from the login route.
As you point out correctly your login route currently doesn't know whether a user is logged in if it has no auth strategy configured. The solution is to add an auth strategy to the login route, but using the try mode. This means the handler will be executed regardless of whether auth was successful. The trick is that you can then check if the user is authenticated (by inspecting the value of request.auth.isAuthenticated) or not and react accordingly.
So your route might look like this:
server.route({
config: {
auth: {
strategy: 'session',
mode: 'try'
}
},
method: 'GET',
path: '/login',
handler: function (request, reply) {
if (request.auth.isAuthenticated) {
return reply.redirect('/'); // user is logged-in send 'em away
}
return reply.view('login'); // do the login thing
}
});
Another approach with the same result is to set your auth strategy on try mode as the default for all routes:
server.auth.strategy('session', 'cookie', 'try', {
password: 'password-that-is-longer-than-32-chars',
isSecure: true
});
Notice that third argument try. With this approach you don't need to add any auth config to the route itself because it will try this strategy by default. According to the server.auth.strategy docs:
mode - if true, the scheme is automatically assigned as a required strategy to any route without an auth config. Can only be assigned to a single server strategy. Value must be true (which is the same as 'required') or a valid authentication mode ('required', 'optional', 'try'). Defaults to false.
There's some more info about modes in the Authentication tutorial on the hapi site.

Sencha Touch history issue, when using routes and route filters

In Sencha Touch 2, I have a beforeFilter, before the routes.
When the user wants to visit a certain view, the "beforeFilter" acts first.
I use the filters for authentication check and other things.
I kept the example very simple, to highlight where I need help:
Ext.define("TestApp.controller.Router", {
extend: "Ext.app.Controller",
config: {
before: {
home: 'beforeFilter',
login: 'beforeFilter',
products: 'beforeFilter'
},
routes: {
'': 'home',
'home' : 'home',
'login' : 'login',
'products' : 'products',
'products/:id': 'product',
}
},
beforeFilter: function(action) {
// The before filter acts before the user gets to any of the routes.
// Check the user's authentication state.
// If the user wants to visit the "products" route and he ISNT't authenticated,
// Redirect the user to the login page.
this.redirectTo('login');
// else - go to the normal root.
action.resume();
},
home: function () {
// This and the functions bellow handle the display of the routes.
},
login: function () {
},
products: function () {
}
});
The problem.
User wants to view the products route but he isn't logged in.
The beforefilter steps in, and redirects the user to the login page.
Here is where I need help:
If the user is on the login page and clicks a button which triggers Sencha's history.back() event, the user gets redirected to the products page, AGAIN, the beforefilter steps in, and it redirects him back to the login view.
Basically, the history will no longer work.
To solve the problem, I would need a way to keep the products route from being logged into Sencha's history object when the user isn't authenticated.
Do you guys have other ideas?
I asked a more general question about this, but this one feel more documented to the issue in particular.
For views that you don't want to have history support, simply add / change the view without using redirectTo.
Straigh to viewport:
Ext.Viewport.add({xtype: 'myloginview'})
or with navigation view (in a controller):
this.getMyNavView().push({xtype: 'myloginview'})
this way the url doesn't change to #login, and doesn't add to the history stack.