Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/244.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel同时使用两个api级别,彼此分开_Php_Laravel_Api - Fatal编程技术网

Php Laravel同时使用两个api级别,彼此分开

Php Laravel同时使用两个api级别,彼此分开,php,laravel,api,Php,Laravel,Api,我正在尝试使用laravel创建API应用程序。 我想使用两个级别的系统:普通api和客户api。 这意味着标准api路由正在由普通守卫(用户)使用用户模型进行身份验证,而客户api路由正在由不同守卫(客户)使用客户模型进行身份验证。 现在的问题是,每当我登录到customers api并检索令牌时,该令牌也可以用来访问我不想要的普通api 我创建了一个中间件来记录auth用户,它显示了这两个模型,但只显示了应该登录的客户 场景如下:我登录到客户登录路由,然后尝试从普通api和客户api访问路由

我正在尝试使用laravel创建API应用程序。
我想使用两个级别的系统:普通api和客户api。
这意味着标准api路由正在由普通守卫(用户)使用用户模型进行身份验证,而客户api路由正在由不同守卫(客户)使用客户模型进行身份验证。
现在的问题是,每当我登录到customers api并检索令牌时,该令牌也可以用来访问我不想要的普通api

我创建了一个中间件来记录auth用户,它显示了这两个模型,但只显示了应该登录的客户

场景如下:我登录到客户登录路由,然后尝试从普通api和客户api访问路由,它记录路由的模型,但模型不同,不应访问默认用户

每当我转到:/api/v1/user role/all(普通api)
(我从日志中删除了私有数据)

当我转到:/api/v1/customer/customer/paginate(客户端)时

用户模型:

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;
    use SoftDeletes { restore as private restoreSoftDeletes; }
    use EntrustUserTrait { restore as private restoreEntrustUserTrait; }

    protected $guard = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'username', 'email', 'password','active', 'firstname', 'lastname',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that are dates.
     *
     * @var array
     */
     protected $dates = [
         'created_at', 'updated_at', 'deleted_at',
     ];
    /**
     * Automatically creates hash for the user password.
     *
     * @param  string  $value
     * @return void
     */
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = Hash::make($value);
    }

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
    public function restore()
    {
      $this->restoreSoftDeletes();
      $this->restoreEntrustUserTrait();
    }

    public function roles()
    {
      return $this->belongsToMany('App\Models\User\Role', 'role_user');
    }
    
    public function ServiceRequests()
    {
      return $this->hasMany('App\Models\ServiceRequest');
    }

    public function followUpRequests()
    {
        return $this->hasMany('App\Models\ServiceRequest', 'requested_by');
    }

    public function isAdmin()
    {
      return $this->roles()->where('name', 'admin')->exists();
    }
}
客户模式:

class Customer extends Authenticatable implements JWTSubject
{
    use Notifiable;
    use SoftDeletes { restore as private restoreSoftDeletes; }
    use EntrustUserTrait { restore as private restoreEntrustUserTrait; }

    protected $guard = 'customers';
    protected $fillable = ['email', 'password','active', 'firstname', 'lastname'];
    protected $dates = ['created_at', 'updated_at', 'deleted_at'];
    protected $hidden = ['password', 'remember_token'];

    public function establishment(){
        return $this->belongsTo(Establishment::class);
    }

    public function company()
    {
        return $this->belongsTo('App\Models\Company');
    }

    public function roles()
    {
        return $this->belongsToMany(Role::class, 'customers_roles');
    }

    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = Hash::make($value);
    }

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

    public function getJWTCustomClaims()
    {
        return [];
    }

    public function restore()
    {
        $this->restoreSoftDeletes();
        $this->restoreEntrustUserTrait();
    }

    public function isAdmin()
    {
        return $this->roles()->where('name', 'admin')->exists();
    }
}
config/auth.php:

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

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

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session", "token"
    |
    */

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

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

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

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

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
        ],
        'customers' => [
            'provider' => 'customers',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],

];
routes/customers-api.php

$api = app(Router::class);

$api->version('v1', function (Router $api) {
    $api->group(['prefix' => 'v1'], function(Router $api) {
        $api->group(['prefix' => 'customer'], function(Router $api) {
            $api->group(['prefix' => 'auth'], function (Router $api) {
                $api->post('signup', 'App\\Api\\V1\\Controllers\\Auth\\SignUpController@signUp');
                $api->post('login', 'App\\Api\\V1\\Customer\\Controllers\\Auth\\LoginController@login');

                $api->post('forgot-password', 'App\\Api\\V1\\Customer\\Controllers\\Auth\\ForgotPasswordController@sendResetEmail');
                $api->post('recovery', 'App\\Api\\V1\\Customer\\Controllers\\Auth\\ForgotPasswordController@sendResetEmail');

                $api->post('reset', 'App\\Api\\V1\\Controllers\\Auth\\ResetPasswordController@resetPassword');

                $api->post('logout', 'App\\Api\\V1\\Controllers\\Auth\\LogoutController@logout');
                $api->post('refresh', 'App\\Api\\V1\\Controllers\\Auth\\RefreshController@refresh');

            });

            $api->group(['middleware' => ['assign.guard:customers','jwt.auth']], function (Router $api) {
                //routes
            });
        });
    });
});
customers/LoginController.php

