是的你可以。例如,这是我使用 JWT 和 Sentinel 进行 API 休息的代码。您可以使用 Sentinel 为您的数据库播种:
创建角色
示例 EXA 角色
$role = \Sentinel::getRoleRepository()->createModel()->create([
'name' => 'Example',
'slug' => 'EXA',
]);
$role->permissions = [
'servicio_dash' => true,
'servicio_widget' => true,
];
$role->save();
用户角色 USR
$role = \Sentinel::getRoleRepository()->createModel()->create([
'name' => 'User',
'slug' => 'USR',
]);
$role->permissions = [
'servicio_dash' => true,
'servicio_widget' =>false,
];
$role->save();
创建 50 个用户并指定 EXA 角色(使用 faker)
$usr_role = \Sentinel::findRoleBySlug('EXA');
factory(App\User::class, 50)->make()->each(function ($u) use ($usr_role) {
\Sentinel::registerAndActivate($u['attributes']);
});
奖励曲目:工厂示例
$factory->define(App\User::class, function (Faker\Generator $faker) {
return [
'email' => $faker->safeEmail,
'password' => 'p4ssw0rd',
'first_name' => $faker->firstName,
'last_name' => $faker->lastName,
'recycle' => false,
'phone' => $faker->phoneNumber,
'alt_email' => $faker->email
];
});
只有一个用户
$yo = factory(App\User::class)->make(['email' => 'jpaniorte@openmailbox.org']);
\Sentinel::registerAndActivate($yo['attributes']);
$jperez = User::where('email', 'jpaniorte@openmailbox.org')->firstOrFail();
$epa_role->users()->attach($jperez);
为 API REST 验证控制器
public function authenticateCredentials(Request $request)
{
$credentials = $request->only('email', 'password');
$user = \Sentinel::authenticate($credentials);
return response()->json($user);
}
使用令牌(使用 JWT)和哨兵进行身份验证
public function authenticate(Request $request)
{
// grab credentials from the request
$credentials = $request->only('email', 'password');
try {
// attempt to verify the credentials and create a token for the user
if (!$token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
// something went wrong whilst attempting to encode the token
return response()->json(['error' => 'could_not_create_token'], 500);
}
// all good so return the token
return response()->json(compact('token'));
}
注意:为此,您需要使用自定义身份验证提供程序配置 JWT 选项,您可以在此处找到此内容
在任何控制器中
public function hasPermission($type)
{
//$sentinel = \Sentinel::findById(\JWTAuth::parseToken()->authenticate()->id); //->this is for a token
$sentinel = \Sentinel::findById(1); //if you now the id
if($sentinel->hasAccess([$type]))
return response()->json(true, 200);
//yout custom handle for noAccess here
}