编程语言
首页 > 编程语言> > php-Lravel 5.4:在两个表上具有多重身份验证的JWT API一个有效,另一个无效

php-Lravel 5.4:在两个表上具有多重身份验证的JWT API一个有效,另一个无效

作者:互联网

我在用…

> Laravel 5.4
> tymon / jwt-auth:1.0.0-rc.2

我有两个身份验证API的应用程序,一个是客户,另一个是驱动程序,每个驱动程序都有自己的表.

现在让我简要介绍一下JWT软件包的安装以及我对此所做的更新.

>我完全按照JWT文档中的说明安装了软件包.
>现在来到quick start了,这里我更新了两个模型,一个是用户,第二个是驱动程序.
>再次来到“配置身份验证”保护区我使用了两个保护区的配置,让我显示了auth.php的快照.

'defaults' => [
    'guard'     => 'api',
    'passwords' => 'users',
], 

'guards' => [
        'web' => [
            'driver'   => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver'   => 'jwt',
            'provider' => 'users',
        ],

        'driver'    => [
            'driver'   => 'session',
            'provider' => 'drivers',
        ],

        'driver-api' => [
            'driver'   => 'jwt',
            'provider' => 'drivers',
        ],
    ],

'providers' => [
        'users'     => [
            'driver' => 'eloquent',
            'model'  => App\Models\User::class,
        ],

        'drivers'   => [
            'driver' => 'eloquent',
            'model'  => App\Models\Driver::class,
        ],
    ],

>现在继续使用身份验证路由的应用程序,这是我对两个模型的路由

这是用户和驱动程序路线

Route::group( [
    'prefix'     => 'auth',
    'middleware' => 'api'
], function () {
    .......
});

Route::group( [
    'prefix'     => 'driver',
    'middleware' => 'api'
], function () {
   .......
});

>现在是AuthController

在JWT文档中,构造就是这样写的.

public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login']]);
    }

我找到了一些文章,建议做这样的事情来在我们拥有的两个模型之间切换.

所以我的控制器在这里看起来像现在.

public function __construct() {
        $this->user   = new User;
        $this->driver = new Driver;
    }

public function userLogin( Request $request ) {
        Config::set( 'jwt.user', 'App\Models\User' );
        Config::set( 'auth.providers.users.model', User::class );
        $credentials = $request->only( 'email', 'password' );
        $token       = null;
        try {
            if ( $token = $this->guard()->attempt( $credentials ) ) {
                return response()->json( [
                    'response' => 'error',
                    'message'  => 'invalid_email_or_password',
                ] );
            }
        } catch ( JWTAuthException $e ) {
            return response()->json( [
                'response' => 'error',
                'message'  => 'failed_to_create_token',
            ] );
        }

        return response()->json( [
            'response' => 'success',
            'result'   => [
                'token'   => $token,
                'message' => 'I am front user',
            ],
        ] );
    }

    public function driverLogin( Request $request ) {
        Config::set( 'jwt.user', 'App\Models\Driver' );
        Config::set( 'auth.providers.users.model', Driver::class );
        $credentials = $request->only( 'email', 'password' );
        $token       = null;
        try {
            if ( ! $token = $this->guard()->attempt( $credentials ) ) {
                return response()->json( [
                    'response' => 'error',
                    'message'  => 'invalid_email_or_password',
                ] );
            }
        } catch ( JWTAuthException $e ) {
            return response()->json( [
                'response' => 'error',
                'message'  => 'failed_to_create_token',
            ] );
        }

        return response()->json( [
            'response' => 'success',
            'result'   => [
                'token'   => $token,
                'message' => 'I am driver user',
            ],
        ] );
    }

public function me() {
        return response()->json( $this->guard()->user() );
    }

public function logout() {
        $this->guard()->logout();

        return response()->json( [ 'message' => 'Successfully logged out' ] );
    }

public function refresh() {
        return $this->respondWithToken( $this->guard()->refresh() );
    }

protected function respondWithToken( $token ) {
        return response()->json( [
            'access_token' => $token,
            'token_type'   => 'bearer',
            'expires_in'   => $this->guard()->factory()->getTTL() * 60
        ] );
    }

public function guard() {
        return Auth::guard();
    }  

Now with is happening and the problems I faced

现在,驱动程序api仅用作登录Ex.

本地主机:8000 / api / driver / login工作正常

但是当尝试像这样获取驱动程序用户标识时

本地主机:8000 / api / driver / me它返回空数组

Second Issue comes.

