繁体   English   中英

如何在此 Laravel 8 和 Auth0 API 中获取当前用户的 ID?

[英]How do I get the current user's id in this Laravel 8 and Auth0 API?

我正在研究 Laravel 8 API。 我使用 Auth0 进行用户注册和登录。

在注册时,我需要 Auth0 返回的用户 ID(作为user_id ),以便将其插入我自己的用户表中,在名为uid的列中。

此外,一旦用户登录,我需要在myapp.test/api/user-profile/show/显示用户的数据,我还需要user_id

为此,我有代码:

routes\api.php

Route::get('/authorization', [UserController::class, 'authorize']);

用户控制器中:

public function authorize(){

    $appDomain = 'https://' . config('laravel-auth0.domain');
    $appClientId = config('laravel-auth0.client_id');
    $appClientSecret = config('laravel-auth0.client_secret');
    $appAudience = config('laravel-auth0.api_identifier');

    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => "$appDomain/oauth/token",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => "{\"client_id\":\"$appClientId\",\"client_secret\":\"$appClientSecret\",\"audience\":\"$appAudience\",\"grant_type\":\"client_credentials\"}",
        CURLOPT_HTTPHEADER => array(
            "content-type: application/json"
        ),
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
        return "cURL Error #:" . $err;
    } else {
        return $response;
    }
}

问题

authorize()方法(取自 Auth0 网站上的教程)仅返回 access_token 信息,但返回user_id

问题

  1. 如何获取当前用户的 user_id?
  2. 我想我需要用一些东西代替CURLOPT_URL => "$appDomain/oauth/token" ,而不是用什么

要获取当前登录用户的 ID,您可以使用 Auth; $user_id = Auth::user()->id;

它会给你的 id 当前登录用户 id。 但如果您需要完整的登录用户信息,那么您可以使用

$user = Auth::user();

请看这个社区的答案:

https://community.auth0.com/t/how-to-get-user-information-from-the-laravel-api-side/47021/3

向 Authentication API 的 userinfo 端点发出请求以获取用户的个人资料。 https://auth0.com/docs/api/authentication#user-profile

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM