laravel dingo/api添加jwt-auth认证
2021-03-30 08:27
标签:parse nat tps pac dashboard 开放 name soscw 调用 前面我们学了laravel dingo/api创建简单的api,这样api是开放给所有人的,如何查看和限制api的调用呢?可以用jwt-auth来验证,JSON Web Token Authentication 1,首先安装jwt-auth插件,在命令行中用composer安装 2,然后发布 在/config/生成了一个jwt.php文件 3,生成key 如果命令无法运行,可以在/config/jwt.php文件中修改changeme为自己设置的密匙 4,修改/app/Api/Controllers/HelloController.php为 5,添加路由(/routes/web.php) 6,测试路由:php artisan api:routes,如果出现如下提示表示正确 访问url:***.com/api/auth显示错误,因为没加token 重新修改hellocontrol和loutes 用谷歌浏览器postman插件获取token,注意是post方法,步骤如下图所示 将获取的token复制,黏贴到第二步的用户验证token中,下图5中就是我们刚刚注册的用户 laravel dingo/api添加jwt-auth认证 标签:parse nat tps pac dashboard 开放 name soscw 调用 原文地址:https://www.cnblogs.com/ytkah/p/9281833.htmlcomposer require tymon/jwt-auth ‘0.5.*‘
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"
php artisan jwt:generate
‘secret‘ => env(‘JWT_SECRET‘, ‘changeme‘),
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‘));
}
}
$api->post(‘auth‘, ‘App\Api\Controllers\HelloController@authenticate‘);
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‘));
}
//添加user
public function user()
{
JWTAuth::parseToken();
$user = JWTAuth::parseToken()->authenticate();
return $user;
}
}
name(‘home‘);
$api = app(‘Dingo\Api\Routing\Router‘);
$api->version(‘v1‘, function ($api) {
$api->get(‘helloworld‘, ‘App\Api\Controllers\HelloController@index‘);
$api->post(‘auth‘, ‘App\Api\Controllers\HelloController@authenticate‘);
$api->get(‘auth‘, ‘App\Api\Controllers\HelloController@user‘);
});
上一篇:C# 简介
文章标题:laravel dingo/api添加jwt-auth认证
文章链接:http://soscw.com/essay/69914.html