将Laravel 5.8身份验证与外部JSON API结合使用(创建自己的ServiceProvider) [英] Using Laravel 5.8 authentication with external JSON API (Creating own ServiceProvider)

查看:33
本文介绍了将Laravel 5.8身份验证与外部JSON API结合使用(创建自己的ServiceProvider)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个Laravel 5.8应用程序,使其成为用Go编写的外部API的前端.我将用户/密码发布到API,然后使用HTTP/200和JSON令牌(JWT)或HTTP/401响应以表明凭据无效.

I'm building a Laravel 5.8 application to be the front-end to an external API written in Go. I POST a user/pass to the API which then responds with either HTTP/200 and a JSON Token (JWT) or an HTTP/401 to signal the credentials are invalid.

我想使用Laravel的内置身份验证机制(或任何能够真正实现此目的的机制)来创建仅用于已登录用户的页面和路由.重新发明轮子似乎有很多工作.

I would like to use Laravel's built-in auth mechanism (or anything which makes this work really) to be able to create pages and routes only for logged in users. It seems a lot of work to reinvent the wheel.

[TLDR]基本上,我需要一些代码来检查API是否返回HTTP/200,将令牌存储在某个地方(会话/Cookie(但不包含数据库)),然后提供一些方法来轻松地(虚拟)将用户登录到Laravel应用程序.这样,我只能为登录用户创建页面.

[TLDR] Basically I need some code which checks if the API returns an HTTP/200, stores the token somewhere (session/cookie [but not database]) and then provide's some way to easily (virtually) log users into the Laravel app. That way I can create pages for logged in users only.

到目前为止,我已经做到了:

So far I have done this:

APIUser类:

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:

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:

config/auth.php:

'providers' => [
        'users' => [
            'driver' => 'apiuserprovider',
        ],

LoginController:

LoginController:

public function login(Request $request){ 
$credentials = $request->only('email', 'password');

        if (Auth::attempt($credentials)) {
            // Authentication passed...
            return redirect()->intended('/');
        }
}

在登录功能中,当我这样做时:

And in the login function, when I do:

dd($this->guard()->user());

它提供了我用户的信息.一切正常,但是,它不会使用户登录到系统.有什么问题吗?

it gives me user's information. Everything works fine, however, it does not login a user to the system. What is the problem?

推荐答案

更改内部的公共函数retrieveById($ identifier)函数并从API中检索所有用户信息

Change public function retrieveById($identifier) function inside and retrieve all user information from API

这篇关于将Laravel 5.8身份验证与外部JSON API结合使用(创建自己的ServiceProvider)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