【问题标题】:Customizing the token response自定义令牌响应
【发布时间】:2019-11-02 09:59:21
【问题描述】:

我目前的登录响应是这样的,

{
    "token_type": "Bearer",
    "expires_in": 31536000,
    "access_token": "eyJ0eWq4Pt2B7M8W5zWwepDNpWqL0FOzdA8sPNiPhfxJcaktCq7GqQJDNLfPCuN5_Cl4",
    "refresh_token": "def50200278e5e6e658f2149489a6d1578ce4cdef1abb80e21df5efa4bbbc7003840df34768a091a57e88c0"
}

但我需要此响应为 JSON,

{  
   "success":"true",
   "message":"Login Successful",
   "status":"200",
   "data":
   {  
     "token_type": "Bearer",
     "expires_in": 31536000,
     "access_token": "eyJ0eWq4Pt2B7M8W5zWwepDNpWqL0FOzdA8sPNiPhfxJcaktCq7GqQJDNLfPCuN5_Cl4",
     "refresh_token": "def50200278e5e6e658f2149489a6d1578ce4cdef1abb80e21df5efa4bbbc7003840df34768a091a57e88c0"
   }
}

【问题讨论】:

  • 显示您之前尝试过的代码
  • 您的第二个 Json 看起来不正确,您缺少一个 }。但是,如果您从数组创建该 JSON,则更改为该结构应该很简单
  • 两个响应都是 json。

标签: php laravel token laravel-passport


【解决方案1】:

假设你有一个登录控制器,方法就是这样设计的。

如您所说,要返回响应,请使用以下代码

public static function LoginUser(Request $request) {
    $http = new guzzleclient;

    $response = $http->post(env('APP_URL').'/oauth/token', [
        'form_params' => [
            'grant_type' => 'password',
            'client_id' => env('CLIENT_ID'),
            'client_secret' => env('CLIENT_SECRET'),
            'username' => $request->email,
            'password' => $request->password,
            'scope' => '*',    
        ],
    ]); 

    $response = json_decode((string) $response->getBody(), true);
    $final_resp = [
        'success' => "true", 
        'message' => "Login Successful", 
        'data' => $response, 
        'status' => "200"
    ];

    return response()->json($final_resp, 200);
}

请注意,此示例使用密码授予方法。

【讨论】:

    猜你喜欢
    • 2018-03-24
    • 1970-01-01
    • 2019-12-22
    • 2020-10-16
    • 2021-01-28
    • 2019-12-18
    • 1970-01-01
    • 2018-11-14
    • 2016-01-17
    相关资源
    最近更新 更多