【发布时间】:2019-11-21 21:12:22
【问题描述】:
我现在正在开发一个网络应用程序。这个应用程序正在使用 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 函数。我希望有人能给我解决这个问题。
【问题讨论】:
-
“我设法登录,但是当我点击菜单时”您正在开发一个休息 api 并点击菜单?使用基本身份验证,您应该始终发送标头。
-
您的 API 为您提供了什么作为“登录”的回报?它必须给你 something 回来,即一个令牌。否则,你打算如何在其他 API 请求中证明你是谁?
-
我忘了提到我没有开发 REST API,它已经存在,我尝试在我的 Web 应用程序中使用它的身份验证。我的同事说,我应该将标头保存在 LocalStorage 中,但是我还没有找到在 Laravel 中的 localStorage 中保存值的方法
标签: laravel rest basic-authentication