当前位置:网站首页>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 边栏推荐
- redis原理和使用-基本特性
- ES6模块化导入导出)(实现页面嵌套)
- 机器学习中的概率模型
- 力扣题DFS
- Store a group of positive and negative numbers respectively, and count the number of 0 -- assembly language implementation
- 209. Subarray with the smallest length
- JS file import of node
- Mutual transformation of array structure and tree structure
- Node-v download and application, ES6 module import and export
- Babbitt | metauniverse daily must read: does the future of metauniverse belong to large technology companies or to the decentralized Web3 world
猜你喜欢

Nuxt - Project packaging deployment and online to server process (SSR server rendering)

CSDN Top1 "how does a Virgo procedural ape" become a blogger with millions of fans through writing?

Day06 operation -- addition, deletion, modification and query

ES6模块化导入导出)(实现页面嵌套)

Web概述和B/S架构

The idea shortcut key ALT realizes the whole column operation

Review notes of Microcomputer Principles -- zoufengxing

day06 作业--技能题2

2022茶艺师(中级)特种作业证考试题库模拟考试平台操作

网络安全漫山遍野的高大上名词之后的攻防策略本质
随机推荐
Zipkin安装和使用
day06 作业---技能题7
Pytoch learning - from tensor to LR
深度学习常用激活函数总结
TCP solves the problem of short write
公告 | FISCO BCOS v3.0-rc4发布,新增Max版,可支撑海量交易上链
谷粒学院的全部学习源码
Qtcreator reports an error: you need to set an executable in the custom run configuration
756. 蛇形矩阵
分布式跟踪系统选型与实践
【无标题】
Uploading pictures on Alibaba cloud OSS
(2006,Mysql Server has gone away)问题处理
JDBC database connection pool (Druid Technology)
[database] gbase 8A MPP cluster v95 installation and uninstall
js闭包:函数和其词法环境的绑定
day06 作业--技能题1
Probability model in machine learning
数据库操作 题目二
Day06 homework - skill question 7