How to Authenticate User using Laravel Api routes and Vue 2 Js and Vue Router - laravel

My goal is that laravel has an implemented Authorization Provider for us
https://laravel.com/docs/5.3/authentication
so I want to authenticate my users by using that by an API and set it back to my Vue Router
and authorize the users
How can i implement it?
Im always getting an error on authentication
im using axios as my HTTP provider
Here is the app.js
require('./bootstrap');
import VueRouter from 'vue-router';
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
Vue.use(VueRouter);
axios.defaults.baseURL = '/api';
axios.defaults.headers.common['X-CSRF-TOKEN'] = window.Laravel.csrfToken;
import LoginForm from './components/LoginForm.vue';
import RegisterForm from './components/RegisterForm.vue';
Vue.component('login-form',LoginForm)
Vue.component('register-form',RegisterForm)
// Directives
const routes = [
{ path: '/', component: require('./pages/Index.vue') },
{ path: '/admin/users', component: require('./pages/admin/Users.vue') },
{ path: '/user/:id', component: require('./pages/user/Dashboard.vue'),
children: [
// UserHome will be rendered inside User's <router-view>
// when /user/:id is matched
{ path: '', component: require('./pages/user/Index.vue')},
// UserPosts will be rendered inside User's <router-view>
// when /user/:id/posts is matched
{ path: 'settings', component: { template: '<div>Settings</div>' } },
]
},
{ path: '/manager/:id', component: require('./pages/user/Dashboard.vue'),
children: [
// UserHome will be rendered inside User's <router-view>
// when /user/:id is matched
{ path: '', component: require('./pages/user/Index.vue')},
// UserPosts will be rendered inside User's <router-view>
// when /user/:id/posts is matched
{ path: 'settings', component: require('./pages/user/Settings.vue') },
]
},
{ path: '/store/:id', component: require('./pages/user/Dashboard.vue'),
children: [
// UserHome will be rendered inside User's <router-view>
// when /user/:id is matched
{ path: '', component: require('./pages/user/Index.vue')},
// UserPosts will be rendered inside User's <router-view>
// when /user/:id/posts is matched
{ path: 'settings', component: { template: '<div>Settings</div>' } },
]
},
{ path: '/*', component: require('./pages/404.vue') },
];
const router = new VueRouter({
routes,
});
const app = new Vue({
el: '#app',
router,
template: `<div id="#app">
<router-view></router-view>
</div>`,
})
Here is the a Login form component
<template>
<form class="form" #submit.prevent='submitForm'>
<div class="form-group">
<input type="email" class="form-control" name="email" v-model="login.email" placeholder="Email">
</div>
<div class="form-group">
<input type="password" class="form-control" name="password" v-model="login.password" placeholder="Password">
</div>
<div class="form-group">
<button type="submit" class="btn btn-info btn-block"> Login </button>
</div>
</form>
</template>
<script>
export default {
data() {
return {
errors: [],
login: {
email: '',
password: '',
_token: window.Laravel.csrfToken
}
}
},
methods: {
submitForm() {
this.axios.post('/login',this.login)
.then(response => {
})
.catch(response => {
})
}
}
}
</script>
this is my Laravel API
in api.php
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::group(['middleware' => 'auth'], function () {
Route::get('/auth',function() {
return Auth::user();
});
Route::resource('/users','UserController');
Route::resource('/stores','StoreController');
Route::resource('/items','ItemController');
Route::resource('/transactions','StoreController');
Route::resource('/managers','ManagerController');
Route::resource('/employees','EmployeeController');
Route::resource('/customers','CustomerController');
Route::resource('/tags','TagController');
});
Route::group(['middleware' => 'web'], function() {
Auth::routes();
});
So my BIG PROBLEM here is the authentication using vue i'm used to authentication in blade templates and laravel routes but not on vue

Related

VUE js How hide routes by role in vue-router? Spa Laravel Vue

