当前位置:网站首页>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 边栏推荐
- Day 6 summary & database operation
- day06 作业---技能题7
- Sklearn machine learning foundation (linear regression, under fitting, over fitting, ridge regression, model loading and saving)
- JS file import of node
- 209. Subarray with the smallest length
- 网络安全漫山遍野的高大上名词之后的攻防策略本质
- Web概述和B/S架构
- zsh: command not found: nvm
- mysql函数
- 《Datawhale熊猫书》出版了!
猜你喜欢

(2006,Mysql Server has gone away)问题处理

Day06 homework -- skill question 2

网络安全漫山遍野的高大上名词之后的攻防策略本质

Web概述和B/S架构

Day06 homework - skill question 6

Dynamic SQL and exceptions of pl/sql

Okaleido launched the fusion mining mode, which is the only way for Oka to verify the current output

03 exception handling, state keeping, request hook -- 04 large project structure and blueprint

idea快捷键 alt实现整列操作

堆外内存的使用
随机推荐
李沐d2l(六)---模型选择
数据库操作技能7
力扣——二叉树剪枝
Regular expression: judge whether it conforms to USD format
Zipkin安装和使用
at、crontab
基于序的评价指标 (特别针对推荐系统和多标签学习)
How to quickly learn a programming language
本地缓存
TCP solves the problem of short write
Day06 homework - skill question 7
NFT与数字藏品到底有何区别?
数据库操作 题目二
【ARKit、RealityKit】把图片转为3D模型
The lessons of 2000. Web3 = the third industrial revolution?
Learn more about the difference between B-tree and b+tree
十大蓝筹NFT近半年数据横向对比
[eslint] Failed to load parser ‘@typescript-eslint/parser‘ declared in ‘package. json » eslint-confi
《Datawhale熊猫书》出版了!
2022茶艺师(中级)特种作业证考试题库模拟考试平台操作