php 如何安全地实现“基于令牌的身份验证”以访问在 PHPFox 中开发的网站资源(即功能和数据)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29121112/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to implement 'Token Based Authentication' securely for accessing the website's resources(i.e. functions and data) that is developed in PHPFox?
提问by PHPFan
I want to use methods and resources from the code of a website which is developed in PHPFox.
我想使用在PHPFox 中开发的网站代码中的方法和资源。
Basically, I'll receive request from iPhone/Android
, I'll get the request and pass to the respective function from the PHPFox code, take the response from that function and return it back to the device.
基本上,我将收到来自 的请求iPhone/Android
,我将获取请求并从 PHPFox 代码传递给相应的函数,从该函数获取响应并将其返回给设备。
For this purpose I've developed REST APIs using Slim framework.
为此,我使用Slim 框架开发了 REST API 。
But the major blocker I'm facing currently is in accessing the resources(i.e. functions and data) of PHPFox website.
但我目前面临的主要障碍是访问 PHPFox 网站的资源(即功能和数据)。
I'm not understanding how should I authenticate the user using 'Token Based Authentication'in order to access the website's resources.
我不明白我应该如何使用“基于令牌的身份验证”来对用户进行身份验证以访问网站的资源。
If someone could guide me in proper direction with some useful working example it would be really helpful for me.
如果有人可以通过一些有用的工作示例指导我朝着正确的方向前进,那对我来说真的很有帮助。
N.B. : The proposed implementation of 'Token Based Authentication' should be very secure and fast in speed. The security should not be compromised in any way.
注意:“基于令牌的身份验证”的提议实施应该非常安全且速度很快。不应以任何方式损害安全性。
Following is the code I tried on my own but I don't know whether it's right or wrong. Is my approach correct or wrong. Please someone analyse it and let me know your feedback on it.
以下是我自己尝试的代码,但我不知道它是对还是错。我的方法是对还是错。请有人对其进行分析,并让我知道您对此的反馈。
To create a token i use this function which takes as parameters, the user's data
为了创建一个令牌,我使用这个函数作为参数,用户的数据
define('SECRET_KEY', "fakesecretkey");
function createToken($data)
{
/* Create a part of token using secretKey and other stuff */
$tokenGeneric = SECRET_KEY.$_SERVER["SERVER_NAME"]; // It can be 'stronger' of course
/* Encoding token */
$token = hash('sha256', $tokenGeneric.$data);
return array('token' => $token, 'userData' => $data);
}
So a user can authentified himself and receive an array which contains a token (genericPart + his data, encoded), and hisData not encoded :
因此,用户可以对自己进行身份验证并接收一个包含令牌(genericPart + his data,已编码)和 hisData 未编码的数组:
function auth($login, $password)
{
// we check user. For instance, it's ok, and we get his ID and his role.
$userID = 1;
$userRole = "admin";
// Concatenating data with TIME
$data = time()."_".$userID."-".$userRole;
$token = createToken($data);
echo json_encode($token);
}
Then the user can send me his token + his un-encoded data in order to check :
然后用户可以向我发送他的令牌 + 他的未编码数据以检查:
define('VALIDITY_TIME', 3600);
function checkToken($receivedToken, $receivedData)
{
/* Recreate the generic part of token using secretKey and other stuff */
$tokenGeneric = SECRET_KEY.$_SERVER["SERVER_NAME"];
// We create a token which should match
$token = hash('sha256', $tokenGeneric.$receivedData);
// We check if token is ok !
if ($receivedToken != $token)
{
echo 'wrong Token !';
return false;
}
list($tokenDate, $userData) = explode("_", $receivedData);
// here we compare tokenDate with current time using VALIDITY_TIME to check if the token is expired
// if token expired we return false
// otherwise it's ok and we return a new token
return createToken(time()."#".$userData);
}
$check = checkToken($_GET['token'], $_GET['data']);
if ($check !== false)
echo json_encode(array("secureData" => "Oo")); // And we add the new token for the next request
Am I right?
我对吗?
Thanks.
谢谢。
回答by Techie
1st you should understand what's token based authentication. It could be explained as below.
第一,您应该了解什么是基于令牌的身份验证。可以解释如下。
The general concept behind a token-based authentication system is simple. Allow users to enter their username and password in order to obtain a token which allows them to fetch a specific resource - without using their username and password. Once their token has been obtained, the user can offer the token - which offers access to a specific resource for a time period - to the remote site.
基于令牌的身份验证系统背后的一般概念很简单。允许用户输入他们的用户名和密码以获取允许他们获取特定资源的令牌 - 无需使用他们的用户名和密码。一旦获得了他们的令牌,用户就可以向远程站点提供令牌——在一段时间内提供对特定资源的访问。
Now let's see what are the steps of implementing it in your REST web service.
现在让我们看看在您的 REST Web 服务中实现它的步骤是什么。
It will use the following flow of control:
- The user provides a username and password in the login form and clicks Log In.
- After a request is made, validate the user on the backend by querying in the database. If the request is valid, create a token by using the user information fetched from the database, and then return that information in the response header so that we can store the token browser in local storage.
- Provide token information in every request header for accessing restricted endpoints in the application.
- If the token fetched from the request header information is valid, let the user access the specified end point, and respond with JSON or XML.
它将使用以下控制流:
- 用户在登录表单中提供用户名和密码,然后单击登录。
- 发出请求后,通过在数据库中查询来验证后端的用户。如果请求有效,则使用从数据库中获取的用户信息创建令牌,然后在响应头中返回该信息,以便我们可以将令牌浏览器存储在本地存储中。
- 在每个请求标头中提供令牌信息以访问应用程序中的受限端点。
- 如果从请求头信息中获取的token有效,则让用户访问指定的端点,并以JSON或XML响应。
See the image below for the flow of control
控制流程见下图
You might be wondering what's a JWT
你可能想知道什么是 JWT
JWT stands for JSON Web Token and is a token format used in authorization headers. This token helps you to design communication between two systems in a secure way. Let's rephrase JWT as the "bearer token" for the purposes of this tutorial. A bearer token consists of three parts: header, payload, and signature.
- The header is the part of the token that keeps the token type and encryption method, encoded in base64.
- The payload includes the information. You can put any kind of data like user info, product info and so on, all of which is also stored in base64 encoding.
- The signature consists of combinations of the header, payload, and secret key. The secret key must be kept securely on the server-side. You can see the JWT schema and an example token below;
JWT 代表 JSON Web Token,是在授权头中使用的一种令牌格式。此令牌可帮助您以安全的方式设计两个系统之间的通信。出于本教程的目的,让我们将 JWT 重新表述为“承载令牌”。不记名令牌由三部分组成:标头、有效载荷和签名。
- 标头是令牌的一部分,用于保存以 base64 编码的令牌类型和加密方法。
- 有效载荷包括信息。您可以放入任何类型的数据,如用户信息、产品信息等,所有这些数据也以 base64 编码存储。
- 签名由标头、有效载荷和密钥的组合组成。密钥必须安全地保存在服务器端。您可以在下面看到 JWT 架构和示例令牌;
You do not need to implement the bearer token generator as you can use php-jwt.
您不需要实现不记名令牌生成器,因为您可以使用php-jwt。
Hope the above explains your confusion. if you come across any issues implementing token based authentication let me know. I can help you.
希望以上能解释你的困惑。如果您在实施基于令牌的身份验证时遇到任何问题,请告诉我。我可以帮你。