Authentication with JWT Laravel 5 without password

后端 未结 3 626
陌清茗
陌清茗 2021-02-05 09:17

I\'m trying to learn Laravel and my goal is to be able to build a RESTful API (no use of views or blade, only JSON results. Later, an AngularJS web app and a Cordova hybrid mobi

相关标签:
3条回答
  • 2021-02-05 09:47

    try with this:

    $user=User::where('email','=','user2@gmail.com')->first();
    
    if (!$userToken=JWTAuth::fromUser($user)) {
                return response()->json(['error' => 'invalid_credentials'], 401);
            }
    
    return response()->json(compact('userToken'));
    

    it works for me, hope can help

    0 讨论(0)
  • 2021-02-05 10:00

    Rather than making a different login strategy for customers and moderators, you can add token authentication to both user type. this will makes your life easier and prepare for scalability. In your api, you can just restrict moderator users to not have access to the api by sending

    <?php
    Response::json('error'=>'method not allowed')

    Apart from this suggestion, I believe @Alimnjan code should work.

    0 讨论(0)
  • 2021-02-05 10:03

    Generating token for the customers (without password) can be achieved through

    $user = \App\Modules\User\Models\UserModel::whereEmail('xyz@gmail.com')->first();
    $userToken=JWTAuth::fromUser($user);
    

    Here $userToken will stores the token after existence check of email in the table configured in UserModel file.

    I have assumed that you stores both customer and moderators in the same table, there must be some flag to discriminate among them. Assume the flag is user_type

    $token = null;
    $user = \App\Modules\User\Models\UserModel::whereEmail('xyz@gmail.com')->first();
    if($user['user_type'] == 'customer'){
       $credentials = $request->only('email');
       $token =JWTAuth::fromUser($user);
    }else if($user['user_type'] == 'moderator'){
       $credentials = $request->only('email','password');
       $token = JWTAuth::attempt($credentials);
    }else{
       //No such user exists
    
    }
    return $token;
    

    As far as custom claims are concerned these are custom defined payloads which can be attached to token string.

    For example, JWTAuth::attempt($credentials,['role'=>1]); Will attempt to add role object to token payload. Once you decode the token string through JWT Facade JWTAuth::parseToken()->getPayload(); you in turn get all payloads defined in required_claims under config/jwt.php with additional role payload.

    Refer https://github.com/tymondesigns/jwt-auth/wiki/Creating-Tokens#creating-a-token-based-on-anything-you-like Let me know in case you requires anything else.

    0 讨论(0)
提交回复
热议问题