laravel sanctum jwt code example

Example 1: laravel sanctum vs jwt

1. Passport : Passport provides a full OAuth2 server implementation for your 
  Laravel application in a matter of minutes. It is therefore necessary to have
  a brief knowledge of OAuth2.

2. Sanctum : Sanctum it is a simple package to issue API tokens to your users
  without the complication of OAuth. Sanctum uses Laravel's built-in cookie
  based session authentication services.

In a small application use Sanctum. it's simple and easy

3. JWT : Auth (Authentication) is the process of identifying the user 
credentials. In web applications, authentication is managed by sessions which
take the input parameters such as email or username and password, for user
identification. If these parameters match, the user is said to be authenticated.

Example 2: laravel sanctum vs jwt

If using sanctum. The implementation will be as follows : 

For WEB

For web you dont need the token explicitly the sanctum/csrf-token handles 
everything for you. In case of web make sure you are allowing credentials for 
example:

In Axios axios.defaults.withCredentials = true;

In JavaScript: xhr.withCredentials = true;.

For Mobile authentication

For mobile authentication, you dont need to call sanctum/csrf-cookie API.

Please refer to the official doc section "Mobile Application Authentication".

https://laravel.com/docs/7.x/sanctum#mobile-application-authentication.

General flow will be as follows:

1. Make a login API and make sure you are not using auth: sanctum middleware
  with this.
2. Call the login API and validate user credentials and return a token on 
  success. You can refer following code:
   /**
     * Get a Token via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login()
    {
        $credentials = request()->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);
        
        $user = User::where('email', $credentials['email'])->first();
        
        if (! $user || ! Hash::check($credentials['password'], $user->password)) {
            return response()->json(['message' => 'Unauthorized'], 401);
        }
        
        return $this->respondWithToken($user->createAccessToken(), ["user" => $user]);
    }
3. The user object has createToken() method to issue a token.

4. Now use this token with every request your making to the routes having 
  auth:sanctum middleware attached to itself.
5. You need to add 'Authorization' => 'Bearer '. $access_token header in the
    request headers.

Example 3: laravel sanctum

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

Route::post('/sanctum/token', function (Request $request) {
    $request->validate([
        'email' => 'required|email',
        'password' => 'required',
        'device_name' => '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.'],
        ]);
    }

    return $user->createToken($request->device_name)->plainTextToken;
});

Tags:

Php Example