Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

php - How to implement 'Token Based Authentication' securely for accessing the website's resources(i.e. functions and data) that is developed in PHPFox?

I want to use methods and resources from the code of a website which is developed in 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.

For this purpose I've developed REST APIs using Slim framework.

But the major blocker I'm facing currently is in accessing the resources(i.e. functions and data) of PHPFox website.

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 :

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Read more

Now let's see what are the steps of implementing it in your REST web service.

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.

See the image below for the flow of control

enter image description here

You might be wondering what's a 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;

enter image description here

You do not need to implement the bearer token generator as you can use 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...