使用外部 JSON API 的 Laravel 5.8 身份验证(创建自己的 ServiceProvider)
Using Laravel 5.8 authentication with external JSON API (Creating own ServiceProvider)
我正在构建一个 Laravel 5.8 应用程序作为用 Go 编写的外部 API 的前端。我 POST 一个 user/pass 到 API 然后用 HTTP/200 和一个 JSON 令牌(JWT)或一个 HTTP/401 来响应凭据无效。
我想使用 Laravel 的内置身份验证机制(或使此功能真正起作用的任何机制)能够仅为登录用户创建页面和路由。重新发明轮子好像很多工作。
[TLDR] 基本上我需要一些代码来检查 API returns 和 HTTP/200 是否将令牌存储在某处(session/cookie [但不是数据库])然后提供一些方法让用户轻松(虚拟)登录到 Laravel 应用程序。这样我就可以仅为登录用户创建页面。
到目前为止我已经这样做了:
API用户class:
protected $attributes = [];
public function __construct($attributes)
{
$this->attributes = $attributes;
}
public function __get($attribute)
{
return $this->attributes[$attribute];
}
public function getKey()
{
return $this->attributes['userId'];
}
/**
* Get the name of the unique identifier for the user.
*
* @return string
*/
public function getAuthIdentifierName()
{
return 'userId';
}
/**
* Get the unique identifier for the user.
*
* @return mixed
*/
public function getAuthIdentifier()
{
return $this->attributes['userId'];
}
/**
* Get the password for the user.
*
* @return string
*/
public function getAuthPassword()
{
return null;
}
public function getAuthIdentifierEmail()
{
return $this->attributes['email'];
}
/**
* Get the token value for the "remember me" session.
*
* @return string
*/
public function getRememberToken()
{
return $this->attributes[$this->getRememberTokenName()];
}
/**
* Set the token value for the "remember me" session.
*
* @param string $value
* @return void
*/
public function setRememberToken($value)
{
$this->attributes[$this->getRememberTokenName()] = $value;
}
/**
* Get the column name for the "remember me" token.
*
* @return string
*/
public function getRememberTokenName()
{
}
public function getAttributes()
{
return $this->attributes;
}
ApiUserProvider:
protected $model;
protected $modelUser;
public function __construct(Request $request)
{
$this->model = APIUser::class;
}
public function fetchUser($credentials) {
if ($credentials['email'] and $credentials['password']) {
$email = $credentials['email'];
$password = $credentials['password'];
$client = new \GuzzleHttp\Client([
'headers' => ['Content-Type' => 'application/json'],
]);
$url = config('apilist.login');
try {
$response = $client->request('POST', $url, [
'json' => [
'email' => $email,
'password' => sha1($password),
],
]);
} catch (GuzzleException $e) {
print_r($e->getResponse());
}
$array = json_decode($response->getBody()->getContents(), true);
if($array["responseMessage"]["code"] == 200){
$userInfo = $array["responseMessage"]["object"];
return new $this->model($userInfo);
} else {
return $array["responseMessage"]["message"] ?: "Something went wrong. Please try again";
}
}
}
public function retrieveById($identifier) {
return $this->modelUser;
}
/**
* Retrieve a user by their unique identifier and "remember me" token.
*
* @param mixed $identifier
* @param string $token
* @return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function retrieveByToken($identifier, $token) {}
/**
* Update the "remember me" token for the given user in storage.
*
* @param \Illuminate\Contracts\Auth\Authenticatable $user
* @param string $token
* @return void
*/
public function updateRememberToken(Authenticatable $user, $token){}
/**
* Retrieve a user by the given credentials.
*
* @param array $credentials
* @return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function retrieveByCredentials(array $credentials){
$user = $this->fetchUser($credentials);
return $user;
}
/**
* Validate a user against the given credentials.
*
* @param \Illuminate\Contracts\Auth\Authenticatable $user
* @param array $credentials
* @return bool
*/
public function validateCredentials(Authenticatable $user, array $credentials){
//return ($credentials['email'] == $user->getAuthIdentifierEmail());
return true;
}
config/auth.php:
'providers' => [
'users' => [
'driver' => 'apiuserprovider',
],
登录控制器:
public function login(Request $request){
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
// Authentication passed...
return redirect()->intended('/');
}
}
并且在登录功能中,当我这样做时:
dd($this->guard()->user());
它给了我用户的信息。一切正常,但是,它不会将用户登录到系统。有什么问题?
更改public function retrieveById($identifier) 函数内部并从API
中检索所有用户信息
我正在构建一个 Laravel 5.8 应用程序作为用 Go 编写的外部 API 的前端。我 POST 一个 user/pass 到 API 然后用 HTTP/200 和一个 JSON 令牌(JWT)或一个 HTTP/401 来响应凭据无效。
我想使用 Laravel 的内置身份验证机制(或使此功能真正起作用的任何机制)能够仅为登录用户创建页面和路由。重新发明轮子好像很多工作。
[TLDR] 基本上我需要一些代码来检查 API returns 和 HTTP/200 是否将令牌存储在某处(session/cookie [但不是数据库])然后提供一些方法让用户轻松(虚拟)登录到 Laravel 应用程序。这样我就可以仅为登录用户创建页面。
到目前为止我已经这样做了:
API用户class:
protected $attributes = [];
public function __construct($attributes)
{
$this->attributes = $attributes;
}
public function __get($attribute)
{
return $this->attributes[$attribute];
}
public function getKey()
{
return $this->attributes['userId'];
}
/**
* Get the name of the unique identifier for the user.
*
* @return string
*/
public function getAuthIdentifierName()
{
return 'userId';
}
/**
* Get the unique identifier for the user.
*
* @return mixed
*/
public function getAuthIdentifier()
{
return $this->attributes['userId'];
}
/**
* Get the password for the user.
*
* @return string
*/
public function getAuthPassword()
{
return null;
}
public function getAuthIdentifierEmail()
{
return $this->attributes['email'];
}
/**
* Get the token value for the "remember me" session.
*
* @return string
*/
public function getRememberToken()
{
return $this->attributes[$this->getRememberTokenName()];
}
/**
* Set the token value for the "remember me" session.
*
* @param string $value
* @return void
*/
public function setRememberToken($value)
{
$this->attributes[$this->getRememberTokenName()] = $value;
}
/**
* Get the column name for the "remember me" token.
*
* @return string
*/
public function getRememberTokenName()
{
}
public function getAttributes()
{
return $this->attributes;
}
ApiUserProvider:
protected $model;
protected $modelUser;
public function __construct(Request $request)
{
$this->model = APIUser::class;
}
public function fetchUser($credentials) {
if ($credentials['email'] and $credentials['password']) {
$email = $credentials['email'];
$password = $credentials['password'];
$client = new \GuzzleHttp\Client([
'headers' => ['Content-Type' => 'application/json'],
]);
$url = config('apilist.login');
try {
$response = $client->request('POST', $url, [
'json' => [
'email' => $email,
'password' => sha1($password),
],
]);
} catch (GuzzleException $e) {
print_r($e->getResponse());
}
$array = json_decode($response->getBody()->getContents(), true);
if($array["responseMessage"]["code"] == 200){
$userInfo = $array["responseMessage"]["object"];
return new $this->model($userInfo);
} else {
return $array["responseMessage"]["message"] ?: "Something went wrong. Please try again";
}
}
}
public function retrieveById($identifier) {
return $this->modelUser;
}
/**
* Retrieve a user by their unique identifier and "remember me" token.
*
* @param mixed $identifier
* @param string $token
* @return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function retrieveByToken($identifier, $token) {}
/**
* Update the "remember me" token for the given user in storage.
*
* @param \Illuminate\Contracts\Auth\Authenticatable $user
* @param string $token
* @return void
*/
public function updateRememberToken(Authenticatable $user, $token){}
/**
* Retrieve a user by the given credentials.
*
* @param array $credentials
* @return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function retrieveByCredentials(array $credentials){
$user = $this->fetchUser($credentials);
return $user;
}
/**
* Validate a user against the given credentials.
*
* @param \Illuminate\Contracts\Auth\Authenticatable $user
* @param array $credentials
* @return bool
*/
public function validateCredentials(Authenticatable $user, array $credentials){
//return ($credentials['email'] == $user->getAuthIdentifierEmail());
return true;
}
config/auth.php:
'providers' => [
'users' => [
'driver' => 'apiuserprovider',
],
登录控制器:
public function login(Request $request){
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
// Authentication passed...
return redirect()->intended('/');
}
}
并且在登录功能中,当我这样做时:
dd($this->guard()->user());
它给了我用户的信息。一切正常,但是,它不会将用户登录到系统。有什么问题?
更改public function retrieveById($identifier) 函数内部并从API
中检索所有用户信息