Support the ongoing development of Laravel.io →
Authentication Security Requests

hi, so i am using laravel and vue js and also using laravel passport for authentication method. i tried to follow tutorial from vuetiful project, but i find there is something weird with my app, is that sometimes when i login from login screen it just throw me error 401 even thought i type the right username and password. and when i tried to type in my browser address bar to just navigate into dashboard (which already have some middleware in vue js to redirect user to login screen if not authenticated) it just open dashboard with information that i already authenticated.

to help understanding my issue here is my code

here is my app.js

import Vue from 'vue';
import App from './app.vue';
import Axios from 'axios';
import VueRouter from 'vue-router';
import routes from './routes';

Vue.use(VueRouter)

window.axios = Axios;

axios.defaults.headers.common = {
    'X-CSRF-TOKEN': window.Laravel.csrfToken,
    'X-Requested-With': 'XMLHttpRequest'
};

const router = new VueRouter({
    base: '/vue',
    mode: 'history',
    routes
})

router.beforeEach((to, from, next) => {
    if (to.fullPath !== "/login") {
        axios.get('/api/profile').then(response => {
            next();
        }).catch(error => {
            router.push('/login');
        })
    } else {
        next();
    }
})

const app = new Vue({
    router,
    render: h => h(App)
}).$mount('#root');

here is my routes.js

import dashview from './views/dashview.vue';
import login from './views/login.vue';
import dashboard from './views/dashboard.vue';
import artikelindex from './views/artikel/index.vue';


const routes = [
	{
		path: '/login',
		component: login
	},
	{
		path: '/',
		component: dashview,
		children:[
			{
				path: 'dashboard',
				alias: '',
				component: dashboard,
				name: 'dashboard',
				meta: {description: 'Overview'}
			},
			{
				path: 'artikel',
				alias: '',
				component: artikelindex,
				name: 'artikelindex',
				meta: {description: 'Artikel'}
			}
		]
	}
]

export default routes

here is my login.vue

<template>
<div class="login-box">
	<div class="login-box-body">
		<div class="login-logo">
			<img src="images/logo.png" width="30%" alt="logo">
		</div>
		<p class="login-box-msg">
			<b>Sistem Informasi Manajemen Organisasi</b>
		</p>
		<fieldset>
			<div class="form-group">
				<div class="input-group">
					<span class="input-group-addon"><i class="fa fa-user"></i></span>
					<input type="text" name="username" placeholder="Username" class="form-control" autofocus="true" required="true" v-model="username">
				</div>
			</div>
			<div class="form-group">
				<div class="input-group">
					<span class="input-group-addon"><i class="fa fa-lock"></i></span>
					<input type="password" name="password" placeholder="password" class="form-control" required="true" v-model="password">
				</div>
			</div>
			<div class="row">
				<div class="col-xs-12">
					<button type="button" class="btn btn-primary btn-block btn-flat" @click.prevent="login" ><i class="fa fa-sign-in"></i> Login</button>
				</div>
			</div>
		</fieldset>
	</div>
</div>
</template>

<script type="text/javascript">
	export default {
		methods: {
			login(){
				axios.post('/login',{
					username: this.username,
					password: this.password
				})
				.then(response => {
					this.$router.push('/');
				}).catch(error => {
					console.log(error);
				})
			}
		},
		data(){
			return {
				username: "",
				password: ""
			}
		}
	}
</script>

here is my dashview that only contain header bar which also contain logout button

<template>
	<header class="main-header">
		<nav class="navbar navbar-static-top">
			<div class="navbar-header">
				<router-link to="/" class="navbar-brand" title="Sistem Informasi Manajemen Organisasi">SIMO</router-link>
				<button class="navbar-toggle collapse" data-toggle="collapse" data-target="#navbar-collapse">
					<i class="fa fa-bars"></i>
				</button>
			</div>

			<div class="collapse navbar-collapse pull-left" id="navbar-collapse">
				<ul class="nav navbar-nav">
					<li>
						<router-link to="/">Dashboard</router-link>
					</li>
					<li>
						<router-link to="/artikel">Artikel</router-link>
					</li>
					<li>
						<a href="#" @click.prevent="logout">Logout</a>
					</li>
				</ul>
			</div>
		</nav>
	</header>
</template>

<script type="text/javascript">
	export default{
		methods:{
			logout(){
				axios.post('/logout').then(response => {
					location.reload();
				}).catch(error => {
					location.reload();
				});
			}
		}
	}
</script>

and here is my dashboard.vue

<template>
	<div>Hello {{name}}</div>
</template>
<script type="text/javascript">
	export default{
		created(){
			this.getUser();
		},
		methods:{
			getUser(){
				axios.get('/api/profile').then(response => {
					this.name = response.data.name;
				})
			}
		},
		data(){
			return{
				name:''
			}
		}
	}
</script>

as you can see to test is it authenticated just do get request to '/api/profile', and here is my laravel api routes

<?php

use Illuminate\Http\Request;

Route::middleware('auth:api')->get('/profile','AuthController@getUser');

and here is laravel web routes for login and logout (i am following tutorial in that wordpress)

<?php

Route::get('/vue/{vue?}', function () {
    return view('vue');
})->where('vue', '^(?!.*api).*$[\/\w\.-]*');

Route::post('login', 'AuthController@login');
Route::post('logout', 'AuthController@logout');

and this is my authcontroller (i am not using laravel built in auth since i have some specific need)

<?php
namespace App\Http\Controllers;

use Auth;
use Input;
use Validator;
use DB;
use Date;
use Redirect;

use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class AuthController extends Controller{


    function getUser(Request $request)
    {
       return json_encode($request->user());
    }


    public function login(Request $request)
    {
        if(Auth::attempt(array('username' => $request->username, 'password' => $request->password))){
            return response()
                ->json([
                    'authenticated' => true
                ]);
        }
    }

    public function logout()
    {
        Auth::logout();
        return response()
        ->json([
            'logout' => true
        ]);
    }

}
Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

t0n1zz t0n1zz Joined 8 Oct 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.