curl 登录/访问(php / laravel)sanctum接口的示例代码/库

hl0ma9xz  于 4个月前  发布在  PHP
关注(0)|答案(1)|浏览(57)

我在php / laravel中有一个sanctum接口:
这些路线是:

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

Route::middleware('auth:sanctum')->prefix('v1')->group(function() {
  Route::get('/xxx', [\App\Http\Controllers\XxxController::class, 'index']);

字符串
IN XXxOntroller.php

public function show(Request $request, $xxxId) {
      if (Auth::user()->xxxs()->where('uuid', $xxxId)) {
        $xxx = Xxx::where('uuid', $xxxId)->with('counters')->firstOrFail();

        return response()->json($xxx);
      }
      $this->unauthorized();
    }


我知道Sanctum documentation,但我需要的是客户端的示例或库(Python)。我猜URL是baseUrl/user,我需要传递uuidpassword来请求CsrfToken。
如果尝试在this issue之后使用curl,但只得到HTML
我也试过php代码

$client_id = "you";
$secret = "token";
$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL => 'https://domain.cn/api/user',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'GET',
    CURLOPT_POSTFIELDS => 'grant_type=client_credentials',
    CURLOPT_HTTPHEADER => [
        'Authorization: Basic '.base64_encode($client_id.':'.$secret)
    ],
]);


Python sanctum软件包

from sanctum import HTTPClient


而且这也不能正确地触发接口。

ftf50wuq

ftf50wuq1#

最后,它比假设的要简单得多。只需要一个“bearing”令牌,而不需要CsrfToken,uuid和密码。使用python:

import requests

BEARER_TOKEN: Final = "secret"
hed = {'Authorization': 'Bearer ' + bearer_token,
       'Content-Type': 'application/json'}
DATA_URL = "https://domain.cn/api/v1/xxx/id"
r = requests.get(DATA_URL,headers=hed)

字符串

相关问题