I want to create auth system in Nextjs with Laravel sanctum. I have faced problem to check if token is valid or no. Here my code in Nextjs middelaware, he is only check if token exist. so anyone can create token manualy in browser and will be redirect to dashboard.
I'dont know if this method its safe? or it's not good btw or if there is another way.
Thank you for your help
Middelware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
function getToken(req: NextRequest): string | undefined {
const { cookies } = req
return cookies.get('token')
}
export function middleware(request: NextRequest) {
const token = getToken(request)
if (request.nextUrl.pathname.startsWith('/dashboard') && !token) {
return NextResponse.redirect(new URL('/', request.url))
}
if (request.nextUrl.pathname.startsWith('/login') && token) {
return NextResponse.redirect(new URL('/dashboard', request.url))
}
}
Login.js :
import {useState} from 'react';
import axios from 'axios';
import { setCookie } from 'cookies-next';
import {useRouter} from 'next/router'
export default function Login () {
const router = useRouter()
let [ email, setEmail ] = useState('');
let [ password, setPassword ] = useState('');
const handleSubmit = async (e) =>{
e.preventDefault();
axios.get('http://127.0.0.1:8000/sanctum/csrf-cookie')
.then(response => {
axios.post('http://127.0.0.1:8000/api/login', {
email: email,
password: password
}).then(response => {
setCookie('token', response.data.token);
router.push("/dashboard");
})
});
}
Logincontroller :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
class LoginController extends Controller
{
/**
* Handle an authentication attempt.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function authenticate(Request $request)
{
$request->validate([
'email' => 'required|email',
'password' => 'required',
]);
$user = User::where('email', $request->email)->first();
if (!$user || !Hash::check($request->password, $user->password)) {
throw ValidationException::withMessages([
'email' => ['The provided credentials are incorrect.'],
]);
}
$token = $user->createToken('mytoken')->plainTextToken;
$response = [
'token' => $token,
'token_type' => 'Bearer',
'user' => $user,
];
return $response;
}
}
Just use the auth:sanctum
middleware in your route.
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Details: https://laravel.com/docs/9.x/sanctum#protecting-routes
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.