{"id":485884,"date":"2022-08-19T03:48:29","date_gmt":"2022-08-19T00:48:29","guid":{"rendered":"https:\/\/en.buradabiliyorum.com\/what-are-json-web-tokens-jwts-why-do-apis-use-them\/"},"modified":"2022-08-19T03:48:29","modified_gmt":"2022-08-19T00:48:29","slug":"what-are-json-web-tokens-jwts-why-do-apis-use-them","status":"publish","type":"post","link":"https:\/\/buradabiliyorum.com\/en\/what-are-json-web-tokens-jwts-why-do-apis-use-them\/","title":{"rendered":"#What Are JSON Web Tokens (JWTs)? Why Do APIs Use Them?"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_89 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<label for=\"ez-toc-cssicon-toggle-item-6af6ad2186a0e\" class=\"ez-toc-cssicon-toggle-label\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #dd3333;color:#dd3333\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #dd3333;color:#dd3333\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/label><input type=\"checkbox\"  id=\"ez-toc-cssicon-toggle-item-6af6ad2186a0e\" checked aria-label=\"Toggle\" \/><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-1'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/buradabiliyorum.com\/en\/what-are-json-web-tokens-jwts-why-do-apis-use-them\/#%E2%80%9CWhat_Are_JSON_Web_Tokens_JWTs_Why_Do_APIs_Use_Them%E2%80%9D\" >&#8220;What Are JSON Web Tokens (JWTs)? Why Do APIs Use Them?&#8221;<\/a><ul class='ez-toc-list-level-2' ><li class='ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/buradabiliyorum.com\/en\/what-are-json-web-tokens-jwts-why-do-apis-use-them\/#How_JWTs_Work\" >How JWTs Work<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/buradabiliyorum.com\/en\/what-are-json-web-tokens-jwts-why-do-apis-use-them\/#The_JWT_Format\" >The JWT Format<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/buradabiliyorum.com\/en\/what-are-json-web-tokens-jwts-why-do-apis-use-them\/#Creating_a_JWT\" >Creating a JWT<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/buradabiliyorum.com\/en\/what-are-json-web-tokens-jwts-why-do-apis-use-them\/#Verifying_Incoming_JWTs\" >Verifying Incoming JWTs<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/buradabiliyorum.com\/en\/what-are-json-web-tokens-jwts-why-do-apis-use-them\/#When_to_Use_JWTs\" >When to Use JWTs<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/buradabiliyorum.com\/en\/what-are-json-web-tokens-jwts-why-do-apis-use-them\/#Summary\" >Summary<\/a><\/li><\/ul><\/li><\/ul><\/nav><\/div>\n<h1><span class=\"ez-toc-section\" id=\"%E2%80%9CWhat_Are_JSON_Web_Tokens_JWTs_Why_Do_APIs_Use_Them%E2%80%9D\"><\/span>&#8220;What Are JSON Web Tokens (JWTs)? Why Do APIs Use Them?&#8221;<span class=\"ez-toc-section-end\"><\/span><\/h1>\n<div>\n<figure style=\"width: 1202px\" class=\"wp-caption alignnone\"><img loading=\"lazy\" decoding=\"async\" class=\"type:primaryImage size-full wp-image-827120\" data-pagespeed-no-defer=\"\" src=\"https:\/\/www.howtogeek.com\/wp-content\/uploads\/2022\/08\/shutterstock_1931787956.jpg?width=1198&amp;trim=1,1&amp;bg-color=000&amp;pad=1,1\" alt=\"\" width=\"1202\" height=\"677\"\/><figcaption class=\"wp-caption-text\"><span class=\"type:primaryImage imagecredit\"><a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/www.shutterstock.com\/image-photo\/internet-network-security-concept-young-man-1931787956\">Shutterstock.com\/TierneyMJ<\/a><\/span><\/figcaption><\/figure>\n<p>The <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/www.rfc-editor.org\/rfc\/rfc7519\">JSON Web Tokens (JWT) standard<\/a> describes a compact method for verifiable data transfers. Each token contains a signature that allows the issuing party to check the message\u2019s integrity.<\/p>\n<p>In this article, you\u2019ll learn what the JWT structure includes and how you can generate your own tokens. JWTs are a popular way to secure APIs and authenticate user sessions because they\u2019re simple and self-contained.<\/p>\n<h2 id=\"how-jwts-work\"><span class=\"ez-toc-section\" id=\"How_JWTs_Work\"><\/span>How JWTs Work<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>One of the most common tasks in any API is validating that users are who they claim to be. Authentication\u2019s usually handled by having the client include an API key with requests it sends to the server. The key contains embedded information that identifies the user. This still leaves one big question: how can the server validate that it issued the key in the first place?<\/p>\n<p>JWTs conveniently solve this problem by using a secret to sign each token. The server can check a token\u2019s valid by trying to recompute the presented signature using its private secret. Any tampering will cause the verification to fail.<\/p>\n<h2 id=\"the-jwt-format\"><span class=\"ez-toc-section\" id=\"The_JWT_Format\"><\/span>The JWT Format<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>JWTs are formed from three distinct components:<\/p>\n<ul>\n<li><strong>Header<\/strong> \u2013 This includes metadata about the token itself, such as the signing algorithm that was used.<\/li>\n<li><strong>Payload<\/strong> \u2013 The token\u2019s payload can be any arbitrary data relevant to your system. It could include the user\u2019s ID and a list of features they can interact with.<\/li>\n<li><strong>Signature<\/strong> \u2013 The signature allows the token\u2019s integrity to be validated in the future. It\u2019s created by signing the header and payload using a secret value that\u2019s known only to the server.<\/li>\n<\/ul>\n<p>These three components are joined with periods to produce the JWT:<\/p>\n<pre>header.payload.signature<\/pre>\n<p>Each piece is encoded using Base-64. The complete token is a string of text that can be easily consumed in programming environments and sent with HTTP requests.<\/p>\n<h2 id=\"creating-a-jwt\"><span class=\"ez-toc-section\" id=\"Creating_a_JWT\"><\/span>Creating a JWT<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The steps to create a JWT can be implemented in all programming languages. This example uses PHP but the process will be similar in your own system.<\/p>\n<p>Start out by creating the header. This usually includes two fields, <code>alg<\/code> and <code>typ<\/code>:<\/p>\n<ul>\n<li><strong><code>alg<\/code><\/strong> \u2013 The hashing algorithm that will be used to create the signature. This is normally HMAC SHA256 (<code>HS256<\/code>).<\/li>\n<li><strong><code>typ<\/code><\/strong> \u2013 The type of token that\u2019s being generated. This should be <code>JWT<\/code>.<\/li>\n<\/ul>\n<p>Here\u2019s the JSON that defines the header:<\/p>\n<div class=\"wp-geshi-highlight-wrap5\">\n<div class=\"wp-geshi-highlight-wrap4\">\n<div class=\"wp-geshi-highlight-wrap3\">\n<div class=\"wp-geshi-highlight-wrap2\">\n<div class=\"wp-geshi-highlight-wrap\">\n<div class=\"wp-geshi-highlight\">\n<div class=\"json\">\n<pre class=\"de1\">{&#13;\n    \"alg\": \"HS256\",&#13;\n    \"typ\": \"JWT\"&#13;\n}<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>The header JSON needs to be Base64-encoded next:<\/p>\n<div class=\"wp-geshi-highlight-wrap5\">\n<div class=\"wp-geshi-highlight-wrap4\">\n<div class=\"wp-geshi-highlight-wrap3\">\n<div class=\"wp-geshi-highlight-wrap2\">\n<div class=\"wp-geshi-highlight-wrap\">\n<div class=\"wp-geshi-highlight\">\n<div class=\"php\">\n<pre class=\"de1\"><span class=\"re0\">$headerData<\/span> <span class=\"sy0\">=<\/span> <span class=\"br0\">[<\/span><span class=\"st0\">\"alg\"<\/span> <span class=\"sy0\">=&gt;<\/span> <span class=\"st0\">\"HS256\"<\/span><span class=\"sy0\">,<\/span> <span class=\"st0\">\"typ\"<\/span> <span class=\"sy0\">=&gt;<\/span> <span class=\"st0\">\"JWT\"<\/span><span class=\"br0\">]<\/span><span class=\"sy0\">;<\/span>\n<span class=\"re0\">$header<\/span> <span class=\"sy0\">=<\/span> <span class=\"kw3\">base64_encode<\/span><span class=\"br0\">(<\/span><span class=\"kw3\">json_encode<\/span><span class=\"br0\">(<\/span><span class=\"re0\">$headerData<\/span><span class=\"br0\">)<\/span><span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>Next define your token\u2019s payload as another JSON object. This is <a href=\"https:\/\/buradabiliyorum.com\/en\/category\/download-scripts-themes-apps\/\" data-internallinksmanager029f6b8e52c=\"9\" title=\"Download Scripts &amp; Themes &amp; Apps\" target=\"_blank\" rel=\"noopener\">app<\/a>lication-specific. The example offers details of the authenticated user account, as well as information about the token itself. <code>exp<\/code>, <code>iat<\/code>, and <code>nbf<\/code> are fields used by convention to express the token\u2019s expiry time, issued at time, and not valid before (start) time. The payload needs to be Base64-encoded too.<\/p>\n<div class=\"wp-geshi-highlight-wrap5\">\n<div class=\"wp-geshi-highlight-wrap4\">\n<div class=\"wp-geshi-highlight-wrap3\">\n<div class=\"wp-geshi-highlight-wrap2\">\n<div class=\"wp-geshi-highlight-wrap\">\n<div class=\"wp-geshi-highlight\">\n<div class=\"php\">\n<pre class=\"de1\"><span class=\"re0\">$payloadData<\/span> <span class=\"sy0\">=<\/span> <span class=\"br0\">[<\/span>\n    <span class=\"st0\">\"userId\"<\/span> <span class=\"sy0\">=&gt;<\/span> <span class=\"nu0\">1001<\/span><span class=\"sy0\">,<\/span>\n    <span class=\"st0\">\"userName\"<\/span> <span class=\"sy0\">=&gt;<\/span> <span class=\"st0\">\"demo\"<\/span><span class=\"sy0\">,<\/span>\n    <span class=\"st0\">\"licensedFeatures\"<\/span> <span class=\"sy0\">=&gt;<\/span> <span class=\"br0\">[<\/span><span class=\"st0\">\"todos\"<\/span><span class=\"sy0\">,<\/span> <span class=\"st0\">\"calendar\"<\/span><span class=\"sy0\">,<\/span> <span class=\"st0\">\"invoicing\"<\/span><span class=\"br0\">]<\/span><span class=\"sy0\">,<\/span>\n    <span class=\"st0\">\"exp\"<\/span> <span class=\"sy0\">=&gt;<\/span> <span class=\"br0\">(<\/span><span class=\"kw3\">time<\/span><span class=\"br0\">(<\/span><span class=\"br0\">)<\/span> <span class=\"sy0\">+<\/span> <span class=\"nu0\">900<\/span><span class=\"br0\">)<\/span><span class=\"sy0\">,<\/span>\n    <span class=\"st0\">\"iat\"<\/span> <span class=\"sy0\">=&gt;<\/span> <span class=\"kw3\">time<\/span><span class=\"br0\">(<\/span><span class=\"br0\">)<\/span><span class=\"sy0\">,<\/span>\n    <span class=\"st0\">\"nbf\"<\/span> <span class=\"sy0\">=&gt;<\/span> <span class=\"kw3\">time<\/span><span class=\"br0\">(<\/span><span class=\"br0\">)<\/span>\n<span class=\"br0\">]<\/span><span class=\"sy0\">;<\/span>\n<span class=\"re0\">$payload<\/span> <span class=\"sy0\">=<\/span> <span class=\"kw3\">base64_encode<\/span><span class=\"br0\">(<\/span><span class=\"kw3\">json_encode<\/span><span class=\"br0\">(<\/span><span class=\"re0\">$payloadData<\/span><span class=\"br0\">)<\/span><span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>All that remains is to create the signature. To produce this you first combine the header and payload into a single string separated by a <code>.<\/code> character:<\/p>\n<div class=\"wp-geshi-highlight-wrap5\">\n<div class=\"wp-geshi-highlight-wrap4\">\n<div class=\"wp-geshi-highlight-wrap3\">\n<div class=\"wp-geshi-highlight-wrap2\">\n<div class=\"wp-geshi-highlight-wrap\">\n<div class=\"wp-geshi-highlight\">\n<div class=\"php\">\n<pre class=\"de1\"><span class=\"re0\">$headerAndPayload<\/span> <span class=\"sy0\">=<\/span> <span class=\"st0\">\"<span class=\"es4\">$header<\/span>.<span class=\"es4\">$payload<\/span>\"<\/span><span class=\"sy0\">;<\/span><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>Next you must generate a unique secret to use as your signing key. The secret needs to be stored securely on your server and must never be sent to clients. Exposure of this value would allow anyone to create valid tokens.<\/p>\n<div class=\"wp-geshi-highlight-wrap5\">\n<div class=\"wp-geshi-highlight-wrap4\">\n<div class=\"wp-geshi-highlight-wrap3\">\n<div class=\"wp-geshi-highlight-wrap2\">\n<div class=\"wp-geshi-highlight-wrap\">\n<div class=\"wp-geshi-highlight\">\n<div class=\"php\">\n<pre class=\"de1\"><span class=\"co1\">\/\/ PHP method to generate 32 random characters<\/span>\n<span class=\"re0\">$secret<\/span> <span class=\"sy0\">=<\/span> <span class=\"kw3\">bin2hex<\/span><span class=\"br0\">(<\/span>openssl_random_pseudo_bytes<span class=\"br0\">(<\/span><span class=\"nu0\">16<\/span><span class=\"br0\">)<\/span><span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>You complete the process by using the secret to sign the combined header and payload string using the hashing algorithm you indicated in the header. The output signature must be Base64-encoded like the other components.<\/p>\n<div class=\"wp-geshi-highlight-wrap5\">\n<div class=\"wp-geshi-highlight-wrap4\">\n<div class=\"wp-geshi-highlight-wrap3\">\n<div class=\"wp-geshi-highlight-wrap2\">\n<div class=\"wp-geshi-highlight-wrap\">\n<div class=\"wp-geshi-highlight\">\n<div class=\"php\">\n<pre class=\"de1\"><span class=\"re0\">$signature<\/span> <span class=\"sy0\">=<\/span> <span class=\"kw3\">base64_encode<\/span><span class=\"br0\">(<\/span><span class=\"kw3\">hash_hmac<\/span><span class=\"br0\">(<\/span><span class=\"st0\">\"sha256\"<\/span><span class=\"sy0\">,<\/span> <span class=\"re0\">$headerAndPayload<\/span><span class=\"sy0\">,<\/span> <span class=\"re0\">$secret<\/span><span class=\"sy0\">,<\/span> <span class=\"kw4\">true<\/span><span class=\"br0\">)<\/span><span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>Now you\u2019ve got the header, payload, and signature as individual textual components. Join them all together with <code>.<\/code> separators to create the JWT to send to your client:<\/p>\n<div class=\"wp-geshi-highlight-wrap5\">\n<div class=\"wp-geshi-highlight-wrap4\">\n<div class=\"wp-geshi-highlight-wrap3\">\n<div class=\"wp-geshi-highlight-wrap2\">\n<div class=\"wp-geshi-highlight-wrap\">\n<div class=\"wp-geshi-highlight\">\n<div class=\"php\">\n<pre class=\"de1\"><span class=\"re0\">$jwt<\/span> <span class=\"sy0\">=<\/span> <span class=\"st0\">\"<span class=\"es4\">$header<\/span>.<span class=\"es4\">$payload<\/span>.<span class=\"es4\">$signature<\/span>\"<\/span><span class=\"sy0\">;<\/span><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h2 id=\"verifying-incoming-jwts\"><span class=\"ez-toc-section\" id=\"Verifying_Incoming_JWTs\"><\/span>Verifying Incoming JWTs<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The client application can determine the features available to the user by decoding the token\u2019s payload. Here\u2019s an example in JavaScript:<\/p>\n<div class=\"wp-geshi-highlight-wrap5\">\n<div class=\"wp-geshi-highlight-wrap4\">\n<div class=\"wp-geshi-highlight-wrap3\">\n<div class=\"wp-geshi-highlight-wrap2\">\n<div class=\"wp-geshi-highlight-wrap\">\n<div class=\"wp-geshi-highlight\">\n<div class=\"javascript\">\n<pre class=\"de1\"><span class=\"kw1\">const<\/span> tokenComponents <span class=\"sy0\">=<\/span> jwt.<span class=\"me1\">split<\/span><span class=\"br0\">(<\/span><span class=\"st0\">\".\"<\/span><span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n<span class=\"kw1\">const<\/span> payload <span class=\"sy0\">=<\/span> token<span class=\"br0\">[<\/span><span class=\"nu0\">1<\/span><span class=\"br0\">]<\/span><span class=\"sy0\">;<\/span>\n<span class=\"kw1\">const<\/span> payloadDecoded <span class=\"sy0\">=<\/span> JSON.<span class=\"me1\">parse<\/span><span class=\"br0\">(<\/span>atob<span class=\"br0\">(<\/span>payload<span class=\"br0\">)<\/span><span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n\u00a0\n<span class=\"co1\">\/\/ [\"todos\", \"calendar\", \"invoicing\"]<\/span>\nconsole.<span class=\"me1\">log<\/span><span class=\"br0\">(<\/span>payloadDecoded.<span class=\"me1\">licensedFeatures<\/span><span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>An attacker might realize this data is plain text and looks easy to modify. They could try to convince the server they\u2019ve got a bonus feature by changing the token\u2019s payload in their next request:<\/p>\n<div class=\"wp-geshi-highlight-wrap5\">\n<div class=\"wp-geshi-highlight-wrap4\">\n<div class=\"wp-geshi-highlight-wrap3\">\n<div class=\"wp-geshi-highlight-wrap2\">\n<div class=\"wp-geshi-highlight-wrap\">\n<div class=\"wp-geshi-highlight\">\n<div class=\"javascript\">\n<pre class=\"de1\"><span class=\"co1\">\/\/ Create a new payload component<\/span>\n<span class=\"kw1\">const<\/span> modifiedPayload <span class=\"sy0\">=<\/span> btoa<span class=\"br0\">(<\/span>JSON.<span class=\"me1\">stringify<\/span><span class=\"br0\">(<\/span><span class=\"br0\">{<\/span>\n    ...<span class=\"me1\">payloadDecoded<\/span><span class=\"sy0\">,<\/span>\n    licensedFeatures<span class=\"sy0\">:<\/span> <span class=\"br0\">[<\/span><span class=\"st0\">\"todos\"<\/span><span class=\"sy0\">,<\/span> <span class=\"st0\">\"calendar\"<\/span><span class=\"sy0\">,<\/span> <span class=\"st0\">\"invoicing\"<\/span><span class=\"sy0\">,<\/span> <span class=\"st0\">\"extraPremiumFeature\"<\/span><span class=\"br0\">]<\/span>\n<span class=\"br0\">}<\/span><span class=\"br0\">)<\/span><span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n\u00a0\n<span class=\"co1\">\/\/ Stitch the JWT back together with the original header and signature<\/span>\n<span class=\"kw1\">const<\/span> newJwt <span class=\"sy0\">=<\/span> `$<span class=\"br0\">{<\/span>token<span class=\"br0\">[<\/span><span class=\"nu0\">0<\/span><span class=\"br0\">]<\/span><span class=\"br0\">}<\/span>.$<span class=\"br0\">{<\/span>modifiedPayload<span class=\"br0\">}<\/span>.$<span class=\"br0\">{<\/span>token<span class=\"br0\">[<\/span><span class=\"nu0\">2<\/span><span class=\"br0\">]<\/span><span class=\"br0\">}<\/span>`<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>The answer to how the server defends against these attacks lies in the method used to generate the signature. The signature value takes into account the token\u2019s header and payload. Modifying the payload, as in this example, means the signature is no longer valid.<\/p>\n<p>Server-side code verifies incoming JWTs by recomputing their signatures. The token has been tampered with if the signature sent by the client doesn\u2019t match the value generated on the server.<\/p>\n<div class=\"wp-geshi-highlight-wrap5\">\n<div class=\"wp-geshi-highlight-wrap4\">\n<div class=\"wp-geshi-highlight-wrap3\">\n<div class=\"wp-geshi-highlight-wrap2\">\n<div class=\"wp-geshi-highlight-wrap\">\n<div class=\"wp-geshi-highlight\">\n<div class=\"php\">\n<pre class=\"de1\"><span class=\"re0\">$tamperedToken<\/span> <span class=\"sy0\">=<\/span> <span class=\"re0\">$_POST<\/span><span class=\"br0\">[<\/span><span class=\"st0\">\"apiKey\"<\/span><span class=\"br0\">]<\/span><span class=\"sy0\">;<\/span>\n<span class=\"kw3\">list<\/span><span class=\"br0\">(<\/span><span class=\"re0\">$header<\/span><span class=\"sy0\">,<\/span> <span class=\"re0\">$payload<\/span><span class=\"sy0\">,<\/span> <span class=\"re0\">$signature<\/span><span class=\"br0\">)<\/span> <span class=\"sy0\">=<\/span> <span class=\"re0\">$tamperedToken<\/span><span class=\"sy0\">;<\/span>\n\u00a0\n<span class=\"co1\">\/\/ Determine the signature this token *should* have <\/span>\n<span class=\"co1\">\/\/ when the server's secret is used as the key<\/span>\n<span class=\"re0\">$expectedSignature<\/span> <span class=\"sy0\">=<\/span> <span class=\"kw3\">hash_hmac<\/span><span class=\"br0\">(<\/span><span class=\"st0\">\"sha256\"<\/span><span class=\"sy0\">,<\/span> <span class=\"st0\">\"<span class=\"es4\">$header<\/span>.<span class=\"es4\">$payload<\/span>\"<\/span><span class=\"sy0\">,<\/span> <span class=\"re0\">$secret<\/span><span class=\"sy0\">,<\/span> <span class=\"kw4\">true<\/span><span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n\u00a0\n<span class=\"co1\">\/\/ The token has been tampered with because its <\/span>\n<span class=\"co1\">\/\/ signature is incorrect for the data it includes<\/span>\n<span class=\"kw1\">if<\/span> <span class=\"br0\">(<\/span><span class=\"re0\">$signature<\/span> <span class=\"sy0\">!==<\/span> <span class=\"re0\">$expectedSignature<\/span><span class=\"br0\">)<\/span> <span class=\"br0\">{<\/span>\n    http_response_code<span class=\"br0\">(<\/span><span class=\"nu0\">403<\/span><span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n<span class=\"br0\">}<\/span>\n<span class=\"co1\">\/\/ The signatures match - we generated this <\/span>\n<span class=\"co1\">\/\/ token and can safely trust its data<\/span>\n<span class=\"kw1\">else<\/span> <span class=\"br0\">{<\/span>\n    <span class=\"re0\">$user<\/span> <span class=\"sy0\">=<\/span> fetchUserById<span class=\"br0\">(<\/span><span class=\"re0\">$payload<\/span><span class=\"br0\">[<\/span><span class=\"st0\">\"userId\"<\/span><span class=\"br0\">]<\/span><span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n<span class=\"br0\">}<\/span><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>It\u2019s impossible for an attacker to generate a valid token without access to the server\u2019s secret. This also means that accidental loss \u2013 or deliberate rotation \u2013 of the secret will im<a href=\"https:\/\/buradabiliyorum.com\/en\/category\/social-mediaa\/\" data-internallinksmanager029f6b8e52c=\"1\" title=\"Social Media\" target=\"_blank\" rel=\"noopener\">media<\/a>tely invalidate all previously issued tokens.<\/p>\n<p>In a real-world situation, your authentication code should also inspect the expiration and \u201cnot before\u201d timestamps in the token\u2019s payload. These are used to determine whether the user\u2019s session is still valid.<\/p>\n<h2 id=\"when-to-use-jwts\"><span class=\"ez-toc-section\" id=\"When_to_Use_JWTs\"><\/span>When to Use JWTs<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>JWTs are frequently used for API authentication because they\u2019re straightforward to implement on the server, easy to consume on the client, and simple to transmit across network boundaries. Despite their simplicity they have good security because each token is signed using the server\u2019s secret key.<\/p>\n<p>JWTs are a stateless mechanism so you don\u2019t need to record information about issued tokens on your server. You can get information about the client that presents a JWT from the token\u2019s payload, instead of having to perform a look-up in a database. This information can be safely trusted once you\u2019ve verified the token\u2019s signature.<\/p>\n<p>Using JWTs is a good choice whenever you need to exchange information between two parties without the risk of tampering. There are weak spots to be aware of though: the whole system will be compromised if your server\u2019s secret key is leaked, or your signature verification code contains a bug. For this reason many developers choose to use an open-source library to implement JWT generation and validation. Options are available for all popular programming languages. They eliminate the risk of oversight when you verify tokens yourself.<\/p>\n<h2 id=\"summary\"><span class=\"ez-toc-section\" id=\"Summary\"><\/span>Summary<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The JWT standard is a data exchange format that includes built-in integrity verification. JWTs are commonly used to secure interactions between API servers and client applications. The server can trust incoming tokens if it\u2019s able to reproduce their signatures. This allows actions to be safely performed using information obtained from the token\u2019s payload.<\/p>\n<p>JWTs are convenient but they do have some drawbacks. A JWT\u2019s Base64-encoded textual representation can quickly become large if you\u2019ve got more than a handful of payload fields. This could become an unacceptable overhead when your client needs to send the JWT with each request.<\/p>\n<p>The statelessness of JWTs is another potential downside too: once they\u2019re issued, tokens are immutable and must be used as-is until they expire. Clients that use JWT payloads to determine a user\u2019s permissions or licensed features will need to get a new token from the backend whenever their assignations change.<\/p>\n<\/div>\n<p><script>\n setTimeout(function(){\n  !function(f,b,e,v,n,t,s)\n  {if(f.fbq)return;n=f.fbq=function(){n.callMethod?\n  n.callMethod.apply(n,arguments):n.queue.push(arguments)};\n  if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';\n  n.queue=[];t=b.createElement(e);t.async=!0;\n  t.src=v;s=b.getElementsByTagName(e)[0];\n  s.parentNode.insertBefore(t,s) } (window, document,'script',\n  'https:\/\/connect.facebook.net\/en_US\/fbevents.js');\n   fbq('init', '335401813750447');\n   fbq('track', 'PageView');\n  },3000);\n<\/script><\/p>\n<blockquote><p><strong><span style=\"color: #ff6600;\">If you liked the article, do not forget to share it with your friends. Follow us on\u00a0<span style=\"color: #ff0000;\"><a style=\"color: #ff0000;\" href=\"https:\/\/news.google.com\/publications\/CAAqBwgKMLG0nwswvr63Aw\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">Google News<\/a><\/span>\u00a0too, click on the star and choose us from your favorites.<\/span><\/strong><\/p><\/blockquote>\n<blockquote>\n<p style=\"text-align: center;\">For forums sites go to <span style=\"color: #ff9900;\"><a style=\"color: #ff9900;\" href=\"https:\/\/forum.buradabiliyorum.com\/\" target=\"_blank\" rel=\"noopener\">Forum.BuradaBiliyorum.Com<\/a><\/span><\/strong><\/p>\n<\/blockquote>\n<blockquote>\n<p style=\"text-align: center;\"><strong>If you want to read more like this article, you can visit our <span style=\"color: #ff9900;\"><a style=\"color: #ff9900;\" href=\"https:\/\/en.buradabiliyorum.com\/technology\/\" target=\"_blank\" rel=\"noopener\">Technology category.<\/a><\/span><\/strong><\/p>\n<\/blockquote>\n<p><span style=\"color: black;\"><a style=\"color: #ff9900;\" href=\"https:\/\/www.howtogeek.com\/devops\/what-are-json-web-tokens-jwts-why-do-apis-use-them\/\" target=\"_blank\" rel=\"noopener\">Source<\/a><\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>&#8220;What Are JSON Web Tokens (JWTs)? Why Do APIs Use Them?&#8221; Shutterstock.com\/TierneyMJ The JSON Web Tokens (JWT) standard describes a compact method for verifiable data transfers. Each token contains a signature that allows the issuing party to check the message\u2019s integrity. In this article, you\u2019ll learn what the JWT structure includes and how you can&#8230;<\/p>\n","protected":false},"author":1,"featured_media":485885,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"fifu_image_url":"https:\/\/www.howtogeek.com\/wp-content\/uploads\/2022\/08\/shutterstock_1931787956.jpg?height=200p&trim=2,2,2,2","fifu_image_alt":"","footnotes":""},"categories":[18],"tags":[],"class_list":["post-485884","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-technology"],"_links":{"self":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts\/485884","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/comments?post=485884"}],"version-history":[{"count":0,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts\/485884\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/media\/485885"}],"wp:attachment":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/media?parent=485884"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/categories?post=485884"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/tags?post=485884"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}