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, and a signature, separated by dots (.). It is typically used to authenticate users and exchange information securely.
Structure of JWT
- Header: Contains metadata about the token, such as the type of token (JWT) and the signing algorithm (e.g., HMAC SHA256).
- Payload: Contains the claims. Claims are statements about an entity (typically, the user) and additional data.
- Signature: Used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn’t changed along the way.
Generating a JWT
To generate a JWT, you typically need a server-side library. Here’s an example using Node.js with the jsonwebtoken
package:
const jwt = require('jsonwebtoken');
const payload = {
username: 'exampleUser',
role: 'admin'
};
const secret = 'your-256-bit-secret';
const token = jwt.sign(payload, secret, { expiresIn: '1h' });
console.log(token);
Generating a JWT Using Java Spring Boot
To generate a JWT in a Spring Boot application, we can use the jjwt
library. Here’s a step-by-step guide:
- Add Dependencies (Add the
jjwt
dependency to ourpom.xml
)
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
2. Create a JWT Utility Class (Create a utility class to handle the creation of JWT tokens.)
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
public class JwtUtil {
private String secretKey = "your-secret-key";
public String generateToken(String username) {
return Jwts.builder()
.setSubject(username)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10)) // 10 hours
.signWith(SignatureAlgorithm.HS256, secretKey)
.compact();
}
}
3. Use the Utility Class in our Application
public class AuthService {
private JwtUtil jwtUtil = new JwtUtil();
public String authenticateUser(String username, String password) {
// Validate user credentials (this is just an example)
if ("exampleUser".equals(username) && "password".equals(password)) {
return jwtUtil.generateToken(username);
}
throw new RuntimeException("Invalid credentials");
}
}
Using JWT in Angular
In an Angular application, JWTs are often used for authenticating API requests. Here’s a simple example of how you can use JWT for authentication:
- Install Dependencies: First, ensure you have
@auth0/angular-jwt
installed.
npm install @auth0/angular-jwt
- Setup HTTP Interceptor: Create an HTTP interceptor to append the JWT to your requests.
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(private authService: AuthService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = this.authService.getToken();
if (token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${token}`
}
});
}
return next.handle(request);
}
}
- Add Interceptor to Angular Module:
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { JwtInterceptor } from './jwt.interceptor';
@NgModule({
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true }
]
})
export class AppModule {}
- AuthService: A simple service to manage JWT.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private token: string | null = null;
setToken(token: string): void {
this.token = token;
}
getToken(): string | null {
return this.token;
}
}
Conclusion
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.