简体   繁体   English

如何在 laravel api 中使用护照获取用户 ID?

[英]How can i get user id using passport in laravel api?

i am trying to retrieve user ID using auth我正在尝试使用 auth 检索用户 ID

what i have tried so far:到目前为止我已经尝试过:

public function testfun()
{
    $id = Auth::user()->id;
    return $id;
}

it return:它返回:

ErrorException: Attempt to read property "id" on null

i tried:我试过:

public function testfun(Request $request)
{
    return Auth::user()->id;
}

i got the same error我有同样的错误

i tried to place the API within the middleware:我试图将 API 放在中间件中:

Route::group(['middleware' => 'auth:api'], function() {
Route::get('testapi', [RegisterController::class, 'testfun']);
});

and call it with guard:并用警卫称呼它:

public function testfun(Request $request)
{
    return auth('api')->user();
}

i got:我有:

Symfony\Component\Routing\Exception\RouteNotFoundException: Route [/login] not defined.

here is the full Route of API:这是 API 的完整路线:

Route::group(['prefix' => 'auth'], function () {
Route::post('login', [RegisterController::class, 'login']);
Route::post('register', [RegisterController::class, 'register']);


Route::group(['middleware' => 'auth:api'], function() {
Route::get('logout', [RegisterController::class, 'logout']);
Route::get('user', [RegisterController::class, 'user']);
Route::post('changePassword', [RegisterController::class, 'changePassword']);
Route::get('testapi', [RegisterController::class, 'testfun']);
});
});

when i place this route under the first group(auth):当我将这条路线放在第一组(auth)下时:

Route::get('testapi', [RegisterController::class, 'testfun']);

and try this on controller:在 controller 上试试这个:

return auth()->user();

i will get response 200 but it doesn't show anything我会收到 200 响应,但没有显示任何内容

here is my login function:这是我的登录 function:

public function login(Request $request)
{
    $request->validate([
    'email' => 'required|string|email',
    'password' => 'required|string',
    ]);

    $credentials = request(['email','password']);
    if(!Auth::attempt($credentials))
    {
    return response()->json([
        'message' => 'Unauthorized'
    ],401);
    }

    $user = $request->user();
    $tokenResult = $user->createToken('Personal Access Token');
    $token = $tokenResult->token;

    if($request->remember_me)
        $token->expires_at = Carbon::now()->addWeeks(1);
    $token->save();

    return response()->json([
        'message'=>'Authorized Successfully!',
        'access_token' => $tokenResult-> accessToken,
        'token_type'=> 'Bearer',
        'expires_at'=> Carbon::parse(
            $tokenResult->token->expires_at
        )->toDateTimeString(),
        'userData' => $this->user($request),
    ]);
}

in the above after login i am able to see the user details under 'userData' as showing below from Postman在上面登录后,我能够在“userData”下看到用户详细信息,如下所示来自 Postman

{
"message": "Authorized Successfully!",
"access_token": "eyJ0eXAiOiJKV1QiLC....",
"token_type": "Bearer",
"expires_at": "2023-12-05 11:18:07",
"userData": {
    "id": 1,
    "fullname": "Admin",
    "email": "admin@gmail.com",
    "roles_id": 2,
    "role": "Admin"
}
}

i even tried to place it alone in the API route as showing below:我什至试图将它单独放在 API 路线中,如下所示:

Route::middleware('auth:api')->get('/usertest', function (Request $request) {
return $request->user()->id;
});

and i got this error:我得到了这个错误:

Symfony\Component\Routing\Exception\RouteNotFoundException: Route [/login] not defined

i have been trying to get the ID of the authenticated user but with no luck我一直在尝试获取经过身份验证的用户的 ID,但没有成功

what am i doing wrong?我究竟做错了什么?

Answer:回答:

in Postman i had to set this header Accept: application/json otherwise Laravel Passport would never know it's an API client and thus redirect to a /login page for the web. https://stackoverflow.com/a/51681131/19663907 in Postman i had to set this header Accept: application/json otherwise Laravel Passport would never know it's an API client and thus redirect to a /login page for the web. https://stackoverflow.com/a/51681131/19663907

and also for Authorization in Postman (Bearer Token) placed the token in it after login以及 Postman 中的授权(不记名令牌)在登录后将令牌放入其中

and used the function as showing below:并使用 function 如下所示:

public function testfun(Request $request)
{
    $id = $request->user()->id;
    $currentUser = DB::table('users')
        ->select('users.*')
        ->where('id', $id)
        ->get();

        return $currentUser;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在laravel护照api中获取带有访问令牌的user_id? - How can I get user_id with access token in laravel passport api? 如何使用 Passport 在 Laravel API 中获取当前用户? - How to get current user in Laravel API using Passport? 使用Laravel通行证获得API时如何在Laravel控制器中获取身份验证用户? - How to get auth user in Laravel controller when using the Laravel passport for API? 如何从 Laravel 护照令牌中获取用户 ID? - How to get the user id from laravel passport token? Laravel/Passport 获取守卫用户 id - Laravel/Passport get guard user id Laravel Passport API:createToken获取id - Laravel Passport API: createToken get id 在 Laravel 护照上使用自定义 id (api_account_id) 而不是传统的 user_id 问题 - Using custom id (api_account_id) instead of conventional user_id problem on laravel passport 当我想让用户登录时,我收到“消息”:“未验证” laravel 护照 api - I get “message”: “Unauthenticated” laravel passport api when I want to get user logged in 从令牌中获取ID,以便我可以检查用户是否是资源护照Laravel的所有者 - Taking id from token so I can check if the user is the owner of the recource Passport Laravel 是否可以在不使用护照的情况下使用 api 中的用户使用 laravel 默认身份验证 - is it possible to get the user in api without using passport using laravel default auth
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM