Last active
March 11, 2025 05:05
-
-
Save aimtiaz11/239c933eb9a2213f270989935f11316d to your computer and use it in GitHub Desktop.
Create JWT Token - API Controller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.company.controller; | |
import com.company.model.SuccessResponseModel; | |
import io.jsonwebtoken.Jwts; | |
import io.jsonwebtoken.security.Keys; | |
import org.springframework.http.ResponseEntity; | |
import org.springframework.web.bind.annotation.GetMapping; | |
import org.springframework.web.bind.annotation.RequestMapping; | |
import org.springframework.web.bind.annotation.RestController; | |
import reactor.core.publisher.Mono; | |
import java.security.Key; | |
import java.util.Base64; | |
import java.util.Date; | |
@RestController | |
@RequestMapping("/api/v1") | |
public class JwtTokenController { | |
// In plaintext for demo purpose, ALWAYS HAVE THIS ENCRYPTED !! | |
private final String base64Secret = "9hgSUF1MeeRfwArdmfn9DHoTYr909raQL5rSUN9EhAZA00oItuPbiY80Gk7QqB37yl9eK4"; | |
private final long ttl = 30 * 1000L; // 30 seconds | |
@GetMapping("/token") | |
public Mono<ResponseEntity<SuccessResponseModel>> generateToken() { | |
long nowMillis = System.currentTimeMillis(); | |
Date now = new Date(nowMillis); | |
Date expiryDate = new Date(nowMillis + ttl); | |
Key key = Keys.hmacShaKeyFor(Base64.getDecoder().decode(base64Secret)); | |
String jwt = Jwts.builder() | |
.header() | |
.add("typ", "JWT") | |
.add("alg", "HS256") | |
.and() | |
.subject("user") | |
.issuedAt(now) | |
.expiration(expiryDate) | |
.signWith(key) | |
.compact(); | |
SuccessResponseModel responseModel = new SuccessResponseModel(); | |
responseModel.setToken(jwt); | |
return Mono.just(ResponseEntity.ok()).map(e -> ResponseEntity.ok(responseModel)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment