yannstatic/static/2018/11/23/Using-a-JSON-Web-Token-in-PHP.html

2297 lines
206 KiB
HTML
Raw Normal View History

2024-10-31 20:18:37 +01:00
<!DOCTYPE html><html lang="fr">
<head><meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"><title>JSON Web Token (JWT) en PHP - YannStatic</title>
<meta name="description" content="JSON Web Token (JWT)">
<link rel="canonical" href="https://static.rnmkcy.eu/2018/11/23/Using-a-JSON-Web-Token-in-PHP.html"><link rel="alternate" type="application/rss+xml" title="YannStatic" href="/feed.xml">
<!-- - include head/favicon.html - -->
<link rel="shortcut icon" type="image/png" href="/assets/favicon/favicon.png"><link rel="stylesheet" href="/assets/css/main.css"><link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" ><!-- start custom head snippets --><link rel="stylesheet" href="/assets/css/expand.css">
<!-- end custom head snippets --><script>(function() {
window.isArray = function(val) {
return Object.prototype.toString.call(val) === '[object Array]';
};
window.isString = function(val) {
return typeof val === 'string';
};
window.hasEvent = function(event) {
return 'on'.concat(event) in window.document;
};
window.isOverallScroller = function(node) {
return node === document.documentElement || node === document.body || node === window;
};
window.isFormElement = function(node) {
var tagName = node.tagName;
return tagName === 'INPUT' || tagName === 'SELECT' || tagName === 'TEXTAREA';
};
window.pageLoad = (function () {
var loaded = false, cbs = [];
window.addEventListener('load', function () {
var i;
loaded = true;
if (cbs.length > 0) {
for (i = 0; i < cbs.length; i++) {
cbs[i]();
}
}
});
return {
then: function(cb) {
cb && (loaded ? cb() : (cbs.push(cb)));
}
};
})();
})();
(function() {
window.throttle = function(func, wait) {
var args, result, thisArg, timeoutId, lastCalled = 0;
function trailingCall() {
lastCalled = new Date;
timeoutId = null;
result = func.apply(thisArg, args);
}
return function() {
var now = new Date,
remaining = wait - (now - lastCalled);
args = arguments;
thisArg = this;
if (remaining <= 0) {
clearTimeout(timeoutId);
timeoutId = null;
lastCalled = now;
result = func.apply(thisArg, args);
} else if (!timeoutId) {
timeoutId = setTimeout(trailingCall, remaining);
}
return result;
};
};
})();
(function() {
var Set = (function() {
var add = function(item) {
var i, data = this._data;
for (i = 0; i < data.length; i++) {
if (data[i] === item) {
return;
}
}
this.size ++;
data.push(item);
return data;
};
var Set = function(data) {
this.size = 0;
this._data = [];
var i;
if (data.length > 0) {
for (i = 0; i < data.length; i++) {
add.call(this, data[i]);
}
}
};
Set.prototype.add = add;
Set.prototype.get = function(index) { return this._data[index]; };
Set.prototype.has = function(item) {
var i, data = this._data;
for (i = 0; i < data.length; i++) {
if (this.get(i) === item) {
return true;
}
}
return false;
};
Set.prototype.is = function(map) {
if (map._data.length !== this._data.length) { return false; }
var i, j, flag, tData = this._data, mData = map._data;
for (i = 0; i < tData.length; i++) {
for (flag = false, j = 0; j < mData.length; j++) {
if (tData[i] === mData[j]) {
flag = true;
break;
}
}
if (!flag) { return false; }
}
return true;
};
Set.prototype.values = function() {
return this._data;
};
return Set;
})();
window.Lazyload = (function(doc) {
var queue = {js: [], css: []}, sources = {js: {}, css: {}}, context = this;
var createNode = function(name, attrs) {
var node = doc.createElement(name), attr;
for (attr in attrs) {
if (attrs.hasOwnProperty(attr)) {
node.setAttribute(attr, attrs[attr]);
}
}
return node;
};
var end = function(type, url) {
var s, q, qi, cbs, i, j, cur, val, flag;
if (type === 'js' || type ==='css') {
s = sources[type], q = queue[type];
s[url] = true;
for (i = 0; i < q.length; i++) {
cur = q[i];
if (cur.urls.has(url)) {
qi = cur, val = qi.urls.values();
qi && (cbs = qi.callbacks);
for (flag = true, j = 0; j < val.length; j++) {
cur = val[j];
if (!s[cur]) {
flag = false;
}
}
if (flag && cbs && cbs.length > 0) {
for (j = 0; j < cbs.length; j++) {
cbs[j].call(context);
}
qi.load = true;
}
}
}
}
};
var load = function(type, urls, callback) {
var s, q, qi, node, i, cur,
_urls = typeof urls === 'string' ? new Set([urls]) : new Set(urls), val, url;
if (type === 'js' || type ==='css') {
s = sources[type], q = queue[type];
for (i = 0; i < q.length; i++) {
cur = q[i];
if (_urls.is(cur.urls)) {
qi = cur;
break;
}
}
val = _urls.values();
if (qi) {
callback && (qi.load || qi.callbacks.push(callback));
callback && (qi.load && callback());
} else {
q.push({
urls: _urls,
callbacks: callback ? [callback] : [],
load: false
});
for (i = 0; i < val.length; i++) {
node = null, url = val[i];
if (s[url] === undefined) {
(type === 'js' ) && (node = createNode('script', { src: url }));
(type === 'css') && (node = createNode('link', { rel: 'stylesheet', href: url }));
if (node) {
node.onload = (function(type, url) {
return function() {
end(type, url);
};
})(type, url);
(doc.head || doc.body).appendChild(node);
s[url] = false;
}
}
}
}
}
};
return {
js: function(url, callback) {
load('js', url, callback);
},
css: function(url, callback) {
load('css', url, callback);
}
};
})(this.document);
})();
</script><script>
(function() {
var TEXT_VARIABLES = {
version: '2.2.6',
sources: {
font_awesome: 'https://use.fontawesome.com/releases/v5.0.13/css/all.css',
jquery: '/assets/js/jquery.min.js',
leancloud_js_sdk: '//cdn.jsdelivr.net/npm/leancloud-storage@3.13.2/dist/av-min.js',
chart: 'https://cdn.bootcss.com/Chart.js/2.7.2/Chart.bundle.min.js',
gitalk: {
js: 'https://cdn.bootcss.com/gitalk/1.2.2/gitalk.min.js',
css: 'https://cdn.bootcss.com/gitalk/1.2.2/gitalk.min.css'
},
valine: 'https://unpkg.com/valine/dist/Valine.min.js'
},
site: {
toc: {
selectors: 'h1,h2,h3'
}
},
paths: {
search_js: '/assets/search.js'
}
};
window.TEXT_VARIABLES = TEXT_VARIABLES;
})();
</script>
</head>
<body>
<div class="root" data-is-touch="false">
<div class="layout--page js-page-root"><!----><div class="page__main js-page-main page__viewport hide-footer has-aside has-aside cell cell--auto">
<div class="page__main-inner"><div class="page__header d-print-none"><header class="header"><div class="main">
<div class="header__title">
<div class="header__brand"><svg id="svg" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="400" height="478.9473684210526" viewBox="0, 0, 400,478.9473684210526"><g id="svgg"><path id="path0" d="M308.400 56.805 C 306.970 56.966,303.280 57.385,300.200 57.738 C 290.906 58.803,278.299 59.676,269.200 59.887 L 260.600 60.085 259.400 61.171 C 258.010 62.428,256.198 63.600,255.645 63.600 C 255.070 63.600,252.887 65.897,252.598 66.806 C 252.460 67.243,252.206 67.600,252.034 67.600 C 251.397 67.600,247.206 71.509,247.202 72.107 C 247.201 72.275,246.390 73.190,245.400 74.138 C 243.961 75.517,243.598 76.137,243.592 77.231 C 243.579 79.293,241.785 83.966,240.470 85.364 C 239.176 86.740,238.522 88.365,237.991 91.521 C 237.631 93.665,236.114 97.200,235.554 97.200 C 234.938 97.200,232.737 102.354,232.450 104.472 C 232.158 106.625,230.879 109.226,229.535 110.400 C 228.933 110.926,228.171 113.162,226.434 119.500 C 226.178 120.435,225.795 121.200,225.584 121.200 C 225.373 121.200,225.200 121.476,225.200 121.813 C 225.200 122.149,224.885 122.541,224.500 122.683 C 223.606 123.013,223.214 123.593,223.204 124.600 C 223.183 126.555,220.763 132.911,219.410 134.562 C 218.443 135.742,217.876 136.956,217.599 138.440 C 217.041 141.424,215.177 146.434,214.532 146.681 C 214.240 146.794,214.000 147.055,214.000 147.261 C 214.000 147.467,213.550 148.086,213.000 148.636 C 212.450 149.186,212.000 149.893,212.000 150.208 C 212.000 151.386,208.441 154.450,207.597 153.998 C 206.319 153.315,204.913 150.379,204.633 147.811 C 204.365 145.357,202.848 142.147,201.759 141.729 C 200.967 141.425,199.200 137.451,199.200 135.974 C 199.200 134.629,198.435 133.224,196.660 131.311 C 195.363 129.913,194.572 128.123,193.870 125.000 C 193.623 123.900,193.236 122.793,193.010 122.540 C 190.863 120.133,190.147 118.880,188.978 115.481 C 188.100 112.928,187.151 111.003,186.254 109.955 C 185.358 108.908,184.518 107.204,183.847 105.073 C 183.280 103.273,182.497 101.329,182.108 100.753 C 181.719 100.177,180.904 98.997,180.298 98.131 C 179.693 97.265,178.939 95.576,178.624 94.378 C 178.041 92.159,177.125 90.326,175.023 87.168 C 174.375 86.196,173.619 84.539,173.342 83.486 C 172.800 81.429,171.529 79.567,170.131 78.785 C 169.654 78.517,168.697 77.511,168.006 76.549 C 167.316 75.587,166.594 74.800,166.402 74.800 C 166.210 74.800,164.869 73.633,163.421 72.206 C 160.103 68.936,161.107 69.109,146.550 69.301 C 133.437 69.474,128.581 70.162,126.618 72.124 C 126.248 72.495,125.462 72.904,124.872 73.033 C 124.282 73.163,123.088 73.536,122.219 73.863 C 121.349 74.191,119.028 74.638,117.061 74.858 C 113.514 75.254,109.970 76.350,108.782 77.419 C 107.652 78.436,100.146 80.400,97.388 80.400 C 95.775 80.400,93.167 81.360,91.200 82.679 C 90.430 83.195,89.113 83.804,88.274 84.031 C 85.875 84.681,78.799 90.910,74.400 96.243 L 73.400 97.456 73.455 106.028 C 73.526 117.055,74.527 121.238,77.820 124.263 C 78.919 125.273,80.400 127.902,80.400 128.842 C 80.400 129.202,81.075 130.256,81.900 131.186 C 83.563 133.059,85.497 136.346,86.039 138.216 C 86.233 138.886,87.203 140.207,88.196 141.153 C 89.188 142.098,90.000 143.104,90.000 143.388 C 90.000 144.337,92.129 148.594,92.869 149.123 C 93.271 149.410,93.600 149.831,93.600 150.059 C 93.600 150.286,93.932 150.771,94.337 151.136 C 94.743 151.501,95.598 153.004,96.237 154.475 C 96.877 155.947,97.760 157.351,98.200 157.596 C 98.640 157.841,99.900 159.943,101.000 162.267 C 102.207 164.817,103.327 166.644,103.825 166.876 C 104.278 167.087,105.065 168.101,105.573 169.130 C 107.658 173.348,108.097 174.093,110.006 176.647 C 111.103 178.114,112.000 179.725,112.000 180.227 C 112.000 181.048,113.425 183.163,114.678 184.200 C 115.295 184.711,117.396 188.733,117.720 190.022 C 117.855 190.562,118.603 191.633,119.381 192.402 C 120.160 193.171,121.496 195.258,122.351 197.039 C 123.206 198.820,124.167 200.378,124.487 200.501 C 124.807 200.624,125.953 202.496,127.034 204.662 C 128.114 206.828,129.676 209.299,130.505 210.153 C 131.333 211.007,132.124 212.177,132.262 212.753 C 132.618 214.239,134.291 217.048,136.288 219.5
" href="/">YannStatic</a></div><!--<button class="button button--secondary button--circle search-button js-search-toggle"><i class="fas fa-search"></i></button>--><!-- <li><button class="button button--secondary button--circle search-button js-search-toggle"><i class="fas fa-search"></i></button></li> -->
<!-- Champ de recherche -->
<div id="searchbox" class="search search--dark" style="visibility: visible">
<div class="main">
<div class="search__header"></div>
<div class="search-bar">
<div class="search-box js-search-box">
<div class="search-box__icon-search"><i class="fas fa-search"></i></div>
<input id="search-input" type="text" />
<!-- <div class="search-box__icon-clear js-icon-clear">
<a><i class="fas fa-times"></i></a>
</div> -->
</div>
</div>
</div>
</div>
<!-- Script pointing to search-script.js -->
<script>/*!
* Simple-Jekyll-Search
* Copyright 2015-2020, Christian Fei
* Licensed under the MIT License.
*/
(function(){
'use strict'
var _$Templater_7 = {
compile: compile,
setOptions: setOptions
}
const options = {}
options.pattern = /\{(.*?)\}/g
options.template = ''
options.middleware = function () {}
function setOptions (_options) {
options.pattern = _options.pattern || options.pattern
options.template = _options.template || options.template
if (typeof _options.middleware === 'function') {
options.middleware = _options.middleware
}
}
function compile (data) {
return options.template.replace(options.pattern, function (match, prop) {
const value = options.middleware(prop, data[prop], options.template)
if (typeof value !== 'undefined') {
return value
}
return data[prop] || match
})
}
'use strict';
function fuzzysearch (needle, haystack) {
var tlen = haystack.length;
var qlen = needle.length;
if (qlen > tlen) {
return false;
}
if (qlen === tlen) {
return needle === haystack;
}
outer: for (var i = 0, j = 0; i < qlen; i++) {
var nch = needle.charCodeAt(i);
while (j < tlen) {
if (haystack.charCodeAt(j++) === nch) {
continue outer;
}
}
return false;
}
return true;
}
var _$fuzzysearch_1 = fuzzysearch;
'use strict'
/* removed: const _$fuzzysearch_1 = require('fuzzysearch') */;
var _$FuzzySearchStrategy_5 = new FuzzySearchStrategy()
function FuzzySearchStrategy () {
this.matches = function (string, crit) {
return _$fuzzysearch_1(crit.toLowerCase(), string.toLowerCase())
}
}
'use strict'
var _$LiteralSearchStrategy_6 = new LiteralSearchStrategy()
function LiteralSearchStrategy () {
this.matches = function (str, crit) {
if (!str) return false
str = str.trim().toLowerCase()
crit = crit.trim().toLowerCase()
return crit.split(' ').filter(function (word) {
return str.indexOf(word) >= 0
}).length === crit.split(' ').length
}
}
'use strict'
var _$Repository_4 = {
put: put,
clear: clear,
search: search,
setOptions: __setOptions_4
}
/* removed: const _$FuzzySearchStrategy_5 = require('./SearchStrategies/FuzzySearchStrategy') */;
/* removed: const _$LiteralSearchStrategy_6 = require('./SearchStrategies/LiteralSearchStrategy') */;
function NoSort () {
return 0
}
const data = []
let opt = {}
opt.fuzzy = false
opt.limit = 10
opt.searchStrategy = opt.fuzzy ? _$FuzzySearchStrategy_5 : _$LiteralSearchStrategy_6
opt.sort = NoSort
opt.exclude = []
function put (data) {
if (isObject(data)) {
return addObject(data)
}
if (isArray(data)) {
return addArray(data)
}
return undefined
}
function clear () {
data.length = 0
return data
}
function isObject (obj) {
return Boolean(obj) && Object.prototype.toString.call(obj) === '[object Object]'
}
function isArray (obj) {
return Boolean(obj) && Object.prototype.toString.call(obj) === '[object Array]'
}
function addObject (_data) {
data.push(_data)
return data
}
function addArray (_data) {
const added = []
clear()
for (let i = 0, len = _data.length; i < len; i++) {
if (isObject(_data[i])) {
added.push(addObject(_data[i]))
}
}
return added
}
function search (crit) {
if (!crit) {
return []
}
return findMatches(data, crit, opt.searchStrategy, opt).sort(opt.sort)
}
function __setOptions_4 (_opt) {
opt = _opt || {}
opt.fuzzy = _opt.fuzzy || false
opt.limit = _opt.limit || 10
opt.searchStrategy = _opt.fuzzy ? _$FuzzySearchStrategy_5 : _$LiteralSearchStrategy_6
opt.sort = _opt.sort || NoSort
opt.exclude = _opt.exclude || []
}
function findMatches (data, crit, strategy, opt) {
const matches = []
for (let i = 0; i < data.length && matches.length < opt.limit; i++) {
const match = findMatchesInObject(data[i], crit, strategy, opt)
if (match) {
matches.push(match)
}
}
return matches
}
function findMatchesInObject (obj, crit, strategy, opt) {
for (const key in obj) {
if (!isExcluded(obj[key], opt.exclude) && strategy.matches(obj[key], crit)) {
return obj
}
}
}
function isExcluded (term, excludedTerms) {
for (let i = 0, len = excludedTerms.length; i < len; i++) {
const excludedTerm = excludedTerms[i]
if (new RegExp(excludedTerm).test(term)) {
return true
}
}
return false
}
/* globals ActiveXObject:false */
'use strict'
var _$JSONLoader_2 = {
load: load
}
function load (location, callback) {
const xhr = getXHR()
xhr.open('GET', location, true)
xhr.onreadystatechange = createStateChangeListener(xhr, callback)
xhr.send()
}
function createStateChangeListener (xhr, callback) {
return function () {
if (xhr.readyState === 4 && xhr.status === 200) {
try {
callback(null, JSON.parse(xhr.responseText))
} catch (err) {
callback(err, null)
}
}
}
}
function getXHR () {
return window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP')
}
'use strict'
var _$OptionsValidator_3 = function OptionsValidator (params) {
if (!validateParams(params)) {
throw new Error('-- OptionsValidator: required options missing')
}
if (!(this instanceof OptionsValidator)) {
return new OptionsValidator(params)
}
const requiredOptions = params.required
this.getRequiredOptions = function () {
return requiredOptions
}
this.validate = function (parameters) {
const errors = []
requiredOptions.forEach(function (requiredOptionName) {
if (typeof parameters[requiredOptionName] === 'undefined') {
errors.push(requiredOptionName)
}
})
return errors
}
function validateParams (params) {
if (!params) {
return false
}
return typeof params.required !== 'undefined' && params.required instanceof Array
}
}
'use strict'
var _$utils_9 = {
merge: merge,
isJSON: isJSON
}
function merge (defaultParams, mergeParams) {
const mergedOptions = {}
for (const option in defaultParams) {
mergedOptions[option] = defaultParams[option]
if (typeof mergeParams[option] !== 'undefined') {
mergedOptions[option] = mergeParams[option]
}
}
return mergedOptions
}
function isJSON (json) {
try {
if (json instanceof Object && JSON.parse(JSON.stringify(json))) {
return true
}
return false
} catch (err) {
return false
}
}
var _$src_8 = {};
(function (window) {
'use strict'
let options = {
searchInput: null,
resultsContainer: null,
json: [],
success: Function.prototype,
searchResultTemplate: '<li><a href="{url}" title="{desc}">{title}</a></li>',
templateMiddleware: Function.prototype,
sortMiddleware: function () {
return 0
},
noResultsText: 'No results found',
limit: 10,
fuzzy: false,
debounceTime: null,
exclude: []
}
let debounceTimerHandle
const debounce = function (func, delayMillis) {
if (delayMillis) {
clearTimeout(debounceTimerHandle)
debounceTimerHandle = setTimeout(func, delayMillis)
} else {
func.call()
}
}
const requiredOptions = ['searchInput', 'resultsContainer', 'json']
/* removed: const _$Templater_7 = require('./Templater') */;
/* removed: const _$Repository_4 = require('./Repository') */;
/* removed: const _$JSONLoader_2 = require('./JSONLoader') */;
const optionsValidator = _$OptionsValidator_3({
required: requiredOptions
})
/* removed: const _$utils_9 = require('./utils') */;
window.SimpleJekyllSearch = function (_options) {
const errors = optionsValidator.validate(_options)
if (errors.length > 0) {
throwError('You must specify the following required options: ' + requiredOptions)
}
options = _$utils_9.merge(options, _options)
_$Templater_7.setOptions({
template: options.searchResultTemplate,
middleware: options.templateMiddleware
})
_$Repository_4.setOptions({
fuzzy: options.fuzzy,
limit: options.limit,
sort: options.sortMiddleware,
exclude: options.exclude
})
if (_$utils_9.isJSON(options.json)) {
initWithJSON(options.json)
} else {
initWithURL(options.json)
}
const rv = {
search: search
}
typeof options.success === 'function' && options.success.call(rv)
return rv
}
function initWithJSON (json) {
_$Repository_4.put(json)
registerInput()
}
function initWithURL (url) {
_$JSONLoader_2.load(url, function (err, json) {
if (err) {
throwError('failed to get JSON (' + url + ')')
}
initWithJSON(json)
})
}
function emptyResultsContainer () {
options.resultsContainer.innerHTML = ''
}
function appendToResultsContainer (text) {
options.resultsContainer.innerHTML += text
}
function registerInput () {
options.searchInput.addEventListener('input', function (e) {
if (isWhitelistedKey(e.which)) {
emptyResultsContainer()
debounce(function () { search(e.target.value) }, options.debounceTime)
}
})
}
function search (query) {
if (isValidQuery(query)) {
emptyResultsContainer()
render(_$Repository_4.search(query), query)
}
}
function render (results, query) {
const len = results.length
if (len === 0) {
return appendToResultsContainer(options.noResultsText)
}
for (let i = 0; i < len; i++) {
results[i].query = query
appendToResultsContainer(_$Templater_7.compile(results[i]))
}
}
function isValidQuery (query) {
return query && query.length > 0
}
function isWhitelistedKey (key) {
return [13, 16, 20, 37, 38, 39, 40, 91].indexOf(key) === -1
}
function throwError (message) {
throw new Error('SimpleJekyllSearch --- ' + message)
}
})(window)
}());
</script>
<!-- Configuration -->
<script>
SimpleJekyllSearch({
searchInput: document.getElementById('search-input'),
resultsContainer: document.getElementById('results-container'),
json: '/search.json',
//searchResultTemplate: '<li><a href="https://static.rnmkcy.eu{url}">{date}&nbsp;{title}</a></li>'
searchResultTemplate: '<li><a href="{url}">{date}&nbsp;{title}</a></li>'
})
</script>
<!-- Fin déclaration champ de recherche --></div><nav class="navigation">
<ul><li class="navigation__item"><a href="/archive.html">Etiquettes</a></li><li class="navigation__item"><a href="/htmldoc.html">Documents</a></li><li class="navigation__item"><a href="/liens_ttrss.html">Liens</a></li><li class="navigation__item"><a href="/aide-jekyll-text-theme.html">Aide</a></li></ul>
</nav></div>
</header>
</div><div class="page__content"><div class ="main"><div class="grid grid--reverse">
<div class="col-main cell cell--auto"><!-- start custom main top snippet --><div id="results-container" class="search-result js-search-result"></div><!-- end custom main top snippet -->
<article itemscope itemtype="http://schema.org/Article"><div class="article__header"><header><h1 style="color:Tomato;">JSON Web Token (JWT) en PHP</h1></header></div><meta itemprop="headline" content="JSON Web Token (JWT) en PHP"><div class="article__info clearfix"><ul class="left-col menu"><li>
<a class="button button--secondary button--pill button--sm"
href="/archive.html?tag=json">json</a>
</li></ul><ul class="right-col menu"><li>
<i class="far fa-calendar-alt"></i>&nbsp;<span title="Création" style="color:#FF00FF">23&nbsp;nov.&nbsp;&nbsp;2018</span>
<span title="Modification" style="color:#00FF7F">14&nbsp;avr.&nbsp;&nbsp;2018</span></li></ul></div><meta itemprop="datePublished" content="2018-04-14T00:00:00+02:00">
<meta itemprop="keywords" content="json"><div class="js-article-content">
<div class="layout--article"><!-- start custom article top snippet -->
<style>
#myBtn {
display: none;
position: fixed;
bottom: 10px;
right: 10px;
z-index: 99;
font-size: 12px;
font-weight: bold;
border: none;
outline: none;
background-color: white;
color: black;
cursor: pointer;
padding: 5px;
border-radius: 4px;
}
#myBtn:hover {
background-color: #555;
}
</style>
<button onclick="topFunction()" id="myBtn" title="Haut de page">&#8679;</button>
<script>
//Get the button
var mybutton = document.getElementById("myBtn");
// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
mybutton.style.display = "block";
} else {
mybutton.style.display = "none";
}
}
// When the user clicks on the button, scroll to the top of the document
function topFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
</script>
<!-- end custom article top snippet -->
<div class="article__content" itemprop="articleBody"><details>
<summary><b>Afficher/cacher Sommaire</b></summary>
<!-- affichage sommaire -->
<div class="toc-aside js-toc-root"></div>
</details><h2 id="json-web-token-jwt">JSON Web Token (JWT)</h2>
<p><em>JWT ou JSON Web Token est un standard ouvert décrit dans la RFC 7519 qui permet lauthentification dun utilisateur à laide dun jeton (token) signé</em><br />
Voir article <a href="https://www.codeheroes.fr/index.php/2018/03/23/securiser-une-api-rest/">Sécuriser une API REST (Partie 1) : Théorie</a> qui explique le JWT.</p>
<ul>
<li>Lors du premier échange, le client envoie son couple login/mot de passe au serveur;</li>
<li>Si le couple est valide, le serveur génère un token et lenvoie au client. Ce token permettra dauthentifier lutilisateur lors des prochains échanges;</li>
<li>Le client stocke ensuite le token en local;</li>
<li>Le token est renvoyé, par le client, pour chaque appel à lAPI (via len-tête HTTP « Authorization ») permettant ainsi dauthentifier lutilisateur.</li>
</ul>
<p><img src="/images/jwt1.png" alt="jwt" /></p>
<p>Les Tokens Web JSON se composent généralement de trois parties: un en-tête <strong>header</strong>, une charge utile <strong>payload</strong> et une <strong>signature</strong>.</p>
<h3 id="header">Header</h3>
<p>Objet JSON encodé en base64 qui représente len-tête du token avec 2 éléments</p>
<ul>
<li>Le type du token;</li>
<li>Lalgorithme utilisé pour la signature.</li>
</ul>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>{
"typ":"JWT",
"alg":"HS256"
}
</code></pre></div></div>
<p>HS256 indique que ce jeton <strong>token</strong> est signé avec HMAC-SHA256.</p>
<h3 id="payload">Payload</h3>
<p>Objet JSON encodé en base64 qui représente le corps du token pour y mettre toute information utile au serveur. Le standard définit <u>trois types de propriétés</u> (appelées <strong>claims</strong>) :</p>
<ul>
<li>réservées : Il sagit de noms réservés définis par la spécification. On y retrouve notamment :
<ul>
<li>“iss” (Issuer) : Identifie le serveur ou le système qui a émis le token;</li>
<li>“sub” (Subject) : Identifiant de lutilisateur que le token représente;</li>
<li>“aud” (Audience) : Application ou site qui reçoit le token;</li>
<li>“iat” (Issued At) : Date de génération du token;</li>
<li>“exp” (Expiration Time) : Date dexpiration du token.</li>
</ul>
</li>
<li>publiques : Noms normalisés tels que “email”, “name”, “locale”, etc… (<a href="https://www.iana.org/assignments/jwt/jwt.xhtml">JSON Web Token Claims</a> , voir tableau ci-joint)</li>
</ul>
<table>
<thead>
<tr>
<th>Claim Name</th>
<th style="text-align: center">Claim Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>iss</td>
<td style="text-align: center">Issuer</td>
</tr>
<tr>
<td>sub</td>
<td style="text-align: center">Subject</td>
</tr>
<tr>
<td>aud</td>
<td style="text-align: center">Audience</td>
</tr>
<tr>
<td>exp</td>
<td style="text-align: center">Expiration Time</td>
</tr>
<tr>
<td>nbf</td>
<td style="text-align: center">Not Before</td>
</tr>
<tr>
<td>iat</td>
<td style="text-align: center">Issued At</td>
</tr>
<tr>
<td>jti</td>
<td style="text-align: center">JWT ID</td>
</tr>
<tr>
<td>name</td>
<td style="text-align: center">Full name</td>
</tr>
<tr>
<td>given_name</td>
<td style="text-align: center">Given name(s) or first name(s)</td>
</tr>
<tr>
<td>family_name</td>
<td style="text-align: center">Surname(s) or last name(s)</td>
</tr>
<tr>
<td>middle_name</td>
<td style="text-align: center">Middle name(s)</td>
</tr>
<tr>
<td>nickname</td>
<td style="text-align: center">Casual name</td>
</tr>
<tr>
<td>preferred_username</td>
<td style="text-align: center">Shorthand name by which the End-User wishes to be referred to</td>
</tr>
<tr>
<td>profile</td>
<td style="text-align: center">Profile page URL</td>
</tr>
<tr>
<td>picture</td>
<td style="text-align: center">Profile picture URL</td>
</tr>
<tr>
<td>website</td>
<td style="text-align: center">Web page or blog URL</td>
</tr>
<tr>
<td>email</td>
<td style="text-align: center">Preferred e-mail address</td>
</tr>
<tr>
<td>email_verified</td>
<td style="text-align: center">True if the e-mail address has been verified</td>
</tr>
<tr>
<td>gender</td>
<td style="text-align: center">Gender</td>
</tr>
<tr>
<td>birthdate</td>
<td style="text-align: center">Birthday</td>
</tr>
<tr>
<td>zoneinfo</td>
<td style="text-align: center">Time zone</td>
</tr>
<tr>
<td>locale</td>
<td style="text-align: center">Locale</td>
</tr>
<tr>
<td>phone_number</td>
<td style="text-align: center">Preferred telephone number</td>
</tr>
<tr>
<td>phone_number_verified</td>
<td style="text-align: center">True if the phone number has been verified</td>
</tr>
<tr>
<td>address</td>
<td style="text-align: center">Preferred postal address</td>
</tr>
<tr>
<td>updated_at</td>
<td style="text-align: center">Time the information was last updated</td>
</tr>
<tr>
<td>azp</td>
<td style="text-align: center">Authorized party - the party to which the ID Token was issued</td>
</tr>
<tr>
<td>nonce</td>
<td style="text-align: center">Value used to associate a Client session with an ID Token</td>
</tr>
<tr>
<td>auth_time</td>
<td style="text-align: center">Time when the authentication occurred</td>
</tr>
<tr>
<td>at_hash</td>
<td style="text-align: center">Access Token hash value</td>
</tr>
<tr>
<td>c_hash</td>
<td style="text-align: center">Code hash value</td>
</tr>
<tr>
<td>acr</td>
<td style="text-align: center">Authentication Context Class Reference</td>
</tr>
<tr>
<td>amr</td>
<td style="text-align: center">Authentication Methods References</td>
</tr>
<tr>
<td>sub_jwk</td>
<td style="text-align: center">Public key used to check the signature of an ID Token</td>
</tr>
<tr>
<td>cnf</td>
<td style="text-align: center">Confirmation</td>
</tr>
<tr>
<td>sip_from_tag</td>
<td style="text-align: center">SIP From tag header field parameter value</td>
</tr>
<tr>
<td>sip_date</td>
<td style="text-align: center">SIP Date header field value</td>
</tr>
<tr>
<td>sip_callid</td>
<td style="text-align: center">SIP Call-Id header field value</td>
</tr>
<tr>
<td>sip_cseq_num</td>
<td style="text-align: center">SIP CSeq numeric header field parameter value</td>
</tr>
<tr>
<td>sip_via_branch</td>
<td style="text-align: center">SIP Via branch header field parameter value</td>
</tr>
<tr>
<td>orig</td>
<td style="text-align: center">Originating Identity String</td>
</tr>
<tr>
<td>dest</td>
<td style="text-align: center">Destination Identity String</td>
</tr>
<tr>
<td>mky</td>
<td style="text-align: center">Media Key Fingerprint String</td>
</tr>
</tbody>
</table>
<ul>
<li>privées : Propriétés à définir pour répondre aux besoins de votre application.</li>
</ul>
<blockquote>
<p><strong>/!\le payload ne doit pas contenir de données sensibles</strong></p>
</blockquote>
<h3 id="signature">Signature</h3>
<p>Hash des deux premières parties du token réalisé en utilisant lalgorithme qui est précisé dans le header,lalgorithme utilisé ci-dessous est HS256 (HMAC-SHA-256).</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>HMACSHA256(base64UrlEncode(header) + "." + base64UrlEncode(payload), 'secret')
</code></pre></div></div>
<p>Lalgorithme utilise une clé secrète (détenue par le serveur), utilisée pour signer les tokens mais également sassurer de la validité de ceux-ci en vérifiant leur signature.</p>
<h3 id="expiration-dun-token">Expiration dun token</h3>
<p>JWT possède une date dexpiration (propriété “exp” du payload).<br />
La durée de validité dun JWT va dépendre du type de données échangées (quelques minutes pour des données sensibles à plusieurs heures pour les non sensibles).</p>
<p>Pour éviter à lutilisateur une réauthentification lorsque le JWT expire,utiliser un “refresh token”.<br />
Lorsque lutilisateur sidentifie à laide de son couple login/mot de passe, le serveur génère en plus du JWT, un token aléatoire à usage unique attaché à lutilisateur (généralement sauvegardé en base de données).</p>
<p><img src="/images/jwt2.png" alt="jwt" /></p>
<blockquote>
<p>Utilisation <strong>refresh token</strong></p>
</blockquote>
<p>Lorsque le JWT est expiré :</p>
<ul>
<li>Le client (application ou site) envoie une requête avec le JWT expiré et le “refresh token”</li>
<li>Le serveur vérifie que le JWT est expiré, que le “refresh token” est valide et que celui-ci est bien associé à lutilisateur du JWT expiré</li>
<li>Le serveur génère un nouveau JWT et “refresh token” (lié à lutilisateur) et invalide lancien “refresh token” (par exemple suppression de la base de données ou un champ indiquant que ce token nest plus valide)</li>
<li>Le serveur renvoie le nouveau JWT et “refresh token” au client;</li>
<li>Le client sauvegarde le JWT et le “refresh token”;</li>
<li>Le client peut utiliser le nouveau JWT.</li>
</ul>
<blockquote>
<p>Possibilité dajouter une date dexpiration au <strong>refresh token</strong> .</p>
</blockquote>
<h2 id="créer-un-jeton-web-json-json-web-token-en-php">Créer un jeton Web JSON (Json Web Token) en PHP</h2>
<p>La section suivante décrit étape par étape comment créer un jeton Web JSON en PHP. Pour créer un jeton Web JSON, nous utilisons les deux méthodes PHP décrites ci-dessous:</p>
<ul>
<li><code class="language-plaintext highlighter-rouge">string json_encode (mixed $value [, int $options = 0 [, int $depth = 512 ]] )</code> — Renvoie la représentation JSON dune valeur où largument $value peut être nimporte quel type sauf une ressource</li>
<li><code class="language-plaintext highlighter-rouge">string base64_encode ( string $data )</code> — code les données données en base64.</li>
</ul>
<h3 id="1-encodage-base64-header-json-object">1-Encodage base64 “header JSON Object”</h3>
<p>La première étape dans la création dun JWT est de définir la première partie du jeton <strong>token</strong>, qui est len-tête <strong>header</strong>, puis lencoder en base64, en utilisant les deux méthodes PHP<br />
Création ,droits et édition du fichier <strong>jwt-header.php</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>touch jwt-header.php &amp;&amp; chmod +x jwt-header.php &amp;&amp; nano jwt-header.php
</code></pre></div></div>
<div class="language-php highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#!/usr/bin/php
<span class="cp">&lt;?php</span>
<span class="c1">//setting the header: 'alg' =&gt; 'HS256' indicates that this token is signed using HMAC-SHA256</span>
<span class="nv">$header</span> <span class="o">=</span> <span class="p">[</span>
<span class="s1">'typ'</span> <span class="o">=&gt;</span> <span class="s1">'JWT'</span><span class="p">,</span>
<span class="s1">'alg'</span> <span class="o">=&gt;</span> <span class="s1">'HS256'</span>
<span class="p">];</span>
<span class="c1">// Returns the JSON representation of the header</span>
<span class="nv">$header</span> <span class="o">=</span> <span class="nb">json_encode</span><span class="p">(</span><span class="nv">$header</span><span class="p">);</span>
<span class="c1">//encodes the $header with base64. </span>
<span class="nv">$header</span> <span class="o">=</span> <span class="nb">base64_encode</span><span class="p">(</span><span class="nv">$header</span><span class="p">);</span>
<span class="c1">//list the resulted header</span>
<span class="nb">print_r</span><span class="p">(</span><span class="nv">$header</span><span class="p">);</span>
<span class="cp">?&gt;</span>
</code></pre></div></div>
<p>Exécution et sortie</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>./jwt-header.php
</code></pre></div></div>
<p>eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9</p>
<h3 id="2-encodage-base64-payload-json-object">2-Encodage base64 “payload JSON Object”</h3>
<p>Après avoir créé len-tête, nous devons créer le<strong>payload</strong>:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$payload = ["country" =&gt; "France", "name" =&gt; "Ansel-Arsenault", "email" =&gt; AnselArsenault@jourrapide.com ];
</code></pre></div></div>
<p>Pour coder le <strong>payload</strong>, nous utilisons à nouveau les deux méthodes <strong>json_encode</strong> et <strong>base64_encode</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$payload = json_encode($payload);
$payload = base64_encode($payload);
</code></pre></div></div>
<p>3-Concaténer <strong>header</strong> et <strong>payload</strong> avec le point “.” comme séparateur.</p>
<p>Après avoir encodé le <strong>payload</strong>, nous devons concaténer <strong>header</strong> avec <strong>payload</strong> comme ceci:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$header.$payload
</code></pre></div></div>
<p>Créer le php</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>touch jwt-header-payload.php &amp;&amp; chmod +x jwt-header-payload.php &amp;&amp; nano jwt-header-payload.php
</code></pre></div></div>
<p>Le listing suivant affiche len-tête et la charge utile (<strong>header</strong> et <strong>payload</strong>)</p>
<div class="language-php highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#!/usr/bin/php
<span class="cp">&lt;?php</span>
<span class="nv">$header</span> <span class="o">=</span> <span class="p">[</span>
<span class="s1">'typ'</span> <span class="o">=&gt;</span> <span class="s1">'JWT'</span><span class="p">,</span>
<span class="s1">'alg'</span> <span class="o">=&gt;</span> <span class="s1">'HS256'</span>
<span class="p">];</span>
<span class="nv">$header</span> <span class="o">=</span> <span class="nb">json_encode</span><span class="p">(</span><span class="nv">$header</span><span class="p">);</span>
<span class="nv">$header</span> <span class="o">=</span> <span class="nb">base64_encode</span><span class="p">(</span><span class="nv">$header</span><span class="p">);</span>
<span class="c1">//setting the payload</span>
<span class="nv">$payload</span> <span class="o">=</span> <span class="p">[</span>
<span class="s2">"country"</span> <span class="o">=&gt;</span> <span class="s2">"France"</span><span class="p">,</span>
<span class="s2">"name"</span> <span class="o">=&gt;</span> <span class="s2">"Ansel-Arsenault"</span><span class="p">,</span>
<span class="s2">"email"</span> <span class="o">=&gt;</span> <span class="s2">"AnselArsenault@jourrapide.com "</span>
<span class="p">];</span>
<span class="c1">// Returns the JSON representation of the payload</span>
<span class="nv">$payload</span> <span class="o">=</span> <span class="nb">json_encode</span><span class="p">(</span><span class="nv">$header</span><span class="p">);</span>
<span class="c1">//encodes the $payload with base64. </span>
<span class="nv">$payload</span> <span class="o">=</span> <span class="nb">base64_encode</span><span class="p">(</span><span class="nv">$header</span><span class="p">);</span>
<span class="k">echo</span> <span class="s2">"</span><span class="nv">$header</span><span class="s2">.</span><span class="nv">$payload</span><span class="s2">"</span><span class="p">;</span>
<span class="cp">?&gt;</span>
</code></pre></div></div>
<p>Exécution et sortie</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>./jwt-header-payload.php
</code></pre></div></div>
<p>eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.ZXlKMGVYQWlPaUpLVjFRaUxDSmhiR2NpT2lKSVV6STFOaUo5</p>
<h3 id="4-calculer-la-signature-de-len-tête-header-et-de-la-charge-utile-payload">4-Calculer la “signature” de len-tête “header” et de la charge utile “payload”</h3>
<p>La prochaine étape dans la création dun JWT en PHP consiste à définir la signature en la générant en utilisant la méthode HMAC.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$signature = hash_hmac('sha256','$header.$payload', $key, true);
</code></pre></div></div>
<p>Vous remarquerez que largument <strong>$key</strong> est utilisé pour générer la signature. Il représente votre mot de passe personnel et est utilisé pour valider la signature, comme vous le verrez dans cet article. Dans ce cas, la clé <strong>$key</strong> is Ansel-Signe-Arsenault.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>touch jwt-signature.php &amp;&amp; chmod +x jwt-signature.php &amp;&amp; nano jwt-signature.php
</code></pre></div></div>
<div class="language-php highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#!/usr/bin/php
<span class="cp">&lt;?php</span>
<span class="c1">//setting the personal key identification</span>
<span class="nv">$key</span> <span class="o">=</span> <span class="s1">'Ansel-Signe-Arsenault'</span><span class="p">;</span>
<span class="nv">$header</span> <span class="o">=</span> <span class="p">[</span>
<span class="s1">'typ'</span> <span class="o">=&gt;</span> <span class="s1">'JWT'</span><span class="p">,</span>
<span class="s1">'alg'</span> <span class="o">=&gt;</span> <span class="s1">'HS256'</span>
<span class="p">];</span>
<span class="nv">$header</span> <span class="o">=</span> <span class="nb">json_encode</span><span class="p">(</span><span class="nv">$header</span><span class="p">);</span>
<span class="nv">$header</span> <span class="o">=</span> <span class="nb">base64_encode</span><span class="p">(</span><span class="nv">$header</span><span class="p">);</span>
<span class="nv">$payload</span> <span class="o">=</span> <span class="p">[</span>
<span class="s2">"country"</span> <span class="o">=&gt;</span> <span class="s2">"France"</span><span class="p">,</span>
<span class="s2">"name"</span> <span class="o">=&gt;</span> <span class="s2">"Ansel-Arsenault"</span><span class="p">,</span>
<span class="s2">"email"</span> <span class="o">=&gt;</span> <span class="s2">"AnselArsenault@jourrapide.com "</span>
<span class="p">];</span>
<span class="nv">$payload</span> <span class="o">=</span> <span class="nb">json_encode</span><span class="p">(</span><span class="nv">$header</span><span class="p">);</span>
<span class="nv">$payload</span> <span class="o">=</span> <span class="nb">base64_encode</span><span class="p">(</span><span class="nv">$header</span><span class="p">);</span>
<span class="c1">// Generates a keyed hash value using the HMAC method</span>
<span class="nv">$signature</span> <span class="o">=</span> <span class="nb">hash_hmac</span><span class="p">(</span><span class="s1">'sha256'</span><span class="p">,</span><span class="s1">'$header.$payload'</span><span class="p">,</span> <span class="nv">$key</span><span class="p">,</span> <span class="kc">true</span><span class="p">);</span>
<span class="k">echo</span> <span class="nv">$signature</span><span class="p">;</span>
<span class="cp">?&gt;</span>
</code></pre></div></div>
<p>Exécution et sortie</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>./jwt-signature.php
</code></pre></div></div>
<p><code class="language-plaintext highlighter-rouge"><EFBFBD><EFBFBD><EFBFBD>[<5B>2<EFBFBD>1<EFBFBD><31> <09><><01>sÿ&gt;Z<EFBFBD>a<EFBFBD>@<40><>›)</code></p>
<h3 id="5-concaténer-signatureheader-et-payload">5-Concaténer “signature”,”header” et “payload”.</h3>
<p>Avant deffectuer la dernière étape dans la création du jeton <strong>token</strong> final, nous avons besoin de coder également la <strong>signature</strong> base64, en utilisant cette ligne de code:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$signature = base64_encode($signature);
</code></pre></div></div>
<p>La dernière étape dans la création de notre jeton <strong>token</strong> est de concaténer toutes les chaînes: len-tête <strong>header</strong>, la charge utile <strong>payload</strong> et la <strong>signature</strong> en utilisant cette ligne:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$token = "$header.$payload.$signature";
</code></pre></div></div>
<p>Le fichier php suivant rassemble toutes les étapes décrites ci-dessus et produit le jeton résultant</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>touch jwt-token.php &amp;&amp; chmod +x jwt-token.php &amp;&amp; nano jwt-token.php
</code></pre></div></div>
<div class="language-php highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#!/usr/bin/php
<span class="cp">&lt;?php</span>
<span class="c1">// base64 encodes the header json</span>
<span class="nv">$encoded_header</span> <span class="o">=</span> <span class="nb">base64_encode</span><span class="p">(</span><span class="s1">'{"alg": "HS256","typ": "JWT"}'</span><span class="p">);</span>
<span class="c1">// base64 encodes the payload json</span>
<span class="nv">$encoded_payload</span> <span class="o">=</span> <span class="nb">base64_encode</span><span class="p">(</span><span class="s1">'{"country": "France","name": "Ansel Arsenault","email": "AnselArsenault@jourrapide.com "}'</span><span class="p">);</span>
<span class="c1">// base64 strings are concatenated to one that looks like this</span>
<span class="nv">$header_payload</span> <span class="o">=</span> <span class="nv">$encoded_header</span> <span class="mf">.</span> <span class="s1">'.'</span> <span class="mf">.</span> <span class="nv">$encoded_payload</span><span class="p">;</span>
<span class="c1">//Setting the secret key</span>
<span class="nv">$secret_key</span> <span class="o">=</span> <span class="s1">']~5YL,ymj8Xe72'</span><span class="p">;</span>
<span class="c1">//Clé secrète encodée base64</span>
<span class="nv">$secret_key</span> <span class="o">=</span> <span class="nb">base64_encode</span><span class="p">(</span><span class="nv">$secret_key</span><span class="p">);</span>
<span class="c1">// Creating the signature, a hash with the s256 algorithm and the secret key. The signature is also base64 encoded.</span>
<span class="nv">$signature</span> <span class="o">=</span> <span class="nb">base64_encode</span><span class="p">(</span><span class="nb">hash_hmac</span><span class="p">(</span><span class="s1">'sha256'</span><span class="p">,</span> <span class="nv">$header_payload</span><span class="p">,</span> <span class="nv">$secret_key</span><span class="p">,</span> <span class="kc">true</span><span class="p">));</span>
<span class="c1">// Creating the JWT token by concatenating the signature with the header and payload, that looks like this:</span>
<span class="nv">$jwt_token</span> <span class="o">=</span> <span class="nv">$header_payload</span> <span class="mf">.</span> <span class="s1">'.'</span> <span class="mf">.</span> <span class="nv">$signature</span><span class="p">;</span>
<span class="c1">//listing the resulted JWT</span>
<span class="k">echo</span> <span class="nv">$jwt_token</span><span class="p">;</span>
<span class="cp">?&gt;</span>
</code></pre></div></div>
<p>Exécution et sortie</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>./jwt-token.php
</code></pre></div></div>
<p><strong>token</strong><br />
eyJhbGciOiAiSFMyNTYiLCJ0eXAiOiAiSldUIn0=.eyJjb3VudHJ5IjogIkZyYW5jZSIsIm5hbWUiOiAiQW5zZWwgQXJzZW5hdWx0IiwiZW1haWwiOiAiQW5zZWxBcnNlbmF1bHRAam91cnJhcGlkZS5jb20gIn0=.nGiEj+uzBf6eCtsFZCF0kbJUWdUDpg6SvA+zcPzNUPM=</p>
<p>Maintenant, si nous voulons vérifier que tout sest bien passé, nous pouvons tester le jeton dans <a href="https://jwt.io/">https://jwt.io/</a> en le collant dans la section Encodé. Vous verrez ensuite sur le côté droit, dans la section Décodage, toutes vos données. Mais pour que votre signature puisse le valider, vous devez entrer votre clé secrète au bas de la page, dans la section Vérifier la signature, comme vous pouvez le voir à partir de la figure suivante:</p>
<p><img src="/images/jwt3.png" alt="Texte alternatif" /></p>
<h2 id="vérification-de-la-signature">Vérification de la signature</h2>
<p>Dans cette section, après avoir créé un jeton <strong>token</strong> en PHP, nous voulons vérifier quune <strong>signature</strong> reçue est correcte. La liste suivante obtient le jeton <strong>token</strong>, en extrait la <strong>signature</strong>, crée une nouvelle <strong>signature</strong> en utilisant len-tête <strong>header</strong> et la charge utile <strong>payload</strong> extraite du jeton reçu (en utilisant également la clé secrète <strong>$secret_key</strong>), puis comparez la <strong>signature</strong>. Si tout sest bien passé, vous devriez obtenir un message de réussite:
Créer le php<br />
<code class="language-plaintext highlighter-rouge">touch jwt-verif.php &amp;&amp; chmod +x jwt-verif.php &amp;&amp; nano jwt-verif.php</code></p>
<div class="language-php highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#!/usr/bin/php
<span class="cp">&lt;?php</span>
<span class="nv">$recievedJwt</span> <span class="o">=</span> <span class="s1">'eyJhbGciOiAiSFMyNTYiLCJ0eXAiOiAiSldUIn0=.eyJjb3VudHJ5IjogIlJvbWFuaWEiLCJuYW1lIjogIk9jdGF2aWEgQW5naGVsIiwiZW1haWwiOiAib2N0YXZpYWFuZ2hlbEBnbWFpbC5jb20ifQ==.gbB+B063g+kwsoc4L3B1Bu2wM+VEBElwPiLOb0fj2SE='</span><span class="p">;</span>
<span class="c1">//Setting the secret key</span>
<span class="nv">$secret_key</span> <span class="o">=</span> <span class="s1">']~5YL,ymj8Xe72'</span><span class="p">;</span>
<span class="c1">//Clé secrète encodée base64</span>
<span class="nv">$secret_key</span> <span class="o">=</span> <span class="nb">base64_encode</span><span class="p">(</span><span class="nv">$secret_key</span><span class="p">);</span>
<span class="c1">// Split a string by '.' </span>
<span class="nv">$jwt_values</span> <span class="o">=</span> <span class="nb">explode</span><span class="p">(</span><span class="s1">'.'</span><span class="p">,</span> <span class="nv">$recievedJwt</span><span class="p">);</span>
<span class="c1">// extracting the signature from the original JWT </span>
<span class="nv">$recieved_signature</span> <span class="o">=</span> <span class="nv">$jwt_values</span><span class="p">[</span><span class="mi">2</span><span class="p">];</span>
<span class="c1">// concatenating the first two arguments of the $jwt_values array, representing the header and the payload</span>
<span class="nv">$recievedHeaderAndPayload</span> <span class="o">=</span> <span class="nv">$jwt_values</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="mf">.</span> <span class="s1">'.'</span> <span class="mf">.</span> <span class="nv">$jwt_values</span><span class="p">[</span><span class="mi">1</span><span class="p">];</span>
<span class="c1">// creating the Base 64 encoded new signature generated by applying the HMAC method to the concatenated header and payload values</span>
<span class="nv">$resultedsignature</span> <span class="o">=</span> <span class="nb">base64_encode</span><span class="p">(</span><span class="nb">hash_hmac</span><span class="p">(</span><span class="s1">'sha256'</span><span class="p">,</span> <span class="nv">$recievedHeaderAndPayload</span><span class="p">,</span> <span class="nv">$secret_key</span><span class="p">,</span> <span class="kc">true</span><span class="p">));</span>
<span class="c1">// checking if the created signature is equal to the received signature</span>
<span class="k">if</span><span class="p">(</span><span class="nv">$resultedsignature</span> <span class="o">==</span> <span class="nv">$recieved_signature</span><span class="p">)</span> <span class="p">{</span>
<span class="c1">// If everything worked fine, if the signature is ok and the payload was not modified you should get a success message</span>
<span class="k">echo</span> <span class="s2">"Success"</span><span class="p">;</span>
<span class="p">}</span>
<span class="cp">?&gt;</span>
</code></pre></div></div>
<p>Exécution et sortie<br />
<code class="language-plaintext highlighter-rouge">./jwt-verif.php</code><br />
Success</p>
<p>Au cours de cet article, vous avez appris comment créer un jeton Web JSON en PHP, comment le tester et comment vérifier un jeton reçu sil est correct. En conclusion, un jeton Web JSON est assez facile à créer et à valider vous-même. La clé secrète ne devra pas tomber dans de mauvaises mains, sinon vous ne pouvez plus faire confiance aux signatures.</p>
</div>
<div class="d-print-none"><footer class="article__footer"><meta itemprop="dateModified" content="2018-11-23T00:00:00+01:00"><!-- start custom article footer snippet -->
<!-- end custom article footer snippet -->
<!--
<div align="right"><a type="application/rss+xml" href="/feed.xml" title="S'abonner"><i class="fa fa-rss fa-2x"></i></a>
&emsp;</div>
-->
</footer>
<div class="article__section-navigator clearfix"><div class="previous"><span>PRÉCÉDENT</span><a href="/2018/11/23/Routeur-LEDE-Project.html">Routeur projet LEDE</a></div><div class="next"><span>SUIVANT</span><a href="/2018/11/23/VPN-Connexions.html">VPN Connexions</a></div></div></div>
</div>
<script>(function() {
var SOURCES = window.TEXT_VARIABLES.sources;
window.Lazyload.js(SOURCES.jquery, function() {
$(function() {
var $this ,$scroll;
var $articleContent = $('.js-article-content');
var hasSidebar = $('.js-page-root').hasClass('layout--page--sidebar');
var scroll = hasSidebar ? '.js-page-main' : 'html, body';
$scroll = $(scroll);
$articleContent.find('.highlight').each(function() {
$this = $(this);
$this.attr('data-lang', $this.find('code').attr('data-lang'));
});
$articleContent.find('h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]').each(function() {
$this = $(this);
$this.append($('<a class="anchor d-print-none" aria-hidden="true"></a>').html('<i class="fas fa-anchor"></i>'));
});
$articleContent.on('click', '.anchor', function() {
$scroll.scrollToAnchor('#' + $(this).parent().attr('id'), 400);
});
});
});
})();
</script>
</div><section class="page__comments d-print-none"></section></article><!-- start custom main bottom snippet -->
<!-- end custom main bottom snippet -->
</div>
</div></div></div></div>
</div><script>(function() {
var SOURCES = window.TEXT_VARIABLES.sources;
window.Lazyload.js(SOURCES.jquery, function() {
var $body = $('body'), $window = $(window);
var $pageRoot = $('.js-page-root'), $pageMain = $('.js-page-main');
var activeCount = 0;
function modal(options) {
var $root = this, visible, onChange, hideWhenWindowScroll = false;
var scrollTop;
function setOptions(options) {
var _options = options || {};
visible = _options.initialVisible === undefined ? false : show;
onChange = _options.onChange;
hideWhenWindowScroll = _options.hideWhenWindowScroll;
}
function init() {
setState(visible);
}
function setState(isShow) {
if (isShow === visible) {
return;
}
visible = isShow;
if (visible) {
activeCount++;
scrollTop = $(window).scrollTop() || $pageMain.scrollTop();
$root.addClass('modal--show');
$pageMain.scrollTop(scrollTop);
activeCount === 1 && ($pageRoot.addClass('show-modal'), $body.addClass('of-hidden'));
hideWhenWindowScroll && window.hasEvent('touchstart') && $window.on('scroll', hide);
$window.on('keyup', handleKeyup);
} else {
activeCount > 0 && activeCount--;
$root.removeClass('modal--show');
$window.scrollTop(scrollTop);
activeCount === 0 && ($pageRoot.removeClass('show-modal'), $body.removeClass('of-hidden'));
hideWhenWindowScroll && window.hasEvent('touchstart') && $window.off('scroll', hide);
$window.off('keyup', handleKeyup);
}
onChange && onChange(visible);
}
function show() {
setState(true);
}
function hide() {
setState(false);
}
function handleKeyup(e) {
// Char Code: 27 ESC
if (e.which === 27) {
hide();
}
}
setOptions(options);
init();
return {
show: show,
hide: hide,
$el: $root
};
}
$.fn.modal = modal;
});
})();
</script><div class="modal modal--overflow page__search-modal d-print-none js-page-search-modal"><script>
(function () {
var SOURCES = window.TEXT_VARIABLES.sources;
window.Lazyload.js(SOURCES.jquery, function() {
// search panel
var search = (window.search || (window.search = {}));
var useDefaultSearchBox = window.useDefaultSearchBox === undefined ?
true : window.useDefaultSearchBox ;
var $searchModal = $('.js-page-search-modal');
var $searchToggle = $('.js-search-toggle');
var searchModal = $searchModal.modal({ onChange: handleModalChange, hideWhenWindowScroll: true });
var modalVisible = false;
search.searchModal = searchModal;
var $searchBox = null;
var $searchInput = null;
var $searchClear = null;
function getModalVisible() {
return modalVisible;
}
search.getModalVisible = getModalVisible;
function handleModalChange(visible) {
modalVisible = visible;
if (visible) {
search.onShow && search.onShow();
useDefaultSearchBox && $searchInput[0] && $searchInput[0].focus();
} else {
search.onShow && search.onHide();
useDefaultSearchBox && $searchInput[0] && $searchInput[0].blur();
setTimeout(function() {
useDefaultSearchBox && ($searchInput.val(''), $searchBox.removeClass('not-empty'));
search.clear && search.clear();
window.pageAsideAffix && window.pageAsideAffix.refresh();
}, 400);
}
}
$searchToggle.on('click', function() {
modalVisible ? searchModal.hide() : searchModal.show();
});
// Char Code: 83 S, 191 /
$(window).on('keyup', function(e) {
if (!modalVisible && !window.isFormElement(e.target || e.srcElement) && (e.which === 83 || e.which === 191)) {
modalVisible || searchModal.show();
}
});
if (useDefaultSearchBox) {
$searchBox = $('.js-search-box');
$searchInput = $searchBox.children('input');
$searchClear = $searchBox.children('.js-icon-clear');
search.getSearchInput = function() {
return $searchInput.get(0);
};
search.getVal = function() {
return $searchInput.val();
};
search.setVal = function(val) {
$searchInput.val(val);
};
$searchInput.on('focus', function() {
$(this).addClass('focus');
});
$searchInput.on('blur', function() {
$(this).removeClass('focus');
});
$searchInput.on('input', window.throttle(function() {
var val = $(this).val();
if (val === '' || typeof val !== 'string') {
search.clear && search.clear();
} else {
$searchBox.addClass('not-empty');
search.onInputNotEmpty && search.onInputNotEmpty(val);
}
}, 400));
$searchClear.on('click', function() {
$searchInput.val(''); $searchBox.removeClass('not-empty');
search.clear && search.clear();
});
}
});
})();
</script><div class="search search--dark">
<div class="main">
<div class="search__header">Recherche</div>
<div class="search-bar">
<div class="search-box js-search-box">
<div class="search-box__icon-search"><i class="fas fa-search"></i></div>
<input id="search-input" type="text" />
<div class="search-box__icon-clear js-icon-clear">
<a><i class="fas fa-times"></i></a>
</div>
</div>
<button class="button button--theme-dark button--pill search__cancel js-search-toggle">
Annuler</button>
</div>
<div id="results-container" class="search-result js-search-result"></div>
</div>
</div>
<!-- Script pointing to search-script.js -->
<script>/*!
* Simple-Jekyll-Search
* Copyright 2015-2020, Christian Fei
* Licensed under the MIT License.
*/
(function(){
'use strict'
var _$Templater_7 = {
compile: compile,
setOptions: setOptions
}
const options = {}
options.pattern = /\{(.*?)\}/g
options.template = ''
options.middleware = function () {}
function setOptions (_options) {
options.pattern = _options.pattern || options.pattern
options.template = _options.template || options.template
if (typeof _options.middleware === 'function') {
options.middleware = _options.middleware
}
}
function compile (data) {
return options.template.replace(options.pattern, function (match, prop) {
const value = options.middleware(prop, data[prop], options.template)
if (typeof value !== 'undefined') {
return value
}
return data[prop] || match
})
}
'use strict';
function fuzzysearch (needle, haystack) {
var tlen = haystack.length;
var qlen = needle.length;
if (qlen > tlen) {
return false;
}
if (qlen === tlen) {
return needle === haystack;
}
outer: for (var i = 0, j = 0; i < qlen; i++) {
var nch = needle.charCodeAt(i);
while (j < tlen) {
if (haystack.charCodeAt(j++) === nch) {
continue outer;
}
}
return false;
}
return true;
}
var _$fuzzysearch_1 = fuzzysearch;
'use strict'
/* removed: const _$fuzzysearch_1 = require('fuzzysearch') */;
var _$FuzzySearchStrategy_5 = new FuzzySearchStrategy()
function FuzzySearchStrategy () {
this.matches = function (string, crit) {
return _$fuzzysearch_1(crit.toLowerCase(), string.toLowerCase())
}
}
'use strict'
var _$LiteralSearchStrategy_6 = new LiteralSearchStrategy()
function LiteralSearchStrategy () {
this.matches = function (str, crit) {
if (!str) return false
str = str.trim().toLowerCase()
crit = crit.trim().toLowerCase()
return crit.split(' ').filter(function (word) {
return str.indexOf(word) >= 0
}).length === crit.split(' ').length
}
}
'use strict'
var _$Repository_4 = {
put: put,
clear: clear,
search: search,
setOptions: __setOptions_4
}
/* removed: const _$FuzzySearchStrategy_5 = require('./SearchStrategies/FuzzySearchStrategy') */;
/* removed: const _$LiteralSearchStrategy_6 = require('./SearchStrategies/LiteralSearchStrategy') */;
function NoSort () {
return 0
}
const data = []
let opt = {}
opt.fuzzy = false
opt.limit = 10
opt.searchStrategy = opt.fuzzy ? _$FuzzySearchStrategy_5 : _$LiteralSearchStrategy_6
opt.sort = NoSort
opt.exclude = []
function put (data) {
if (isObject(data)) {
return addObject(data)
}
if (isArray(data)) {
return addArray(data)
}
return undefined
}
function clear () {
data.length = 0
return data
}
function isObject (obj) {
return Boolean(obj) && Object.prototype.toString.call(obj) === '[object Object]'
}
function isArray (obj) {
return Boolean(obj) && Object.prototype.toString.call(obj) === '[object Array]'
}
function addObject (_data) {
data.push(_data)
return data
}
function addArray (_data) {
const added = []
clear()
for (let i = 0, len = _data.length; i < len; i++) {
if (isObject(_data[i])) {
added.push(addObject(_data[i]))
}
}
return added
}
function search (crit) {
if (!crit) {
return []
}
return findMatches(data, crit, opt.searchStrategy, opt).sort(opt.sort)
}
function __setOptions_4 (_opt) {
opt = _opt || {}
opt.fuzzy = _opt.fuzzy || false
opt.limit = _opt.limit || 10
opt.searchStrategy = _opt.fuzzy ? _$FuzzySearchStrategy_5 : _$LiteralSearchStrategy_6
opt.sort = _opt.sort || NoSort
opt.exclude = _opt.exclude || []
}
function findMatches (data, crit, strategy, opt) {
const matches = []
for (let i = 0; i < data.length && matches.length < opt.limit; i++) {
const match = findMatchesInObject(data[i], crit, strategy, opt)
if (match) {
matches.push(match)
}
}
return matches
}
function findMatchesInObject (obj, crit, strategy, opt) {
for (const key in obj) {
if (!isExcluded(obj[key], opt.exclude) && strategy.matches(obj[key], crit)) {
return obj
}
}
}
function isExcluded (term, excludedTerms) {
for (let i = 0, len = excludedTerms.length; i < len; i++) {
const excludedTerm = excludedTerms[i]
if (new RegExp(excludedTerm).test(term)) {
return true
}
}
return false
}
/* globals ActiveXObject:false */
'use strict'
var _$JSONLoader_2 = {
load: load
}
function load (location, callback) {
const xhr = getXHR()
xhr.open('GET', location, true)
xhr.onreadystatechange = createStateChangeListener(xhr, callback)
xhr.send()
}
function createStateChangeListener (xhr, callback) {
return function () {
if (xhr.readyState === 4 && xhr.status === 200) {
try {
callback(null, JSON.parse(xhr.responseText))
} catch (err) {
callback(err, null)
}
}
}
}
function getXHR () {
return window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP')
}
'use strict'
var _$OptionsValidator_3 = function OptionsValidator (params) {
if (!validateParams(params)) {
throw new Error('-- OptionsValidator: required options missing')
}
if (!(this instanceof OptionsValidator)) {
return new OptionsValidator(params)
}
const requiredOptions = params.required
this.getRequiredOptions = function () {
return requiredOptions
}
this.validate = function (parameters) {
const errors = []
requiredOptions.forEach(function (requiredOptionName) {
if (typeof parameters[requiredOptionName] === 'undefined') {
errors.push(requiredOptionName)
}
})
return errors
}
function validateParams (params) {
if (!params) {
return false
}
return typeof params.required !== 'undefined' && params.required instanceof Array
}
}
'use strict'
var _$utils_9 = {
merge: merge,
isJSON: isJSON
}
function merge (defaultParams, mergeParams) {
const mergedOptions = {}
for (const option in defaultParams) {
mergedOptions[option] = defaultParams[option]
if (typeof mergeParams[option] !== 'undefined') {
mergedOptions[option] = mergeParams[option]
}
}
return mergedOptions
}
function isJSON (json) {
try {
if (json instanceof Object && JSON.parse(JSON.stringify(json))) {
return true
}
return false
} catch (err) {
return false
}
}
var _$src_8 = {};
(function (window) {
'use strict'
let options = {
searchInput: null,
resultsContainer: null,
json: [],
success: Function.prototype,
searchResultTemplate: '<li><a href="{url}" title="{desc}">{title}</a></li>',
templateMiddleware: Function.prototype,
sortMiddleware: function () {
return 0
},
noResultsText: 'No results found',
limit: 10,
fuzzy: false,
debounceTime: null,
exclude: []
}
let debounceTimerHandle
const debounce = function (func, delayMillis) {
if (delayMillis) {
clearTimeout(debounceTimerHandle)
debounceTimerHandle = setTimeout(func, delayMillis)
} else {
func.call()
}
}
const requiredOptions = ['searchInput', 'resultsContainer', 'json']
/* removed: const _$Templater_7 = require('./Templater') */;
/* removed: const _$Repository_4 = require('./Repository') */;
/* removed: const _$JSONLoader_2 = require('./JSONLoader') */;
const optionsValidator = _$OptionsValidator_3({
required: requiredOptions
})
/* removed: const _$utils_9 = require('./utils') */;
window.SimpleJekyllSearch = function (_options) {
const errors = optionsValidator.validate(_options)
if (errors.length > 0) {
throwError('You must specify the following required options: ' + requiredOptions)
}
options = _$utils_9.merge(options, _options)
_$Templater_7.setOptions({
template: options.searchResultTemplate,
middleware: options.templateMiddleware
})
_$Repository_4.setOptions({
fuzzy: options.fuzzy,
limit: options.limit,
sort: options.sortMiddleware,
exclude: options.exclude
})
if (_$utils_9.isJSON(options.json)) {
initWithJSON(options.json)
} else {
initWithURL(options.json)
}
const rv = {
search: search
}
typeof options.success === 'function' && options.success.call(rv)
return rv
}
function initWithJSON (json) {
_$Repository_4.put(json)
registerInput()
}
function initWithURL (url) {
_$JSONLoader_2.load(url, function (err, json) {
if (err) {
throwError('failed to get JSON (' + url + ')')
}
initWithJSON(json)
})
}
function emptyResultsContainer () {
options.resultsContainer.innerHTML = ''
}
function appendToResultsContainer (text) {
options.resultsContainer.innerHTML += text
}
function registerInput () {
options.searchInput.addEventListener('input', function (e) {
if (isWhitelistedKey(e.which)) {
emptyResultsContainer()
debounce(function () { search(e.target.value) }, options.debounceTime)
}
})
}
function search (query) {
if (isValidQuery(query)) {
emptyResultsContainer()
render(_$Repository_4.search(query), query)
}
}
function render (results, query) {
const len = results.length
if (len === 0) {
return appendToResultsContainer(options.noResultsText)
}
for (let i = 0; i < len; i++) {
results[i].query = query
appendToResultsContainer(_$Templater_7.compile(results[i]))
}
}
function isValidQuery (query) {
return query && query.length > 0
}
function isWhitelistedKey (key) {
return [13, 16, 20, 37, 38, 39, 40, 91].indexOf(key) === -1
}
function throwError (message) {
throw new Error('SimpleJekyllSearch --- ' + message)
}
})(window)
}());
</script>
<!-- Configuration -->
<script>
SimpleJekyllSearch({
searchInput: document.getElementById('search-input'),
resultsContainer: document.getElementById('results-container'),
noResultsText: '<p>Aucun résultat!</p>',
json: '/search.json',
searchResultTemplate: '<li><a href="{url}">{date}&nbsp;{title}</a>&nbsp;(Création {create})</li>'
})
</script>
</div></div>
<script>(function() {
var SOURCES = window.TEXT_VARIABLES.sources;
window.Lazyload.js(SOURCES.jquery, function() {
function scrollToAnchor(anchor, duration, callback) {
var $root = this;
$root.animate({ scrollTop: $(anchor).position().top }, duration, function() {
window.history.replaceState(null, '', window.location.href.split('#')[0] + anchor);
callback && callback();
});
}
$.fn.scrollToAnchor = scrollToAnchor;
});
})();
(function() {
var SOURCES = window.TEXT_VARIABLES.sources;
window.Lazyload.js(SOURCES.jquery, function() {
function affix(options) {
var $root = this, $window = $(window), $scrollTarget, $scroll,
offsetBottom = 0, scrollTarget = window, scroll = window.document, disabled = false, isOverallScroller = true,
rootTop, rootLeft, rootHeight, scrollBottom, rootBottomTop,
hasInit = false, curState;
function setOptions(options) {
var _options = options || {};
_options.offsetBottom && (offsetBottom = _options.offsetBottom);
_options.scrollTarget && (scrollTarget = _options.scrollTarget);
_options.scroll && (scroll = _options.scroll);
_options.disabled !== undefined && (disabled = _options.disabled);
$scrollTarget = $(scrollTarget);
isOverallScroller = window.isOverallScroller($scrollTarget[0]);
$scroll = $(scroll);
}
function preCalc() {
top();
rootHeight = $root.outerHeight();
rootTop = $root.offset().top + (isOverallScroller ? 0 : $scrollTarget.scrollTop());
rootLeft = $root.offset().left;
}
function calc(needPreCalc) {
needPreCalc && preCalc();
scrollBottom = $scroll.outerHeight() - offsetBottom - rootHeight;
rootBottomTop = scrollBottom - rootTop;
}
function top() {
if (curState !== 'top') {
$root.removeClass('fixed').css({
left: 0,
top: 0
});
curState = 'top';
}
}
function fixed() {
if (curState !== 'fixed') {
$root.addClass('fixed').css({
left: rootLeft + 'px',
top: 0
});
curState = 'fixed';
}
}
function bottom() {
if (curState !== 'bottom') {
$root.removeClass('fixed').css({
left: 0,
top: rootBottomTop + 'px'
});
curState = 'bottom';
}
}
function setState() {
var scrollTop = $scrollTarget.scrollTop();
if (scrollTop >= rootTop && scrollTop <= scrollBottom) {
fixed();
} else if (scrollTop < rootTop) {
top();
} else {
bottom();
}
}
function init() {
if(!hasInit) {
var interval, timeout;
calc(true); setState();
// run calc every 100 millisecond
interval = setInterval(function() {
calc();
}, 100);
timeout = setTimeout(function() {
clearInterval(interval);
}, 45000);
window.pageLoad.then(function() {
setTimeout(function() {
clearInterval(interval);
clearTimeout(timeout);
}, 3000);
});
$scrollTarget.on('scroll', function() {
disabled || setState();
});
$window.on('resize', function() {
disabled || (calc(true), setState());
});
hasInit = true;
}
}
setOptions(options);
if (!disabled) {
init();
}
$window.on('resize', window.throttle(function() {
init();
}, 200));
return {
setOptions: setOptions,
refresh: function() {
calc(true, { animation: false }); setState();
}
};
}
$.fn.affix = affix;
});
})();
(function() {
var SOURCES = window.TEXT_VARIABLES.sources;
window.Lazyload.js(SOURCES.jquery, function() {
function toc(options) {
var $root = this, $window = $(window), $scrollTarget, $scroller, $tocUl = $('<ul class="toc toc--ellipsis"></ul>'), $tocLi, $headings, $activeLast, $activeCur,
selectors = 'h1,h2,h3', container = 'body', scrollTarget = window, scroller = 'html, body', disabled = false,
headingsPos, scrolling = false, hasRendered = false, hasInit = false;
function setOptions(options) {
var _options = options || {};
_options.selectors && (selectors = _options.selectors);
_options.container && (container = _options.container);
_options.scrollTarget && (scrollTarget = _options.scrollTarget);
_options.scroller && (scroller = _options.scroller);
_options.disabled !== undefined && (disabled = _options.disabled);
$headings = $(container).find(selectors).filter('[id]');
$scrollTarget = $(scrollTarget);
$scroller = $(scroller);
}
function calc() {
headingsPos = [];
$headings.each(function() {
headingsPos.push(Math.floor($(this).position().top));
});
}
function setState(element, disabled) {
var scrollTop = $scrollTarget.scrollTop(), i;
if (disabled || !headingsPos || headingsPos.length < 1) { return; }
if (element) {
$activeCur = element;
} else {
for (i = 0; i < headingsPos.length; i++) {
if (scrollTop >= headingsPos[i]) {
$activeCur = $tocLi.eq(i);
} else {
$activeCur || ($activeCur = $tocLi.eq(i));
break;
}
}
}
$activeLast && $activeLast.removeClass('active');
($activeLast = $activeCur).addClass('active');
}
function render() {
if(!hasRendered) {
$root.append($tocUl);
$headings.each(function() {
var $this = $(this);
$tocUl.append($('<li></li>').addClass('toc-' + $this.prop('tagName').toLowerCase())
.append($('<a></a>').text($this.text()).attr('href', '#' + $this.prop('id'))));
});
$tocLi = $tocUl.children('li');
$tocUl.on('click', 'a', function(e) {
e.preventDefault();
var $this = $(this);
scrolling = true;
setState($this.parent());
$scroller.scrollToAnchor($this.attr('href'), 400, function() {
scrolling = false;
});
});
}
hasRendered = true;
}
function init() {
var interval, timeout;
if(!hasInit) {
render(); calc(); setState(null, scrolling);
// run calc every 100 millisecond
interval = setInterval(function() {
calc();
}, 100);
timeout = setTimeout(function() {
clearInterval(interval);
}, 45000);
window.pageLoad.then(function() {
setTimeout(function() {
clearInterval(interval);
clearTimeout(timeout);
}, 3000);
});
$scrollTarget.on('scroll', function() {
disabled || setState(null, scrolling);
});
$window.on('resize', window.throttle(function() {
if (!disabled) {
render(); calc(); setState(null, scrolling);
}
}, 100));
}
hasInit = true;
}
setOptions(options);
if (!disabled) {
init();
}
$window.on('resize', window.throttle(function() {
init();
}, 200));
return {
setOptions: setOptions
};
}
$.fn.toc = toc;
});
})();
/*(function () {
})();*/
</script><script>
/* toc must before affix, since affix need to konw toc' height. */(function() {
var SOURCES = window.TEXT_VARIABLES.sources;
var TOC_SELECTOR = window.TEXT_VARIABLES.site.toc.selectors;
window.Lazyload.js(SOURCES.jquery, function() {
var $window = $(window);
var $articleContent = $('.js-article-content');
var $tocRoot = $('.js-toc-root'), $col2 = $('.js-col-aside');
var toc;
var tocDisabled = false;
var hasSidebar = $('.js-page-root').hasClass('layout--page--sidebar');
var hasToc = $articleContent.find(TOC_SELECTOR).length > 0;
function disabled() {
return $col2.css('display') === 'none' || !hasToc;
}
tocDisabled = disabled();
toc = $tocRoot.toc({
selectors: TOC_SELECTOR,
container: $articleContent,
scrollTarget: hasSidebar ? '.js-page-main' : null,
scroller: hasSidebar ? '.js-page-main' : null,
disabled: tocDisabled
});
$window.on('resize', window.throttle(function() {
tocDisabled = disabled();
toc && toc.setOptions({
disabled: tocDisabled
});
}, 100));
});
})();
(function() {
var SOURCES = window.TEXT_VARIABLES.sources;
window.Lazyload.js(SOURCES.jquery, function() {
var $window = $(window), $pageFooter = $('.js-page-footer');
var $pageAside = $('.js-page-aside');
var affix;
var tocDisabled = false;
var hasSidebar = $('.js-page-root').hasClass('layout--page--sidebar');
affix = $pageAside.affix({
offsetBottom: $pageFooter.outerHeight(),
scrollTarget: hasSidebar ? '.js-page-main' : null,
scroller: hasSidebar ? '.js-page-main' : null,
scroll: hasSidebar ? $('.js-page-main').children() : null,
disabled: tocDisabled
});
$window.on('resize', window.throttle(function() {
affix && affix.setOptions({
disabled: tocDisabled
});
}, 100));
window.pageAsideAffix = affix;
});
})();
</script><!---->
</div>
<script>(function () {
var $root = document.getElementsByClassName('root')[0];
if (window.hasEvent('touchstart')) {
$root.dataset.isTouch = true;
document.addEventListener('touchstart', function(){}, false);
}
})();
</script>
</body>
</html>