I am writing a SPA application (laravel + vue). There was a question how to hide routes in vue-router before authorization of a user with a certain role.
Now there is such a router.js fight with routes.
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../components/Calendar.vue'
import PermissionList from '../components/PermissionList.vue'
import BoardsList from '../components/BoardsList.vue'
import UsersList from '../components/UsersList.vue'
import Login from '../components/Login.vue'
const routes = [{
path: '/',
name: 'Home',
component: Home
},
{
path: '/permission-list',
name: 'PermissionList',
component: PermissionList
},
{
path: '/boards-list',
name: 'BoardsList',
component: BoardsList
},
{
path: '/users-list',
name: 'UsersList',
component: UsersList
},
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/dsad',
name: 'asd',
component: Login
},
]
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes,
linkActiveClass: "active",
})
router.beforeEach((to, from, next) => {
const token = localStorage.getItem('token');
if (!token) {
if (to.name == 'Login') {
next();
} else {
next({
name: 'Login'
});
}
} else {
if (to.name == 'Login') {
next({
name: 'Home'
});
} else {
next();
}
}
})
export default router
User data including his role and jwt token come after authorization and are stored in localstorage.
<template>
<main class="form-signin text-center">
<div>
<h1 class="h3 mb-3 fw-normal">Form</h1>
<div class="form-floating">
<input
type="text"
class="form-control"
placeholder="Login"
v-model="login"
/>
<label for="floatingInput">Login</label>
</div>
<div class="form-floating my-2">
<input
type="password"
class="form-control"
placeholder="Pass"
v-model="password"
/>
<label for="floatingPassword">Pass</label>
</div>
<a class="w-100 btn btn-lg btn-primary" #click="logIn()">
Login
</a>
</div>
</main>
</template>
<script>
export default {
name:'Login',
data() {
return {
login:"",
password:"",
};
},
methods: {
logIn() {
this.HTTP.get('/sanctum/csrf-cookie').then(response => {
this.HTTP.post("/login",{
email:this.login,
password:this.password,
})
.then((response) => {
localStorage.setItem('token',response.config.headers['X-XSRF-TOKEN']);
localStorage.setItem('user',JSON.stringify(response.data.user));
this.$emit('loginUpdate');
this.$router.push('/');
})
.catch((error) => {
console.log(error);
});
});
},
},
};
</script>
<style>
.form-signin {
width: 100%;
max-width: 330px;
padding: 15px;
margin: auto;
}
.form-signin .checkbox {
font-weight: 400;
}
</style>
if you go to the vue developer panel, all routes will be visible even before the user is authorized, how can I hide them so that unauthorized users do not see the site structure.
did you solve this problem?
Just use separated js file using your mixin laravel config. One login.js, another app.js and then use each of them in separated view-laravel

Implementing Laravel 7 Passport authentification with Nuxt frontend

