|
| 1 | +package io.jsonwebtoken.jjwtfun.controller; |
| 2 | + |
| 3 | +import io.jsonwebtoken.Claims; |
| 4 | +import io.jsonwebtoken.Jws; |
| 5 | +import io.jsonwebtoken.Jwts; |
| 6 | +import io.jsonwebtoken.MalformedJwtException; |
| 7 | +import io.jsonwebtoken.SignatureAlgorithm; |
| 8 | +import io.jsonwebtoken.SignatureException; |
| 9 | +import org.springframework.http.HttpStatus; |
| 10 | +import org.springframework.web.bind.annotation.ExceptionHandler; |
| 11 | +import org.springframework.web.bind.annotation.RequestMapping; |
| 12 | +import org.springframework.web.bind.annotation.RequestParam; |
| 13 | +import org.springframework.web.bind.annotation.ResponseStatus; |
| 14 | +import org.springframework.web.bind.annotation.RestController; |
| 15 | + |
| 16 | +import java.io.UnsupportedEncodingException; |
| 17 | +import java.time.Instant; |
| 18 | +import java.time.temporal.ChronoUnit; |
| 19 | +import java.util.Date; |
| 20 | +import java.util.HashMap; |
| 21 | +import java.util.Map; |
| 22 | + |
| 23 | +@RestController |
| 24 | +public class FixedJWTController { |
| 25 | + |
| 26 | + @RequestMapping("/fixed-builder") |
| 27 | + public String fixedBuilder() throws UnsupportedEncodingException { |
| 28 | + |
| 29 | + String jws = Jwts.builder() |
| 30 | + .setSubject("msilverman") |
| 31 | + .setExpiration(Date.from(Instant.now().plus(1, ChronoUnit.DAYS))) |
| 32 | + .claim("name", "Micah Silverman") |
| 33 | + .claim("scope", "admins") |
| 34 | + .signWith( |
| 35 | + SignatureAlgorithm.HS256, |
| 36 | + "secret".getBytes("UTF-8") |
| 37 | + ) |
| 38 | + .compact(); |
| 39 | + |
| 40 | + return jws; |
| 41 | + } |
| 42 | + |
| 43 | + @RequestMapping("/fixed-parser") |
| 44 | + public Jws<Claims> fixedParser(@RequestParam String jws) throws UnsupportedEncodingException { |
| 45 | + Jws<Claims> claims = Jwts.parser() |
| 46 | + .setSigningKey("secret".getBytes("UTF-8")) |
| 47 | + .parseClaimsJws(jws); |
| 48 | + |
| 49 | + return claims; |
| 50 | + } |
| 51 | + |
| 52 | + @ResponseStatus(HttpStatus.BAD_REQUEST) |
| 53 | + @ExceptionHandler({SignatureException.class, MalformedJwtException.class}) |
| 54 | + public Map<String, String> exception(Exception e) { |
| 55 | + Map<String, String> response = new HashMap<>(); |
| 56 | + response.put("status", "ERROR"); |
| 57 | + response.put("message", e.getMessage()); |
| 58 | + response.put("exception-type", e.getClass().getName()); |
| 59 | + return response; |
| 60 | + } |
| 61 | +} |
0 commit comments