php php中基于令牌的身份验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9510703/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 06:58:42  来源:igfitidea点击:

token based authentication in php

phpauthenticationrest

提问by Johannes Staehlin

I have an REST service on my webserver, written in php. I was wondering, what would be the best authentication (besides basic http access authentication). I've heared of token-based auth, and would like to ask if someone could explain the main steps.

我的网络服务器上有一个用 php 编写的 REST 服务。我想知道什么是最好的身份验证(除了基本的 http 访问身份验证)。我听说过基于令牌的身份验证,想请问是否有人可以解释主要步骤。

  • On a GET: Is the token send visible? (isn't that unsafe?)
  • How do I make the token only valid for a specific time?
  • ...
  • 在 GET 上:令牌发送可见吗?(这不是不安全吗?)
  • 如何使令牌仅在特定时间有效?
  • ...

Client: Android/Browser; Server: Apache, PHP5

客户端:安卓/浏览器;服务器:Apache、PHP5

回答by deceze

It can be done either way, and values in a GET request aren't really any more visible than values in a POST request. If anybody can "see" (i.e. intercept) the request, he can see everything you're sending. In the end an HTTP request is just a bunch of HTTP headers possibly followed by a body. The URL is send in the first GET /foo/bar HTTP/1.1line, other values are just send in different, following lines.

它可以通过任何一种方式完成,并且 GET 请求中的值实际上并不比 POST 请求中的值更明显。如果有人可以“看到”(即拦截)请求,他就可以看到您发送的所有内容。最后,HTTP 请求只是一堆 HTTP 标头,可能后跟一个正文。URL 在第一GET /foo/bar HTTP/1.1行发送,其他值只是在不同的下面几行发送。

So it's up to you where you expect your authentication token to be send. You can require it to be a query parameter that is appended to every request:

因此,您希望将身份验证令牌发送到何处取决于您。您可以要求它是附加到每个请求的查询参数:

GET /foo/bar?user=123456&token=abcde...

To really use the HTTP protocol as intended though, you should use the AuthorizationHTTP header:

但是,要真正按预期使用 HTTP 协议,您应该使用AuthorizationHTTP 标头:

Authorization: MyScheme 123456:abcde...

The content of this header is entirely up to you. It usually specifies an authorization method like Basic, followed by whatever you want to require for authentication. This can simply be the username and password, a hash of them, an opaque token the client has obtained at some point or anything else really.

此标题的内容完全取决于您。它通常指定一种授权方法,如Basic,然后是您想要进行身份验证所需的任何内容。这可以只是用户名和密码,它们的散列,客户端在某个时候获得的不透明令牌或其他任何东西。

I'd recommend a token system or a request signing system, with the latter being very much preferred. In a request signing system, the client has to obtain a token from you. It then sends a hash of this token and certain characteristics of the request to authenticate the request, e.g. sha1(Token + Timestamp + Request URL + Request Body). Your server can validate this without the client having to send the token in plain text on each request.

我建议使用令牌系统或请求签名系统,后者是非常受欢迎的。在请求签名系统中,客户端必须从您那里获取令牌。然后它发送这个令牌的散列和请求的某些特征来验证请求,例如sha1(Token + Timestamp + Request URL + Request Body)。您的服务器可以验证这一点,而客户端不必在每个请求中以纯文本形式发送令牌。

How do I make the token only valid for a specific time?

如何使令牌仅在特定时间有效?

You save the token server-side with an expiration timestamp and check against it.

您使用到期时间戳保存令牌服务器端并检查它。

回答by Shiki

Here's a questionabout token-based authentication. I think the most common token-based authentication today is OAuth. But to answer your questions:

这里有一个问题,关于基于令牌的认证。我认为当今最常见的基于令牌的身份验证是OAuth。但是要回答您的问题:

On a GET: Is the token send visible? (isn't that unsafe?)

在 GET 上:令牌发送可见吗?(这不是不安全吗?)

You can pass your tokens through HTTP headers so they are not so easily seen. OAuth allows this. Note that the tokens are still visible, they're just not in the GETquery parameters.

您可以通过 HTTP 标头传递您的令牌,这样它们就不容易被看到。OAuth允许这样做。请注意,令牌仍然可见,只是不在GET查询参数中。

How do I make the token only valid for a specific time?

如何使令牌仅在特定时间有效?

Since you control (create) the tokens, you can set expiry dates for each token. On every request of your API, you should just check your token storage (e.g. Database) if the given token is still valid. If it is not, then you can abort the request (maybe return a HTTP 401 error).

由于您控制(创建)令牌,您可以为每个令牌设置到期日期。对于 API 的每个请求,如果给定的令牌仍然有效,您应该只检查您的令牌存储(例如数据库)。如果不是,那么您可以中止请求(可能返回 HTTP 401 错误)。

回答by Zedd Index

You can use fire-base php JWT (JSON Web Token) for token based authentication.

您可以使用 fire-base php JWT (JSON Web Token) 进行基于令牌的身份验证。

1)Install php jwt by running composer command composer require firebase/php-jwt

1) 通过运行 composer 命令composer require firebase/php-jwt安装 php jwt

   require_once('vendor/autoload.php');
   use \Firebase\JWT\JWT; 
   define('SECRET_KEY','Your-Secret-Key')  // secret key can be a random string  and keep in secret from anyone
   define('ALGORITHM','HS512')

After that Generate your token

之后生成你的令牌

$tokenId    = base64_encode(mcrypt_create_iv(32));
                $issuedAt   = time();
                $notBefore  = $issuedAt + 10;  //Adding 10 seconds
                $expire     = $notBefore + 7200; // Adding 60 seconds
                $serverName = 'http://localhost/php-json/'; /// set your domain name 


                /*
                 * Create the token as an array
                 */
                $data = [
                    'iat'  => $issuedAt,         // Issued at: time when the token was generated
                    'jti'  => $tokenId,          // Json Token Id: an unique identifier for the token
                    'iss'  => $serverName,       // Issuer
                    'nbf'  => $notBefore,        // Not before
                    'exp'  => $expire,           // Expire
                    'data' => [                  // Data related to the logged user you can set your required data
                'id'   => "set your current logged user-id", // id from the users table
                 'name' => "logged user name", //  name
                              ]
                ];
              $secretKey = base64_decode(SECRET_KEY);
              /// Here we will transform this array into JWT:
              $jwt = JWT::encode(
                        $data, //Data to be encoded in the JWT
                        $secretKey, // The signing key
                         ALGORITHM 
                       ); 
             $unencodedArray = ['jwt' => $jwt];

provide this token to your user "$jwt" . On each request user need to send token value with each request to validate user.

将此令牌提供给您的用户“ $jwt”。在每个请求上,用户需要随每个请求发送令牌值以验证用户。

 try {
           $secretKey = base64_decode(SECRET_KEY); 
           $DecodedDataArray = JWT::decode($_REQUEST['tokVal'], $secretKey, array(ALGORITHM));

           echo  "{'status' : 'success' ,'data':".json_encode($DecodedDataArray)." }";die();

           } catch (Exception $e) {
            echo "{'status' : 'fail' ,'msg':'Unauthorized'}";die();
           }

You can get step by step full configurations for php token based authentication

您可以逐步获得基于 php 令牌的身份验证的完整配置