Unterschiede
Hier werden die Unterschiede zwischen zwei Versionen angezeigt.
| Nächste Überarbeitung | Vorhergehende Überarbeitung | ||
| de:modul:ffit:3-jahr:java:learningunits:lu08:aufgaben:a05 [2025/10/28 09:41] – angelegt apeter | de:modul:ffit:3-jahr:java:learningunits:lu08:aufgaben:a05 [2025/10/28 09:48] (aktuell) – apeter | ||
|---|---|---|---|
| Zeile 4: | Zeile 4: | ||
| <code java> | <code java> | ||
| + | package ch.bzz.controller; | ||
| + | |||
| + | |||
| @RestController | @RestController | ||
| public class ProjectApiController implements ProjectApi { | public class ProjectApiController implements ProjectApi { | ||
| Zeile 25: | Zeile 28: | ||
| </ | </ | ||
| + | Versuchen Sie so weit wie möglich die beiden Methoden zu implementieren. | ||
| + | |||
| + | Für das Erstellen des JWT können Sie folgende Hilfsklasse verwenden. | ||
| + | <code java> | ||
| + | import io.jsonwebtoken.Jwts; | ||
| + | import io.jsonwebtoken.SignatureAlgorithm; | ||
| + | import io.jsonwebtoken.security.Keys; | ||
| + | import jakarta.annotation.PostConstruct; | ||
| + | import org.springframework.beans.factory.annotation.Value; | ||
| + | import org.springframework.stereotype.Component; | ||
| + | |||
| + | import java.security.Key; | ||
| + | import java.util.Date; | ||
| + | |||
| + | @Component | ||
| + | public class JwtUtil { | ||
| + | |||
| + | @Value(" | ||
| + | private String secret; | ||
| + | |||
| + | private Key key; | ||
| + | |||
| + | @PostConstruct | ||
| + | public void init() { | ||
| + | key = Keys.hmacShaKeyFor(secret.getBytes()); | ||
| + | } | ||
| + | |||
| + | public String generateToken(String projectName) { | ||
| + | Date currentTime = new Date(); | ||
| + | Date expirationTime = new Date(currentTime.getTime() + 3_600_000); | ||
| + | |||
| + | return Jwts.builder() | ||
| + | .setSubject(projectName) | ||
| + | .setIssuer(" | ||
| + | .setIssuedAt(currentTime) | ||
| + | .setExpiration(expirationTime) | ||
| + | .signWith(key, | ||
| + | .compact(); | ||
| + | } | ||
| + | |||
| + | public boolean validateToken(String token) { | ||
| + | try { | ||
| + | Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token); | ||
| + | return true; | ||
| + | } catch (Exception e) { | ||
| + | return false; | ||
| + | } | ||
| + | } | ||
| + | } | ||
| + | </ | ||