当前位置:网站首页>Apple generated and verified tokens for PHP
Apple generated and verified tokens for PHP
2022-07-26 09:07:00 【Angry devil】
One 、 Scenario description
Two days before ,APP Because there are other third-party logins, only apple logins are ignored , therefore , Was rejected by the red fruit ! therefore , Develop Apple login , Put on the agenda , so , There is this post “Generate and Validate Tokens”. Apple development documentation address :https://developer.apple.com/documentation/sign_in_with_apple/generate_and_validate_tokens
Two 、 Key places
1、 adopt Apple authorization_code Go to request Apple's official interface , Get the returned data
Request parameters ,grant_type, If you choose authorization_code, Then it can only be passed code; conversely , You can only pass refresh_token
2、 For return data parsing , Because we need to use it id_token Medium sub, therefore , Need to deal with JWT Inverse decoding ( There is a detour here , Make a note of )
Be careful , There is no need to gitHub Upper PHP Of jwt The components of , Take it directly payload part , In one way , It can be solved !3、 ... and 、 Code section
<?php
namespace App\Repositories;
/**
* ||--------------------------------------------------------------------------------------------------------------
* | # Apple Generate and verify tokens - Logical processing
* ||——————————————————————————————————————————————————————————————————————————————————————————————————————————————
* | Author:NangongYi
* | Time:2020/11/17 10:52
* | Power: Used to handle Apple login , Request and decoding processing for generating and verifying tokens
* ||--------------------------------------------------------------------------------------------------------------
*/
class AppleService
{
/**
* Private property
*/
protected $jwt;
/**
* Request address
*/
const URL = 'https://appleid.apple.com/auth/token';
/**
* Apple - Web Service endpoint Generate and verify tokens
*
* @param {string} $code Apple authorization_code
* @return {string} sub Customer confidential subject
*/
public function appleCheck($code)
{
$data = [
'client_id' => config('apple.client_id'),
'client_secret' => config('apple.client_secret'),
'grant_type' => config('apple.grant_type'),
'code' => $code
];
$d_string = '';
foreach ($data as $key=>$val) {
$d_string .= '&'.$key.'='.$val;
}
$d_string = substr($d_string, 1);
$url = self::URL;
$res = $this->curlPost($url, $d_string);
$id_token = isset($res['id_token'])?$res['id_token']:'';
$id_token_arr = explode('.',$id_token);
$payload = $id_token_arr[1];
$data = json_decode($this->base64UrlDecode($payload), true);
return isset($data['sub']) ? $data['sub'] : '';
}
/**
* Pass in an array for HTTP POST request
*
* @param {string} $url Request address
* @param {string} $data Request data
* @param {array} $header Request header data
* @return {mixed}
*/
public function curlPost($url , $data)
{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => array(
"Content-Type: application/x-www-form-urlencoded"
),
));
$response = curl_exec($curl);
curl_close($curl);
return json_decode($response, true);
}
/**
* base64UrlEncode https://jwt.io/ in base64UrlEncode Decoding implementation
*
* @param {string} $input String to decode
* @return {bool}|{string}
*/
public function base64UrlDecode($input)
{
$remainder = strlen($input) % 4;
if ($remainder) {
$addlen = 4 - $remainder;
$input .= str_repeat('=', $addlen);
}
return base64_decode(strtr($input, '-_', '+/'));
}
}Four 、 The final summary
I haven't touched before JWT Something about , It's a relatively unfamiliar point .
Json web token (JWT), Is a kind of implementation based on the JSON Open standards for ((RFC 7519). The token Designed to be compact and safe , Especially for single sign in of distributed sites (SSO) scene .
JWT The composition of the
The first part is what we call the head (header), The second part is called load (payload, Similar to what is carried on an aircraft ), The third part is visa (signature).
header
jwt Two parts of information are carried in the head of :
Declaration type , Here is jwt
Algorithm of declaration encryption Usually used directly HMAC SHA256
The whole head is like this JSON:
{
'typ': 'JWT',
'alg': 'HS256'
}
Then the head base64 encryption ( The encryption can be decrypted symmetrically ), It makes up the first part .
eyJ0eXAiOifgH1QiLCJhbGciasDIUzI1NiJ9
playload The load is where the payload is stored .
A statement registered in the standard
Public statement
Private statement
A statement registered in the standard ( Recommended but not mandatory ) :
iss: jwt Issuer
sub: jwt Target users
aud: receive jwt On the side of
exp: jwt The expiration time of , The expiration time must be greater than the issuing time
nbf: Define before what time , The jwt They're not available .
iat: jwt Issued on
jti: jwt Unique identity of , Mainly used as a one-off token, To avoid replay attacks .
Public statement :
Public statements can add any information , Generally add relevant information of users or other necessary information required by business . But it's not recommended to add sensitive information , Because this part can be decrypted on the client side .
Private statement :
A private statement is a statement defined by both the provider and the consumer , It is generally not recommended to store sensitive information , because base64 It's symmetric decryption , It means that this part of information can be classified as clear text information .
Define a payload:
{
"sub": "147258369",
"name": "Jean",
"admin": true
}
And then it's done base64 encryption , obtain Jwt Part two .
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9
signature
jwt The third part of the is a visa information , This visa information consists of three parts :
header (base64 After )
payload (base64 After )
secret
This part needs base64 Encrypted header and base64 Encrypted payload Use . String of connections , And then through header Adding salt in the encryption method stated in secret Combination encryption , And then it forms jwt Part three .
// javascript
var encodedString = base64UrlEncode(header) + '.' + base64UrlEncode(payload);
var signature = HMACSHA256(encodedString, 'secret'); // TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
Use these three parts with . Connect to a complete string , The final jwt.
JWT Use of
JWT The declaration of is generally used to pass the authenticated user identity information between the identity provider and the service provider , To get resources from the resource server , You can also add some additional declaration information that other business logic requires , The token It can also be used directly for authentication , It can also be encrypted .
advantage
because json The generality of , therefore JWT Cross language support is available , image JAVA,JavaScript,NodeJS,PHP And many other languages can be used .
Because of the payload part , therefore JWT It can store some non sensitive information necessary for other business logic in itself .
Easy to transmit ,jwt It's very simple , Bytes are very small , So it's very easy to transmit .
It doesn't need to save session information on the server , So it's easy to apply extensions
Safety related
Should not be in jwt Of payload Some store sensitive information , Because this part is Client decryption Part of .
Well protected secret Private key , The private key is very important .
If possible , Please use https agreement 边栏推荐
- PHP和MySQL获取week值不一致的处理
- Pat grade a a1076 forwards on Weibo
- NTT(快速数论变换)多项式求逆 一千五百字解析
- Dynamic SQL and exceptions of pl/sql
- Probability model in machine learning
- Okaleido launched the fusion mining mode, which is the only way for Oka to verify the current output
- Nuxt - 项目打包部署及上线到服务器流程(SSR 服务端渲染)
- 机器学习中的概率模型
- Which of count (*), count (primary key ID), count (field) and count (1) in MySQL is more efficient? "Suggested collection"
- What is the difference between NFT and digital collections?
猜你喜欢

Database operation topic 2

Announcement | FISCO bcos v3.0-rc4 is released, and the new Max version can support massive transactions on the chain

187. Repeated DNA sequence

Advanced mathematics | Takeshi's "classic series" daily question train of thought and summary of error prone points

Sklearn machine learning foundation (linear regression, under fitting, over fitting, ridge regression, model loading and saving)

What is the difference between NFT and digital collections?

Uni app simple mall production

多项式开根

The idea shortcut key ALT realizes the whole column operation

pycharm 打开多个项目的两种小技巧
随机推荐
“No input file specified “问题的处理
《Datawhale熊猫书》出版了!
day06 作业---技能题7
ES6 modular import and export) (realize page nesting)
Datawhale panda book has been published!
ext3文件系统的一个目录下,无法创建子文件夹,但可以创建文件
Database operation skills 6
SQL入门——组合表
JS file import of node
2022茶艺师(中级)特种作业证考试题库模拟考试平台操作
The lessons of 2000. Web3 = the third industrial revolution?
pycharm 打开多个项目的两种小技巧
838. 堆排序
Pytoch realizes logistic regression
[eslint] Failed to load parser ‘@typescript-eslint/parser‘ declared in ‘package. json » eslint-confi
ONTAP 9文件系统的限制
基于序的评价指标 (特别针对推荐系统和多标签学习)
Flask project learning (I) -- sayhello
ext4文件系统打开了DIR_NLINK特性后,link_count超过65000的后使用link_count=1来表示数量不可知
JDBC数据库连接池(Druid技术)