我正在开发一个Web应用程序。该应用程序正在使用Laravel Framework,并且应该通过另一个已经存在的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 Mobile Apps中成功管理了登录尝试:
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函数。我希望有人可以给我解决这个问题的方法。
答案 0 :(得分:0)
在后端进行身份验证时,您必须应用中间件来对用户进行身份验证,因此必须在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);
}