I have installed and configured Laravel 7.3 Passport, then I made a fresh install of Nuxt.js and configure it as explained here (works perfect with Laravel 5.8.34). But when logging in, I get a CORS error message in the javascript console:
Access to XMLHttpRequest at 'http://my-laravel.test/oauth/token' from
origin 'http://localhost:3000' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource.
Below is how I configured Nuxt.js:
pages/index.vue
<template>
<section class="container">
<div>
<strong>Home Page</strong>
<pre>Both guests and logged in users can access!</pre>
<nuxt-link to="/login">Login</nuxt-link>
</div>
</section>
</template>
pages/login.vue
<template>
<div class="container">
<div class="row justify-content-center mt-5">
<div class="col-md-5">
<form>
<div class="form-group">
<input
v-model="user.username"
class="form-control"
placeholder="Username"
/>
</div>
<div class="form-group">
<input
v-model="user.password"
type="password"
class="form-control"
placeholder="Password"
/>
</div>
<button
#click.prevent="passwordGrantLogin"
type="submit"
class="btn btn-primary btn-block"
>
Login with Password Grant
</button>
</form>
</div>
</div>
</div>
</template>
<script>
export default {
middleware: 'guest',
data() {
return {
user: {
username: '',
password: ''
}
}
},
mounted() {},
methods: {
async passwordGrantLogin() {
await this.$auth.loginWith('password_grant', {
data: {
grant_type: 'password',
client_id: process.env.PASSPORT_PASSWORD_GRANT_ID,
client_secret: process.env.PASSPORT_PASSWORD_GRANT_SECRET,
scope: '',
username: this.user.username,
password: this.user.password
}
})
}
}
}
</script>
pages/profile.vue
<template>
<section class="container">
<div>
<strong>Strategy</strong>
<pre>{{ strategy }}</pre>
</div>
<div>
<strong>User</strong>
<pre>{{ $auth.user }}</pre>
</div>
<button #click="logout" class="btn btn-primary">
Logout
</button>
</section>
</template>
<script>
export default {
middleware: 'auth',
data() {
return {
strategy: this.$auth.$storage.getUniversal('strategy')
}
},
mounted() {},
methods: {
async logout() {
await this.$auth.logout()
}
}
}
</script>
nuxt.config.js (partly)
/*
** Nuxt.js modules
*/
modules: [
// Doc: https://axios.nuxtjs.org/usage
'#nuxtjs/axios',
'#nuxtjs/proxy',
'#nuxtjs/pwa',
'#nuxtjs/auth',
'#nuxtjs/dotenv',
'bootstrap-vue/nuxt'
],
/*
** Axios module configuration
** See https://axios.nuxtjs.org/options
*/
axios: {
baseURL: process.env.LARAVEL_ENDPOINT,
// proxy: true
},
// Proxy module configuration
proxy: {
'/api': {
target: process.env.LARAVEL_ENDPOINT,
pathRewrite: {
'^/api': '/'
}
}
},
// Auth module configuration
auth: {
// redirect: {
// login: '/login',
// logout: '/',
// callback: '/login',
// home: '/profile'
// },
// strategies: {
// 'laravel.passport': {
// url: '/',
// client_id: process.env.PASSPORT_PASSWORD_GRANT_ID,
// client_secret: process.env.PASSPORT_PASSWORD_GRANT_SECRET
// }
// }
strategies: {
local: false,
password_grant: {
_scheme: 'local',
endpoints: {
login: {
url: '/oauth/token',
method: 'post',
propertyName: 'access_token'
},
logout: false,
user: {
url: 'api/auth/me',
method: 'get',
propertyName: 'user'
}
}
}
}
},
middleware/guest.js
export default function({ store, redirect }) {
if (store.state.auth.loggedIn) {
return redirect('/')
}
}
.env
LARAVEL_ENDPOINT='http://my-laravel.test/'
PASSPORT_PASSWORD_GRANT_ID=6
PASSPORT_PASSWORD_GRANT_SECRET=p9PMlcO***********GFeNY0v7xvemkP
As you can see in the commented code source, I also tried unsuccessfully with proxy as suggested here and with auth strategy laravel.passport as suggested here.
Go to cors.php and make sure you have oauth endpoint like api/* or laravel sanctum.
You have to clear config and cache before test again

Vue - Vue routes doesn´t exist

I have a project in Laravel + Vue. In Laravel i have some routes for create endpoints and start page.
Laravel Routes
Route::get('/', 'Auth\LoginController#showLoginForm');
Route::post('/login', 'Auth\LoginController#login');
Auth::routes();
Route::resource('gateways', 'GatewayController');
Route::resource('contadores', 'ContadorController');
'/' route go to Blade file with Login Component.
Login Component has this code.
<template>
<v-content slot="content">
<v-container class="fill-height" fluid>
<v-row align="center" justify="center">
<v-col cols="12" md="8">
<v-card class="elevation-12">
<v-toolbar dark flat>
<v-toolbar-title>LoRaWAN</v-toolbar-title>
</v-toolbar>
<v-card-text>
<v-form>
<v-text-field
label="Usuario"
name="username"
prepend-icon="mdi-account"
type="text"
v-model="username"
/>
<v-text-field
label="Contraseña"
name="password"
prepend-icon="mdi-key"
:append-icon="value ? 'mdi-eye' : 'mdi-eye-off'"
#click:append="() => (value = !value)"
:type="value ? 'password' : 'text'"
v-model="password"
/>
</v-form>
</v-card-text>
<v-card-actions>
<v-btn block dark #click="submit()">Entrar</v-btn>
</v-card-actions>
</v-card>
</v-col>
</v-row>
</v-container>
</v-content>
</template>
<script>
export default {
data() {
return {
value: String,
username: "",
password: ""
};
},
methods: {
submit() {
axios
.post("http://127.0.0.1:8000/login", {
username: this.username,
password: this.password
})
.then(response => {
if (response.data.token != null) {
localStorage.setItem("token", response.data.token);
console.log("ok");
this.$router.push({
name: "lora",
params: { user: this.username }
});
}
})
.catch(function(errors) {
let error = errors.response.data.errors;
let mensaje = "Error no identificado";
if (error.hasOwnProperty("username")) {
mensaje = error.username[0];
} else {
mensaje = error.password[0];
}
Swal.fire({
title: "Error",
text: mensaje,
icon: "error",
confirmButtonText: "Ok"
});
});
}
}
};
</script>
As we can see when login endpoint return token we want to push to other 'lora' route.
Vue routes file
import ContadorComponent from "./components/contador/ContadorComponent.vue";
import GatewayComponent from "./components/gateway/GatewayComponent.vue";
import HomeComponent from "./components/home/HomeComponent.vue";
import MainComponent from "./components/main/MainComponent.vue";
const routes = [{
path: "/lora",
name: "lora",
component: MainComponent,
props: true,
children: [{
path: "",
name: "home",
component: HomeComponent
},
{
path: "contadores",
name: "contadores",
component: ContadorComponent
},
{
path: "gateways",
name: "gateways",
component: GatewayComponent
}
]
}];
const router = new VueRouter({
mode: 'history',
routes: routes
});
new Vue({
vuetify: new Vuetify(),
router
}).$mount("#app");
And lora route (Main Component)
<template>
<v-app id="app">
<layoutDrawer></layoutDrawer>
<layoutHeader></layoutHeader>
<v-content>
<router-view></router-view>
</v-content>
<layoutFooter></layoutFooter>
</v-app>
</template>
<script>
import layoutHeader from "./partials/HeaderComponent.vue";
import layoutFooter from "./partials/FooterComponent.vue";
import layoutDrawer from "./partials/SidebarComponent.vue";
export default {
props: {
username: { type: String, default: "Invitado" }
},
components: {
layoutHeader,
layoutDrawer,
layoutFooter
}
};
</script>
The problem: If i go to http://127.0.0.1:8000/lora returns that this route doesn´t exist. In the vue routes file i declare it, so i don´t know why returns this. Maybe Laravel generate a conflict or something with routes. In laravel routes file i test this code and works
Route::get('/test', function () {
return view('home');
})->name('home');
The view home is blade file with Main Component. Maybe something happens with the vue routes that project doesn't recognize and only works Laravel routes..
The question: Are the vue routes properly declares? Anybody see some error?
Your client and server are running on the same port: http://127.0.0.1:8000.
The url for your lora route should be something like http://127.0.0.1:8001/lora
I found a partially solution. In Laravel routes i need to put this
Route::get('{any?}', function () {
return view('layout');
})->where('any', '.*');
Every time the user push to another page load Layout blade.
#extends('layouts.app')
#section('content')
<layout-component></layout-component>
#endsection
Layout Component
<template>
<v-app id="app">
<router-view></router-view>
</v-app>
</template>

<router-view> in laravel 5.6 and vue.js don't work

I do not know what I'm doing wrong, but my router-view does not work.
I have an app based on Laravel 5.6 and I want to make views through vue.js.
Components "Navbar" and "Foot" are load correctly but I don't see "Home" component which should be load by in App.vue
Routing also does not work. When I type in the browser /about I get an error "Sorry, the page you are looking for could not be found."
Below my files:
App.vue
<template>
<div class="app">
<Navbar/>
<router-view></router-view>
<Foot/>
</div>
</template>
<script>
export default {
name: 'App',
data () {
return{
}
}
}
</script>
Home.vue
<template>
<div class="home">
<h1>Home</h1>
</div>
</template>
<script>
export default {
name: 'Home',
data () {
return {
}
}
}
</script>
About.vue
<template>
<div class="about">
<h1>O nas</h1>
</div>
</template>
<script>
export default {
name: 'About',
data (){
return{
}
}
}
</script>
app.js
require('./bootstrap');
import Vue from 'vue';
import VueRouter from 'vue-router';
import Vuex from 'vuex';
window.Vue = require('vue');
Vue.use(VueRouter);
Vue.use(Vuex);
let AppLayout = require('./components/App.vue');
// home tempalte
const Home = Vue.component('Home', require('./components/Home.vue'));
// About tempalte
const About = Vue.component('About', require('./components/About.vue'));
// register components
const Navbar = Vue.component('Navbar', require('./components/Navbar.vue'));
const Foot = Vue.component('Foot', require('./components/Foot.vue'));
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
name: 'About',
path: '/about',
component: About
}
];
const router = new VueRouter({ mode: 'history', routes: routes});
new Vue(
Vue.util.extend(
{ router },
AppLayout
)
).$mount('#app');
You need to teach laravel's router how to play along with vue's.
Check out this link: https://medium.com/#piethein/how-to-combine-vuejs-router-with-laravel-1226acd73ab0
You need to read around where it says:
Route::get('/vue/{vue_capture?}', function () {
return view('vue.index');
})->where('vue_capture', '[\/\w\.-]*');

Routing through different components in vue

I am currently working with laravel and vuejs for a booking application, the flow of the app is that once the user clicks to book they get redirected to a page where the booking process starts, this page is where i instantiate vue, and i also call the first component (Book Component) to be rendered:
#section('content')
{{-- <div id="mute" class="on"></div> --}}
<div style="padding: 0.9rem" id="app">
{{-- <router-view name="bookBus"></router-view> --}}
<booker :dref="{{ $route }}" :user="{{ Auth::user()->id }}"></booker>
<router-view></router-view>
</div>
#stop
#section('scripts')
my app.js file looks like this:
// Import Components
import BookComponent from './components/BookComponent.vue';
import ConfirmComponent from './components/ConfirmComponent.vue';
import PayComponent from './components/PayComponent.vue';
Vue.component('booker',BookComponent);
const routes = [
{
path: '/',
component: BookComponent,
name: 'bookBus',
meta: {
mdata: model,
userId: userId
},
},
{
path: '/confirm/:bookId',
component: ConfirmComponent,
name: 'confirmBook',
},
{
path: 'payment/:bookRef',
component: PayComponent,
name: 'payNow',
}
]
const router = new VueRouter({
routes,
mode: 'history',
});
const app = new Vue(
{
router,
}).$mount('#app')
after this the next component to be rendered is the confirmation component that asks the user to confirm the submitted details, and after this is the final payment component. The issue is once the booking component has been processed successfully i programmatically moved to the confirm component. But the confirm component renders directly below the book component. what i want to achieve is for the confirm component to render alone and not below the book component.
#section('content')
{{-- <div id="mute" class="on"></div> --}}
<div style="padding: 0.9rem" id="app">
{{-- <router-view name="bookBus"></router-view> --}}
<router-view></router-view>
</div>
#stop
#section('scripts')
app.js
// Import Components
import BookComponent from './components/BookComponent.vue';
import ConfirmComponent from './components/ConfirmComponent.vue';
import PayComponent from './components/PayComponent.vue';
const routes = [
{
path: '/',
component: BookComponent,
name: 'bookBus',
meta: {
mdata: model,
userId: userId
}
},
{
path: '/confirm/:bookId',
component: ConfirmComponent,
name: 'confirmBook',
},
{
path: 'payment/:bookRef',
component: PayComponent,
name: 'payNow',
},
{
path: '*',
redirect: '/'
}
]

Resources