Courses

Vue.js 3 + Laravel 11 API + Vite: SPA CRUD

Login Form and First Authentication

Summary of this lesson:
- Building login form with Vue
- Creating authentication composable
- Implementing Laravel Sanctum authentication
- Handling login validation errors

In this lesson, we will implement the login form and authenticate the user.

login validation error


Login form

So, first the login form.

resources/js/components/Auth/Login.vue:

<template>
<form @submit.prevent="submitLogin">
<!-- Email -->
<div>
<label for="email" class="block font-medium text-sm text-gray-700">
Email
</label>
<input v-model="loginForm.email" id="email" type="email" class="block mt-1 w-full rounded-md shadow-sm border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" required autofocus autocomplete="username">
<!-- Validation Errors -->
<div class="text-red-600 mt-1">
<div v-for="message in validationErrors?.email">
{{ message }}
</div>
</div>
</div>
 
<!-- Password -->
<div class="mt-4">
<label for="password" class="block font-medium text-sm text-gray-700">
Password
</label>
<input v-model="loginForm.password" id="password" type="password" class="block mt-1 w-full rounded-md shadow-sm border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" required autocomplete="current-password">
<!-- Validation Errors -->
<div class="text-red-600 mt-1">
<div v-for="message in validationErrors?.password">
{{ message }}
</div>
</div>
</div>
 
<!-- Remember me -->
<div class="block mt-4">
<label class="flex items-center">
<input type="checkbox" name="remember" v-model="loginForm.remember" class="rounded border-gray-300 text-indigo-600 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
<span class="ml-2 text-sm text-gray-600">Remember me</span>
</label>
</div>
 
<!-- Buttons -->
<div class="flex items-center justify-end mt-4">
<button class="inline-flex items-center px-4 py-2 bg-gray-800 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-gray-700 active:bg-gray-900 focus:outline-none focus:border-gray-900 focus:shadow-outline-gray transition ease-in-out duration-150 ml-4"
:class="{ 'opacity-25': processing }"
:disabled="processing"
>
</div>
</form>
</template>
 
<script setup>
import useAuth from '@/composables/auth';
 
const { loginForm, validationErrors, processing, submitLogin } = useAuth()
</script>

Nothing special about the form itself. When submitted, we will call the submitLogin method, and all fields are binded using the v-model directive.

Now we need to create a new Composable for Auth and implement all the authentication login in it.

resources/js/composables/auth.js:

import { ref, reactive } from 'vue'
import { useRouter } from "vue-router";
 
export default function useAuth() {
const processing = ref(false)
const validationErrors = ref({})
const router = useRouter()
const loginForm = reactive({
email: '',
password: '',
remember: false
})
 
const submitLogin = async () => {
if (processing.value) return
 
processing.value = true
validationErrors.value = {}
 
axios.post('/login', loginForm)
.then(async response => {
loginUser(response)
})
.catch(error => {
if (error.response?.data) {
validationErrors.value = error.response.data.errors
}
})
.finally(() => processing.value = false)
}
 
const loginUser = (response) => {
localStorage.setItem('loggedIn', JSON.stringify(true))
router.push({ name: 'posts.index' })
}
 
return { loginForm, validationErrors, processing, submitLogin }
}

So, what do we do here? The structure and the variables are the same as we have in posts Composable except the loginForm where we bind it to the input in the form with the v-model.

Next, the submit action submitLogin. The processing indicator and the validation errors implementation are the same as we did for the posts form. The only difference here after successful authentication we call the loginUser method.

In the loginUser method we set the loggedIn variable in the local storage to true and redirect to the posts list page.


Login on the Back-end

Now, we need to implement the backend part. For this, we will modify controller that came from the Laravel Breeze.

app/Http/Controllers/Auth/AuthenticatedSessionController.php:

use Symfony\Component\HttpFoundation\JsonResponse;
 
class AuthenticatedSessionController extends Controller
{
// ...
public function store(LoginRequest $request): RedirectResponse
public function store(LoginRequest $request): RedirectResponse|JsonResponse
{
$request->authenticate();
 
$request->session()->regenerate();
 
if ($request->wantsJson()) {
return response()->json($request->user());
}
 
return redirect()->intended(route('dashboard', absolute: false));
return redirect()->intended();
}
// ...
}

In the controller, we check if the request wants JSON which means it comes from Vue.js. If so, we return the user as a JSON.

And we need to add the /login route to the routes file.

routes/web.php:

Route::post('login', [\App\Http\Controllers\Auth\AuthenticatedSessionController::class, 'store']);
 
Route::view('/{any?}', 'dashboard')
->where('any', '.*');

Now if you try to log in with bad credentials, you should see a validation message.

login validation error

But with the correct credentials, you should be redirected to the posts list page!

Previous: Two Layouts: Authenticated and Guest
avatar

How secure is it to store and check for a auth user this way?

localStorage.setItem('loggedIn', JSON.stringify(true))

Shouldn't we be storing/checking for a bearer token?

avatar

How secure is it to store and check for a auth user this way?

as long as you do not have XSS vulnerabilities. same goes for everything else, not only localStorage.

Shouldn't we be storing/checking for a bearer token?

Bearer token is set after you login, and is checked on the backend.

avatar

and as for bearer token, see the next lesson

avatar

There3 is no security risk here. Since we only store the information that we are logged in at the backend. If someone wants to access a restricted area of your Vue frontend, they always find a way - it is just a javascript applicatiion in the users browser. The important thing here is to protect the data in the backend, which is still protected.

avatar
You can use Markdown
avatar

I think you somehow forgot the script section in Login.vue file... Can you please take a look at that?

👍 3
avatar

is not there @David Lun

avatar
You can use Markdown
avatar

This is the script setup I used in Login.vue

<script setup>

import useAuth from "@/composables/auth.js";

const { loginForm, validationErrors, processing, submitLogin } = useAuth()

</script>
avatar

lesson is updated to include that part

avatar
You can use Markdown
avatar

i have a question in the loginUser function i can save the token of the user in local storage instead of "loggedIn" item ?

avatar
You can use Markdown
avatar

In the Intro you state that you only use breeze for its visual tools and we will not use it in the authentication section. Then after going through the whole course, you show us the modifications we have to do on the breeze authentication Controller - which I haven't, since I didn't think I'd need breeze. How much DO you rely on breeze functionality?

avatar

It's been some time since this course was written so don't remember exactly now. You could just copy the controller code from breeze and modify it. As I can see in the source code breeze controllers are used only for loggin in and logging out user.

avatar

Then just create that file with this one method.

avatar
You can use Markdown
avatar

Hello, I think there is something missing or broken in the <button> element in Login.vue file

avatar

Will need more

avatar
You can use Markdown
avatar
You can use Markdown