Answers for "laravel sanctum vs jwt"

PHP
1

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.
Posted by: Guest on August-21-2020

Browse Popular Code Answers by Language