public function login(LoginRequest $request, JWTAuth $JWTAuth)
    {
        $customer = Customer::with(['roles'])->where('email', $request->email)->where('active', 1)->first();
        if ($customer) {
            if (Hash::check($request->password, $customer->password)) {
//                $credentials = $request->only('email', 'password');
                try {
                    $token = Auth()->guard('customers')->attempt(['email' => $request->email, 'password' => $request->password]);

                    if (!$token) {
                        return response()->json([
                            'title' => \Lang::get('app.error'),
                            'message' => \Lang::get('auth.accessDenied')
                        ], 403);
                    } else {
                        return response()->json([
                            'return_value' => true,
                            'title' => \Lang::get('app.success'),
                            'message' => \Lang::get('auth.loginSuccessful'),
                            'token' => $token
                            'user' => $customer,
                            'isAdmin' => $customer->isAdmin()
                        ], 200);
                    }
                } catch (JWTException $e) {
                    // something went wrong whilst attempting to encode the token
                    return response()->json(['error' => 'could_not_create_token'], 500);
                }
            } else {
                return response()->json([
                    'return_value' => false,
                    'title' => \Lang::get('app.error'),
                    'message' => \Lang::get('auth.accessDenied')
                ], 403);
            }
        } else {
            return response()->json([
                'return_value' => false,
                'title' => \Lang::get('app.error'),
                'message' => \Lang::get('auth.accessDenied')
            ], 403);
        }
    }

我认为问题在于,因为您可能正在使用jwt auth包,所以需要特别指出在每个登录控制器中应该使用哪些配置

customers/LoginController.php
@Pehofe86该评论没有帮助我已经尝试过你的解决方案,但它没有解决问题,不能说它不起作用吗?@Pehofe86也许你应该添加更多关于你使用的软件包以及你不同尝试的结果的信息,而不是仅仅写“它不起作用”。我不是你的个人支持代理人。可能是重复的吗?
$api = app(Router::class);

$api->version('v1', function (Router $api) {
  $api->group(['prefix' => 'v1'], function(Router $api) {

    $api->group(['prefix' => 'auth'], function(Router $api) {
        $api->post('signup', 'App\\Api\\V1\\Controllers\\Auth\\SignUpController@signUp');
        $api->post('login', 'App\\Api\\V1\\Controllers\\Auth\\LoginController@login');

        $api->post('forgot-password', 'App\\Api\\V1\\Controllers\\Auth\\ForgotPasswordController@sendResetEmail');
        $api->post('recovery', 'App\\Api\\V1\\Controllers\\Auth\\ForgotPasswordController@sendResetEmail');

        $api->post('reset', 'App\\Api\\V1\\Controllers\\Auth\\ResetPasswordController@resetPassword');

        $api->post('logout', 'App\\Api\\V1\\Controllers\\Auth\\LogoutController@logout');
        $api->post('refresh', 'App\\Api\\V1\\Controllers\\Auth\\RefreshController@refresh');
    });

    $api->group(['middleware' => 'jwt.auth'], function(Router $api) {
        //routes
    });
});
$api = app(Router::class);

$api->version('v1', function (Router $api) {
    $api->group(['prefix' => 'v1'], function(Router $api) {
        $api->group(['prefix' => 'customer'], function(Router $api) {
            $api->group(['prefix' => 'auth'], function (Router $api) {
                $api->post('signup', 'App\\Api\\V1\\Controllers\\Auth\\SignUpController@signUp');
                $api->post('login', 'App\\Api\\V1\\Customer\\Controllers\\Auth\\LoginController@login');

                $api->post('forgot-password', 'App\\Api\\V1\\Customer\\Controllers\\Auth\\ForgotPasswordController@sendResetEmail');
                $api->post('recovery', 'App\\Api\\V1\\Customer\\Controllers\\Auth\\ForgotPasswordController@sendResetEmail');

                $api->post('reset', 'App\\Api\\V1\\Controllers\\Auth\\ResetPasswordController@resetPassword');

                $api->post('logout', 'App\\Api\\V1\\Controllers\\Auth\\LogoutController@logout');
                $api->post('refresh', 'App\\Api\\V1\\Controllers\\Auth\\RefreshController@refresh');

            });

            $api->group(['middleware' => ['assign.guard:customers','jwt.auth']], function (Router $api) {
                //routes
            });
        });
    });
});
public function login(LoginRequest $request, JWTAuth $JWTAuth)
    {
        $customer = Customer::with(['roles'])->where('email', $request->email)->where('active', 1)->first();
        if ($customer) {
            if (Hash::check($request->password, $customer->password)) {
//                $credentials = $request->only('email', 'password');
                try {
                    $token = Auth()->guard('customers')->attempt(['email' => $request->email, 'password' => $request->password]);

                    if (!$token) {
                        return response()->json([
                            'title' => \Lang::get('app.error'),
                            'message' => \Lang::get('auth.accessDenied')
                        ], 403);
                    } else {
                        return response()->json([
                            'return_value' => true,
                            'title' => \Lang::get('app.success'),
                            'message' => \Lang::get('auth.loginSuccessful'),
                            'token' => $token
                            'user' => $customer,
                            'isAdmin' => $customer->isAdmin()
                        ], 200);
                    }
                } catch (JWTException $e) {
                    // something went wrong whilst attempting to encode the token
                    return response()->json(['error' => 'could_not_create_token'], 500);
                }
            } else {
                return response()->json([
                    'return_value' => false,
                    'title' => \Lang::get('app.error'),
                    'message' => \Lang::get('auth.accessDenied')
                ], 403);
            }
        } else {
            return response()->json([
                'return_value' => false,
                'title' => \Lang::get('app.error'),
                'message' => \Lang::get('auth.accessDenied')
            ], 403);
        }
    }
function __construct()
{
    Config::set('jwt.user', Customer::class);
    Config::set('auth.providers', [
        'users' => [
             'driver' => 'eloquent',
             'model' => Customer::class
        ]
    ]);
}