laravel - 来自第三方 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 函数。我希望有人能给我解决这个问题。
解决方案
在后端进行身份验证时,您必须应用中间件来验证用户身份,因此您必须在 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);
}
推荐阅读
- tsql - 如何在没有 group by 子句的情况下使用聚合函数(我使用的是 IFF 函数)
- excel - VBA Excel - 如果在列表中找到,则省略
- javascript - 如何使用打字稿对数组进行排序
- artifactory - 为什么受感染的版本不正确?
- javascript - 如何以编程方式更改路由器路径?
- azure-logic-apps - 使用逻辑应用的 Http 调用输出 json 到 SQL 记录
- python - 如何在python中检查两个粗略词是否相同
- angular - ASP.NET 4.5 Web API 2.0,JWT 消息处理程序将状态 0 返回到 Angular 7 HTTP 拦截器
- c# - 网络核心标识 2.1 中的方法 VerifyTwoFactorTokenAsync() 存在问题
- java - 我的应用违反了网站行为:导航,我不知道为什么?