首页 > 解决方案 > 来自第三方 API 的 Laravel 基本身份验证

问题描述

我现在正在开发一个 Web 应用程序。这个应用程序正在使用 Laravel 框架,并且应该通过另一个已经存在的 REST-API 获取所有数据,以及有关经过身份验证的用户的信息。此 REST-API 使用基本身份验证作为确认身份验证的方法。

到目前为止,我所做的是以下代码:

function userLogin(){

    //get username and password from login form
    $username = $_POST["username"];
    $password = $_POST["password"];

    //create a new Guzzle client
    $client = new Client();

    //send username and password to REST API to get the Authentication
    $response = $client->get('localhost:8080/api/user/login', [
        'auth' => [$username, $password]
    ]);

    if ($response->getStatusCode() < 200 || $response->getStatusCode() >= 300) {
        return back()->with('danger','Login failed.');
    }else{
        return view('home');
    }
}

我设法登录,但是当我单击菜单时,它让我回到登录页面,因为中间件不知道用户登录。

我还从我的同事那里获得了一个 Angular 代码,该代码在他的 Ionic 移动应用程序中成功管理了登录尝试:

login(user:User): Observable<any> {
const headers = new HttpHeaders(user ?
  {authorization:'Basic ' + btoa(user.username + ":" + user.password)}
  :
  {});

  /**
   * a simple temporary measure to counter the error we get
   * when we log in to the app. 
   * because the API sends nothing as response, nothing is assigned to the currentUser variable.
   * this one line only assign value of currentUser manually to localStorage.
   * it consists only of username and password.
   */
  localStorage.setItem('currentUser', JSON.stringify(user));

  /**
   * as of now these do nothing, because the API sends out nothing as response.
   */
  return this.http.get<any>(API_URL + "login", {headers: headers})
  .pipe(map(response => {
    if(response){
      localStorage.setItem('currentUser', JSON.stringify(response));
    }
    return response;
  }));
}

不幸的是,我不知道如何将其转换为 PHP 代码或 Laravel 函数。我希望有人能给我解决这个问题。

标签: laravelrestbasic-authentication

解决方案


在后端进行身份验证时,您必须应用中间件来验证用户身份,因此您必须在 Authenticate.php 或任何其他自定义中间件中编写代码,如下所示:

try{

        $client = new \GuzzleHttp\Client();
        $url = "https://identitytoolkit.googleapis.com/v1/accounts:lookup?key=".env("API_KEY");

        $request = $client->post($url, array(
            'form_params' => array(
                'idToken' => $token
            )
        ));
        //$response = $request->getBody();
        //$response = $request->send();
        $body = $request->getBody();

        if ($request->getStatusCode() !== 200) {
            $res['status'] = 401;
            $res['message'] = 'Error, Invalid domain.';
            return response($res);
        }
    }
    catch(\GuzzleHttp\Exception\ClientException $e) {
       log::info('catch========== Exception');
        $res['status'] = 401;
        $res['message'] = 'Error, Unauthorized.';
        return response($res);
    }

推荐阅读