首页 > 解决方案 > 将自定义 REST api 登录与另一个网站集成

问题描述

我正在尝试将我的 Laravel PASSPORT API 与我的另一个网站集成。

登录路径“ https://api.myapi.com/login

我创建了我想使用 API 路由登录的网站。

我认为我做错了,如果登录并在标题中使用正确的方式承载令牌,我不知道如何检查它。

登录功能和 curl post 方法所在的 Api 类

class Api {

    private $errors = array(); // array to hold validation errors
    private $data = array(); // array to pass back data

    private $cookies;
    private $headers = [];
    private $token;
    private $user_agent;
    private $compression;
    private $proxy;

    function __construct($cookies = true, $cookie = "cookie.c", $compression = 'gzip', $proxy = '') {
        $this->headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';
        $this->headers[] = 'Connection: Keep-Alive';
        $this->headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';
        $this->token = $this->checkAuth();
        if ($this->token !== null) { $this->headers[] = 'Authorization: Bearer ' . $token; }
        $this->user_agent = $this->http_user_agent();
        $this->compression = $compression;
        $this->proxy = $proxy;
        $this->cookies = $cookies;

        if ($this->cookies == true) $this->cookie($cookie);
    }

    //this function is done wrongly..
    public function checkAuth () {
        $auth = json_decode($this->login());

        if ($auth->success === true) {
            return $auth->token;
        }

        return null;
    }

    public function login($vars) {

        if (empty($vars['email'])) $this->errors[$vars['email']] = 'Email field is required.';

        if (empty($vars['password'])) $this->errors[$vars['password']] = 'Password field is required.';

        if ( ! empty($this->errors)) { 
            $this->data['success'] = false;
            $this->data['errors']  = $this->errors;
        } else {
            $email = $vars['email'];
            $password = $vars['password'];

            $fields = array(
                "email" => $email, 
                "password" => $password
            );

            $fields_string = http_build_query($fields);

            $res = $this->post("http://kris.dev/apify/public/stylist/login", $fields_string);
            $logPost = json_decode($res);

            if (isset($logPost->error)) {
                $this->data['success'] = false;
                $this->data['errors']  = $logPost->error;

                return json_encode($this->data);
            } elseif (isset($logPost->token)) {
                $this->data['success'] = true;
                $this->data['token']  = $logPost->token;

                return json_encode($this->data);
            }
        }
        // return all our data to an AJAX call
        return json_encode($this->data);
    }

    private function cookie($cookie_file) {
        if (file_exists($cookie_file)) {
            $this->cookie_file = $cookie_file;
        } else {
            fopen($cookie_file, 'w') or $this->error('The cookie file could not be opened. Make sure this directory has the correct permissions');
            $this->cookie_file = $cookie_file;
            fclose($this->cookie_file);
        }
    }

    public static function http_user_agent() {
        return ((isset($_SERVER['HTTP_USER_AGENT'])) ? $_SERVER['HTTP_USER_AGENT'] : NULL);
    }

    public function post($url, $data) {

        $process = curl_init($url);
        curl_setopt($process, CURLOPT_HTTPHEADER, $this->headers);

        curl_setopt($process, CURLOPT_HEADER, 1);
        curl_setopt($process, CURLOPT_USERAGENT, $this->user_agent);

        if ($this->cookies == true) curl_setopt($process, CURLOPT_COOKIEFILE, $this->cookie_file);
        if ($this->cookies == true) curl_setopt($process, CURLOPT_COOKIEJAR, $this->cookie_file);

        curl_setopt($process, CURLOPT_ENCODING, $this->compression);
        curl_setopt($process, CURLOPT_TIMEOUT, 30);

        if ($this->proxy) curl_setopt($process, CURLOPT_PROXY, $this->proxy);

        curl_setopt($process, CURLOPT_POST, 1);
        curl_setopt($process, CURLOPT_POSTFIELDS, $data);
        curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
        $response = curl_exec($process);

        $header_size = curl_getinfo($process, CURLINFO_HEADER_SIZE);
        $return = substr($response, $header_size);
        curl_close($process);

        return $return;
    }

登录函数将表单参数传递给 Api 类。

require __DIR__ . 'api.php';

$api = new Api();

if (isset($_POST)) {
    $vars = array("email" => $_POST['email'], "password" => $_POST['password']);
    $api->login($vars);
}

ajax 将表单数据传递给登录函数

$(document).ready(function() {

    // process the form
    $('#subButton').click(function(e) {
        // get the form data
        // there are many ways to get this data using jQuery (you can use the class or id also)
        var email = $('#email').val();
        var password = $('#password').val();

        // process the form
        $.ajax({
            type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
            url         : 'functions/login.php', // the url where we want to POST
            data: {
                'email' : email,
                'password' : password
            },
            dataType:'JSON',
            success: function(data) {
                console.log(data);

                // here we will handle errors and validation messages
                if ( ! data.success) {

                    // handle errors for email ---------------
                    if (data.errors.email) {
                        $('#email').addClass('has-error'); // add the error class to show red input
                        $('#email').append('<div class="help-block">' + data.errors.email + '</div>'); // add the actual error message under our input
                    }

                    // handle errors for email ---------------
                    if (data.errors.password) {
                        $('#password').addClass('has-error'); // add the error class to show red input
                        $('#password').append('<div class="help-block">' + data.errors.password + '</div>'); // add the actual error message under our input
                    }

                } else {

                    // ALL GOOD! just show the success message!
                    $('form').append('<div class="alert alert-success">' + data.message + '</div>');
                    $('#token').append('<div class="alert alert-success">' + data.token + '</div>');

                    // usually after form submission, you'll want to redirect
                    // window.location = '/thank-you'; // redirect a user to another page
                    alert('success'); // for now we'll just alert the user

                }
            }

        });
        // stop the form from submitting the normal way and refreshing the page
        e.preventDefault();
    });

});

Laravel 护照 api 登录控制器很简单,如果用户电子邮件和密码正确然后创建 accessToken,如果密码或电子邮件错误,它会抛出 http_code 422 和响应文本“电子邮件或密码不正确。

标签: phpapi

解决方案


推荐阅读