从Ex界面的使用登录. http:// localhost:8000 / login,它会返回到登录屏幕而没有任何错误,因为登录信息是正确的,但是如果我将其更改为’guard’,则auth.php中的默认值为’guard’=>’api’ ‘=>’web’可以正确登录.

甚至Ex的User API.本地主机:8000 / api / auth / login总是返回

{
    "response": "error",
    "message": "invalid_email_or_password"
}

更新资料

I solved half the way
I updated the AuthController to be something like this.

public function __construct() {
        if ( Request()->url() == '/api/driver/me' ) {
            $this->middleware( 'auth:driver-api', [ 'except' => [ 'login' ] ] );
        } elseif ( Request()->url() == '/api/customer/me' ) {
            $this->middleware( 'auth:api', [ 'except' => [ 'login' ] ] );
        }
    }

和登录功能是这样的.

public function login() {
        if ( Request()->url() == '/api/driver' ) {
            Config::set( 'auth.providers.users.model', Driver::class );
            $credentials = request( [ 'email', 'password' ] );

            if ( ! $token = auth()->attempt( $credentials ) ) {
                return response()->json( [ 'error' => 'Unauthorized' ], 401 );
            }

            return $this->respondWithToken( $token );
        }

        Config::set( 'auth.providers.users.model', User::class );
        $credentials = request( [ 'email', 'password' ] );

        if ( ! $token = auth()->attempt( $credentials ) ) {
            return response()->json( [ 'error' => 'Unauthorized' ], 401 );
        }

        return $this->respondWithToken( $token );

    }

但是仍然在auth.php中有问题

'defaults' => [
        'guard'     => 'driver-api',
        'passwords' => 'users',
    ], 

在这里,如果URL请求是localhost:8000 / api / driver / login和’guard’=&gt ;,我需要将’guard’=>’api’切换为’guard’=>’driver-api’.如果网址请求是localhost:8000 / api / customer / login,则使用“ api”来执行此操作.

更新2

这是驱动程序模型

use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Driver extends Authenticatable implements JWTSubject {
    protected $guard = 'driver';

    protected $fillable = [
        ...
        'email',
        'password',
        ...
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    public function getJWTIdentifier() {
        return $this->getKey();
    }

    public function getJWTCustomClaims() {
        return [];
    }
}

和用户模型

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject {
    use Notifiable;

    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    public function getJWTIdentifier() {
            return $this->getKey();
        }

        public function getJWTCustomClaims() {
            return [];
        }

我需要一些帮助,请给我一些想法.

解决方法:

我在jwt中使用多重身份验证的示例

我有2个型号:
1.用户
2.管理员

路线:

Route::post('auth/userlogin', 'ApiController@userLogin');
Route::post('auth/adminlogin', 'ApiController@adminLogin');

控制器:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests;
use Config;
use JWTAuth;
use JWTAuthException;
use App\User;
use App\Admin;

class ApiController extends Controller
{

    public function __construct()
    {
        $this->user = new User;
        $this->admin = new Admin;
    }

    public function userLogin(Request $request){
        Config::set('jwt.user', 'App\User'); 
        Config::set('auth.providers.users.model', \App\User::class);
        $credentials = $request->only('email', 'password');
        $token = null;
        try {
            if (!$token = JWTAuth::attempt($credentials)) {
                return response()->json([
                    'response' => 'error',
                    'message' => 'invalid_email_or_password',
                ]);
            }
        } catch (JWTAuthException $e) {
            return response()->json([
                'response' => 'error',
                'message' => 'failed_to_create_token',
            ]);
        }
        return response()->json([
            'response' => 'success',
            'result' => [
                'token' => $token,
                'message' => 'I am front user',
            ],
        ]);
    }

    public function adminLogin(Request $request){
        Config::set('jwt.user', 'App\Admin'); 
        Config::set('auth.providers.users.model', \App\Admin::class);
        $credentials = $request->only('email', 'password');
        $token = null;
        try {
            if (!$token = JWTAuth::attempt($credentials)) {
                return response()->json([
                    'response' => 'error',
                    'message' => 'invalid_email_or_password',
                ]);
            }
        } catch (JWTAuthException $e) {
            return response()->json([
                'response' => 'error',
                'message' => 'failed_to_create_token',
            ]);
        }
        return response()->json([
            'response' => 'success',
            'result' => [
                'token' => $token,
                'message' => 'I am Admin user',
            ],
        ]);
    }
}

希望对您有帮助.

标签:laravel-5-4,laravel,authentication,jwt,php
来源: https://codeday.me/bug/20191025/1927625.html