Tuesday, 24 June 2025

jwt authentication and authorization

 

๐Ÿ” What Is JWT (JSON Web Token)?

JWT is a compact, URL-safe token format used to represent claims securely between two parties.


✅ Key Uses:

PurposeDescription
AuthenticationVerifies user identity (who are you?)
AuthorizationGrants access to resources (what can you do?)

๐Ÿง  Real-World Analogy

Imagine entering a theater:

  • You show a ticket (JWT).

  • The ticket proves your identity and permissions (e.g., VIP, regular).

  • The staff doesn’t ask your name again — they just validate the ticket.


๐Ÿ” JWT Flow (Authentication + Authorization)

text
Client → (username & password) → Server ← JWT Token ← Client → (JWT token in header) → Server → Validates → Access granted

๐Ÿ“ฆ JWT Structure

A JWT has three parts (Base64 encoded):

css

HEADER.PAYLOAD.SIGNATURE

1. Header

Specifies algorithm and type:

json

{ "alg": "HS256", "typ": "JWT" }

2. Payload

Claims like username, roles, etc.:

json

{ "sub": "user1", "role": "ADMIN", "exp": 1723553791 }

3. Signature

Verifies token integrity using secret key:

scss

HMACSHA256(base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)

✅ JWT Authentication in Spring Boot

๐Ÿ”ง Maven Dependency

xml

<dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency>

๐Ÿ“ Typical Components

1. Login Controller

java

@PostMapping("/login") public ResponseEntity<?> login(@RequestBody LoginRequest req) { if (authService.validate(req.getUsername(), req.getPassword())) { String token = jwtUtil.generateToken(req.getUsername()); return ResponseEntity.ok(new AuthResponse(token)); } return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); }

2. JWT Utility Class

java

public class JwtUtil { private final String SECRET = "mySecretKey"; public String generateToken(String username) { return Jwts.builder() .setSubject(username) .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTimeMillis() + 86400000)) // 1 day .signWith(SignatureAlgorithm.HS256, SECRET) .compact(); } public String extractUsername(String token) { return Jwts.parser().setSigningKey(SECRET) .parseClaimsJws(token).getBody().getSubject(); } public boolean validateToken(String token, String username) { return extractUsername(token).equals(username); } }

3. JWT Filter (for Authorization)

java

public class JwtFilter extends OncePerRequestFilter { @Autowired private JwtUtil jwtUtil; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String header = request.getHeader("Authorization"); String token = null; String username = null; if (header != null && header.startsWith("Bearer ")) { token = header.substring(7); username = jwtUtil.extractUsername(token); } if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(username, null, new ArrayList<>()); SecurityContextHolder.getContext().setAuthentication(authToken); } filterChain.doFilter(request, response); } }

4. Security Config

java

@EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private JwtFilter jwtFilter; @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("/login").permitAll() .anyRequest().authenticated(); http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class); } }

๐Ÿ“ฅ Example Request & Token

๐Ÿ” Login Request

http

POST /login Content-Type: application/json { "username": "admin", "password": "admin123" }

✅ Response:

json

{ "token": "eyJhbGciOiJIUzI1NiJ9..." }

๐Ÿ”’ Authenticated Request:

http

GET /products Authorization: Bearer eyJhbGciOiJIUzI1NiJ9...

๐Ÿงพ Summary

ConceptExplanation
AuthenticationUser logs in, receives JWT token
AuthorizationUser sends token in headers for future requests
Token ValidationServer verifies signature, expiry, and claims
StatelessNo server session storage needed

No comments:

Post a Comment