简体   繁体   English

令牌认证休息API会话

[英]Token Authentication Rest API Session

I am using the Slim Framework to create a stateless REST API. 我正在使用Slim Framework来创建无状态REST API。 Before using this I created a SESSION on server side with session check on every page. 在使用之前,我在服务器端创建了一个SESSION,并在每个页面上进行会话检查。 But now, I don't know how to control it. 但现在,我不知道如何控制它。

I have an api_key in my database for each user. 我的数据库中为每个用户都有一个api_key。 After a user signin, I respond with a api_key and redirect the user to index.php. 在用户登录后,我使用api_key进行响应并将用户重定向到index.php。 But the api_key is not retained. 但是不保留api_key。 How can I pass the api_key to each page with Javascript? 如何使用Javascript将api_key传递给每个页面? Reason being if someone wants data from my REST API, they have to send me an api_key and also if the user logged in before I don't want to show login page again. 原因是如果有人想要我的REST API中的数据,他们必须向我发送api_key,如果用户在我不想再次显示登录页面之前登录。

Here is my REST API part: 这是我的REST API部分:

$app->post('/userlogin', function() use ($app) {
    verifyRequiredParams(array('email', 'password'));
    $email = $app->request->post('email');
    $password = $app->request->post('password');

    $objUserRegLog = new UserRegistrationLogin;
    $result = $objUserRegLog->getUserByEmailAndPassword($email, $password);
    if (!$result) {
        $response["error"] = true;
        $response["message"] = "Error! Invalid e-mail address or password.";
    } else {
        $response["error"] = false;
        $response["id"] = $result["id"];
        $response["email"] = $result["email"];
        $response["api_key"] = $result["api_key"];
    }
    echoResponse(200, $response);
});

$app->get('/students', 'authenticateStudent', function() use ($app) {
    $objStd = new Students;
    $result = $objCases->getAllStudents();
    if (!$result) {
        $response["error"] = true;
        $response["error_msg"] = "An error occured.";
        $status_code = 404;
    } else {
        $response["error"] = false;
        $response["cases"] = $result;
        $status_code = 200;
    }
    echoResponse($status_code, $response);
});

function authenticateStudent(\Slim\Route $route) {
    $headers = apache_request_headers();
    $response = array();
    $app = \Slim\Slim::getInstance();

    if (isset($headers['Authorization'])) {
        $db = new DbOperation();
        $api_key = $headers['Authorization'];
        if (!$db->isValidStudent($api_key)) {
            $response["error"] = true;
            $response["message"] = "Access Denied. Invalid Api key";
            echoResponse(401, $response);
            $app->stop();
        }
    } else {
        $response["error"] = true;
        $response["message"] = "Api key is misssing";
        echoResponse(400, $response);
        $app->stop();
    }
}

And the call with AJAX : 和AJAX一起调用:

$.signin = function() {
    var inputVals = $("#form_signin").serialize();
    $.ajax({
        url : "api/v1/userlogin",
        data : inputVals,
        dataType : "json",
        type : "post",
        success : function(response) {
            if (response.error) {
                $(".popup").trigger("click");
                $(".modal-title").html(response.message_title);
                $(".modal-body").html(response.message);
            } else {
                window.location.href = "index.php";
            }
            console.log(response);
        }
    });
    return false;
}

Well, you need to understand that every request the client sends to your server is independent, so you need to put a variable (the token) in the client system in order to let him to send it in every request, so you know who is talking to your server all the time. 那么,您需要了解客户端发送给您的服务器的每个请求都是独立的,因此您需要在客户端系统中放置一个变量(令牌),以便让他在每个请求中发送它,这样您就知道谁是一直跟你的服务器说话。 Start reading this: http://www.w3schools.com/php/php_cookies.asp 开始阅读: http//www.w3schools.com/php/php_cookies.asp

Once you understand what are and how cookies work, try to read further about authentication and authorization topics. 一旦了解了Cookie的工作原理和方式,请尝试进一步阅读有关身份验证和授权主题的信息。

You have three ways to provide such information. 您有三种方法可以提供此类信息。

Cookies 饼干

In most cases, if you have a login screen, you want to use cookies as mentioned by Hector. 在大多数情况下,如果您有登录屏幕,则需要使用Hector提到的cookie。 One potential problem with cookies, some people do not want them from "random" websites. 一个潜在的cookie问题,有些人不希望它们来自“随机”网站。 However, the good thing is you can close your tab, reopen it, and you can still be logged in (it depends on the type of cookie, but in most cases you want to use this type). 但是,好处是您可以关闭选项卡,重新打开它,您仍然可以登录(这取决于cookie的类型,但在大多数情况下,您希望使用此类型)。

Query String 请求参数

One other way, tedious, is to add a query string parameter with the session identifier. 另一种方法,繁琐,是添加一个带有会话标识符的查询字符串参数。 This also means you must make sure that each single link on your page includes that session identifier. 这也意味着您必须确保页面上的每个链接都包含该会话标识符。 Also, it is generally viewed as a security issue because people who look over your shoulder can see the session identifier (frankly, unless they have a photographic memory...) For people who block cookies, this is another way. 此外,它通常被视为一个安全问题,因为看着你肩膀的人可以看到会话标识符(坦率地说,除非他们有照片记忆......)对于阻止cookie的人,这是另一种方式。 However, since it is using the exact same type of session identifier, you may be infringing on what the user meant when blocking cookies. 但是,由于它使用的是完全相同类型的会话标识符,因此您可能会侵犯用户在阻止Cookie时的含义。

HTML Code HTML代码

The last way, which requires even more work, is to put the value in the HTML. 最后一种方法是将值放在HTML中,这需要更多的工作。 For example, you could use a <meta ...> tag. 例如,您可以使用<meta ...>标记。 At least that way it is hidden from people looking over your shoulder. 至少就是这样,人们看着你的肩膀是隐藏的。 But you still need to transmit it when someone clicks on your links, somehow. 但是,当某人点击你的链接时,你仍需要传输它。 That means you must load any other page using a POST in JavaScript. 这意味着您必须使用JavaScript中的POST加载任何其他页面。 That's rather unconventional. 那是非常传统的。 And just like with the previous method. 就像以前的方法一样。 You may be infringing on the user's will of "no tracking please". 您可能侵犯了用户“不跟踪请”的意愿。

What about Security? 安全怎么样?

The most secure is to have an HTTPS connection with a cookie marked as HTTP-only (ie JavaScript cannot access it, so it cannot temper with it.) 最安全的是与标记为仅HTTP的cookie建立HTTPS连接(即JavaScript无法访问它,因此无法使用它进行调整。)

All other methods have additional security issues. 所有其他方法都有其他安全问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM