{"id":3769,"date":"2025-04-15T11:34:56","date_gmt":"2025-04-15T09:34:56","guid":{"rendered":"https:\/\/nguenkam.com\/blog\/?p=3769"},"modified":"2025-04-15T11:34:56","modified_gmt":"2025-04-15T09:34:56","slug":"understanding-json-web-tokens-jwt-in-javascript-and-angular","status":"publish","type":"post","link":"https:\/\/nguenkam.com\/blog\/index.php\/2025\/04\/15\/understanding-json-web-tokens-jwt-in-javascript-and-angular\/","title":{"rendered":"Understanding JSON Web Tokens (JWT) in JavaScript and Angular"},"content":{"rendered":"\n<p>JSON Web Tokens (JWT) are a compact, URL-safe means of representing claims to be transferred between two parties. This article will guide you through understanding JWT, generating it, and using it in an Angular application.<\/p>\n\n\n\n<h4>What is a JWT?<\/h4>\n\n\n\n<p>A JSON Web Token is a string made up of three parts: a header, a payload, and a signature, separated by dots (.). It is typically used to authenticate users and exchange information securely.<\/p>\n\n\n\n<h4>Structure of JWT<\/h4>\n\n\n\n<ol><li><strong>Header<\/strong>: Contains metadata about the token, such as the type of token (JWT) and the signing algorithm (e.g., HMAC SHA256).<\/li><li><strong>Payload<\/strong>: Contains the claims. Claims are statements about an entity (typically, the user) and additional data.<\/li><li><strong>Signature<\/strong>: Used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn&#8217;t changed along the way.<\/li><\/ol>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h4>Generating a JWT<\/h4>\n\n\n\n<p>To generate a JWT, you typically need a server-side library. Here\u2019s an example using Node.js with the <code>jsonwebtoken<\/code> package:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const jwt = require('jsonwebtoken');\n\nconst payload = {\n  username: 'exampleUser',\n  role: 'admin'\n};\n\nconst secret = 'your-256-bit-secret';\n\nconst token = jwt.sign(payload, secret, { expiresIn: '1h' });\n\nconsole.log(token);<\/code><\/pre>\n\n\n\n<div style=\"height:100px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<h4>Generating a JWT Using Java Spring Boot<\/h4>\n\n\n\n<p>To generate a JWT in a Spring Boot application, we can use the <code>jjwt<\/code> library. Here&#8217;s a step-by-step guide:<\/p>\n\n\n\n<ol><li><span class=\"has-inline-color has-vivid-cyan-blue-color\"><strong>Add Dependencie<\/strong><\/span>s (Add the <code>jjwt<\/code> dependency to our <code>pom.xml<\/code>)<\/li><\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;dependency>\r\n    &lt;groupId>io.jsonwebtoken&lt;\/groupId>\r\n    &lt;artifactId>jjwt&lt;\/artifactId>\r\n    &lt;version>0.9.1&lt;\/version>\r\n&lt;\/dependency>\r<\/code><\/pre>\n\n\n\n<p><strong><span class=\"has-inline-color has-vivid-cyan-blue-color\">2. Create a JWT Utility Class <\/span><\/strong>(Create a utility class to handle the creation of JWT tokens.)<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import io.jsonwebtoken.Jwts;\r\nimport io.jsonwebtoken.SignatureAlgorithm;\r\n\r\nimport java.util.Date;\r\n\r\npublic class JwtUtil {\r\n\r\n    private String secretKey = \"your-secret-key\";\r\n\r\n    public String generateToken(String username) {\r\n        return Jwts.builder()\r\n                .setSubject(username)\r\n                .setIssuedAt(new Date())\r\n                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10)) \/\/ 10 hours\r\n                .signWith(SignatureAlgorithm.HS256, secretKey)\r\n                .compact();\r\n    }\r\n}\r<\/code><\/pre>\n\n\n\n<p><span class=\"has-inline-color has-vivid-cyan-blue-color\"><strong>3. Use the Utility Class in our Application<\/strong><\/span><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class AuthService {\r\n\r\n    private JwtUtil jwtUtil = new JwtUtil();\r\n\r\n    public String authenticateUser(String username, String password) {\r\n        \/\/ Validate user credentials (this is just an example)\r\n        if (\"exampleUser\".equals(username) &amp;&amp; \"password\".equals(password)) {\r\n            return jwtUtil.generateToken(username);\r\n        }\r\n        throw new RuntimeException(\"Invalid credentials\");\r\n    }\r\n}\r<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h4>Using JWT in Angular<\/h4>\n\n\n\n<p>In an Angular application, JWTs are often used for authenticating API requests. Here\u2019s a simple example of how you can use JWT for authentication:<\/p>\n\n\n\n<ol><li><strong>Install Dependencies<\/strong>: First, ensure you have <code>@auth0\/angular-jwt<\/code> installed.<\/li><\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>   npm install @auth0\/angular-jwt<\/code><\/pre>\n\n\n\n<ol start=\"2\"><li><strong>Setup HTTP Interceptor<\/strong>: Create an HTTP interceptor to append the JWT to your requests.<\/li><\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>   import { Injectable } from '@angular\/core';\n   import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular\/common\/http';\n   import { Observable } from 'rxjs';\n   import { AuthService } from '.\/auth.service';\n\n   @Injectable()\n   export class JwtInterceptor implements HttpInterceptor {\n     constructor(private authService: AuthService) {}\n\n     intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {\n       const token = this.authService.getToken();\n       if (token) {\n         request = request.clone({\n           setHeaders: {\n             Authorization: `Bearer ${token}`\n           }\n         });\n       }\n       return next.handle(request);\n     }\n   }<\/code><\/pre>\n\n\n\n<ol start=\"3\"><li><strong>Add Interceptor to Angular Module<\/strong>:<\/li><\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>   import { HTTP_INTERCEPTORS } from '@angular\/common\/http';\n   import { JwtInterceptor } from '.\/jwt.interceptor';\n\n   @NgModule({\n     providers: &#91;\n       { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true }\n     ]\n   })\n   export class AppModule {}<\/code><\/pre>\n\n\n\n<ol start=\"4\"><li><strong>AuthService<\/strong>: A simple service to manage JWT.<\/li><\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>   import { Injectable } from '@angular\/core';\n\n   @Injectable({\n     providedIn: 'root'\n   })\n   export class AuthService {\n     private token: string | null = null;\n\n     setToken(token: string): void {\n       this.token = token;\n     }\n\n     getToken(): string | null {\n       return this.token;\n     }\n   }<\/code><\/pre>\n\n\n\n<div style=\"height:100px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<h5>Conclusion<\/h5>\n\n\n\n<p>JWTs are a powerful tool for authentication and secure data exchange. By understanding how to generate and use JWTs in Angular, you can create more secure and efficient web applications.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>JSON Web Tokens (JWT) are a compact, URL-safe means of representing claims to be transferred between two parties. This article will guide you through understanding JWT, generating it, and using it in an Angular application. What is a JWT? A JSON Web Token is a string made up of three parts: a header, a payload, [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":2892,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[37,5,868],"tags":[385,737,232,927],"_links":{"self":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/3769"}],"collection":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/comments?post=3769"}],"version-history":[{"count":1,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/3769\/revisions"}],"predecessor-version":[{"id":3770,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/3769\/revisions\/3770"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/media\/2892"}],"wp:attachment":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/media?parent=3769"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/categories?post=3769"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/tags?post=3769"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}