我关注了Laravel官方文档以及以下文章 https://medium.com/techcompose/create-rest-api-in-laravel-with-authentication-using-passport-133a1678a876
注册工作正常并返回令牌 登录正常并返回令牌 但是当我按以下方式使用它时,未经身份验证。
curl -X POST \
http://api.local/api/details \
-H 'Accept: application/json' \
-H 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjY0YmE0ZTUxMzBhYWQwYzdmZWVkODRhYTZhNzI4YjE2YjE1NWJhYzA0YmQwMmIxYWZjMGU3NTVjYzk1Y2QwYzY3ZWMzNTRlNzA1MTg0YjY4In0.eyJhdWQiOiIxIiwianRpIjoiNjRiYTRlNTEzMGFhZDBjN2ZlZWQ4NGFhNmE3MjhiMTZiMTU1YmFjMDRiZDAyYjFhZmMwZTc1NWNjOTVjZDBjNjdlYzM1NGU3MDUxODRiNjgiLCJpYXQiOjE1Mzc4NzIxNjcsIm5iZiI6MTUzNzg3MjE2NywiZXhwIjoxNTY5NDA4MTY3LCJzdWIiOiIwIiwic2NvcGVzIjpbXX0.GHGKOiWm_8gr4Hib0ZtCq_FdQSDAntPl2zPIHkkTfTien1PHCoE79S7MdZRdEhjxt5Ds5E2JXhajfa9rDfiXHzKGtmzcRD_VYYxKnWupnhiMlJeHJsmXaWKLjYIw3InQYZtV_cYdcXlYWTDWcCOR1Xr7ezkYECz16oOumtgarPxVRZTHehpj4WiRDDgB4VTRZiRfsHYxMruh55wuT8OkbUAOalRaqwwxfplLYwdfTAcu4vUdwPfswu2_eZ6l1b_8Jd8Jsk5niXROQ7pIAL1oYX0V_HbNz9YkrlbiZN-w9FoM3fMZpYL7hcg1Jcocd7dGPUkcGaMOMjjcRuj5XAKEJOZbQlxs0n5wo4W3Sz11bnO4dRetTj9hyF97QDoaHFduPj4tnn6lItRbBGjQTGy_5qNlckhXxRYTlsYUZ6oNUUU2bUV_hBdklYRCtWgY1DY-Ds0DVhuujea9_u0w0swDwRh5VlV_gQaKEO0sEv-fzg_23UdPpfHgaG8-NHTYs5LsRSNS1iz4hpXuTjZzUOBsAk_k-V13wjeeXElLxy2PgN5s87IVJPEvDtd5F89PjzvaDHM5wsYwmUlnCnzBa8ZEtG8Wj62qBY_RooBmSNzWlT62SpJDbs25GaWOf8y7EtuICcuaOg7bMoGICKJc4GmkK_ltk-M7WieJD95InnWBJ-E'
返回
{
"error": "Unauthenticated."
}
路线:
Route::post('login', 'API\UserController@login');
Route::post('register', 'API\UserController@register');
Route::group(['middleware' => 'auth:api'], function(){
Route::post('details', 'API\UserController@details');
});
AuthServiceProvider:
public function boot()
{
$this->registerPolicies();
Passport::routes();
Passport::tokensExpireIn(Carbon::now()->addYear(21));
Passport::refreshTokensExpireIn(Carbon::now()->addYear(30));
}
config / auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
任何想法,为什么/ details请求没有通过有效令牌传递给自发事件?
答案 0 :(得分:1)
那里的一切对我来说都很好。我唯一建议的是,您需要在.htaccess重写规则中添加以下内容(假设您使用的是Apache)。
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
对于nginx,您可以尝试
proxy_set_header HTTP_AUTHORIZATION $http_authorization;
此外,我刚刚注意到您的oauth_access_tokens
行不包含用户ID。
确保您的登录名包含以下内容:
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
$user = Auth::user();
$token = $user->createToken('MyApp')->accessToken;
$status = 200;
}
else{
$error = "Unauthorised";
$status = 401;
}
return {your json response}