How get access token after autorization laravel sanctum?

6.3k Views Asked by At

Hello i'm newbie in laravel. I use for authorization sanctum. But i want that some request can available for authorization user (i use laravel for only api, on front i use angular 2). web.php:

Route::group(['middleware' => ['auth:sanctum']], function () {
    Route::post('api/user-information', function(Request $request) {
       return response()->json([ auth()->user()]);
    });

    // API route for logout user
    Route::post('api/logout', [AuthController::class, 'logout']);
});

How can I get access token after success autorization user that i can send request for middleware routes. Because if i have request withous access token i always send null in 'api/user-information'. Please help me resolve this problem.

2

There are 2 best solutions below

0
On

You could better make a new function in a controller, probably the AuthController. In this function you can validate fields

$validatedData = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required'],
        ]);

With the validated data you can use Auth::login($validatedData);

Source: https://laravel.com/docs/9.x/authentication#login-throttling

0
On

Welcome to Laravel! I am assuming you have login method that authenticates user. You can create a token in that method and pass it to your frontend.

public function login(Request $request)
{
    $request->validate([
        'email' => 'required|email',
        'password' => 'required',
    ]);

    $user = User::where('email', $request->email)->first();

    if (! $user || ! Hash::check($request->password, $user->password)) {
       return ['status'=>0,'message'=>'Invalid Credentials','data'=>[]];
    }
    $data = [
        'user'=>$user,
        'token'=>$user->createToken('MyToken')->plainTextToken
    ];
    return ['status'=>1, 'message'=>'Login Successful!', 'data'=>$data];
}

If you just need to pass the token, you can simply return token in the response and then pass it in request header (Authorization) of your Angular applcation to access the API routes protected by Sanctum middleware auth:sanctum

return $user->createToken('MyToken')->plainTextToken; 

Also since you are going to use Laravel for API, I would suggest you put all your routes in routes/api.php file.

The routes in routes/api.php are stateless and are assigned the api middleware group. The prefix '/api' is applied to all the routes defined in api.php

You can read more about it in Laravel Documentation

Issuing API Tokens

The Default Route Files