Add JWT-based login and logout endpoints
- POST /api/auth/login authenticates user and returns JWT token. - POST /api/auth/logout is a placeholder (client deletes token). - JwtService handles token creation and expiry validation.
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
package com.skycrate.backend.skycrateBackend.security;
|
||||
|
||||
import com.skycrate.backend.skycrateBackend.entity.User;
|
||||
import io.jsonwebtoken.*;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.security.Key;
|
||||
import java.util.Date;
|
||||
|
||||
@Service
|
||||
public class JwtService {
|
||||
|
||||
private static final String SECRET = "super-secret-256-bit-key-which-you-should-keep-safe!";
|
||||
private static final long EXPIRATION_MS = 1000 * 60 * 60; // 1 hour
|
||||
|
||||
private final Key key = Keys.hmacShaKeyFor(SECRET.getBytes());
|
||||
|
||||
public String generateToken(User user) {
|
||||
return Jwts.builder()
|
||||
.setSubject(user.getEmail())
|
||||
.setIssuedAt(new Date())
|
||||
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_MS))
|
||||
.signWith(key)
|
||||
.compact();
|
||||
}
|
||||
|
||||
public String extractUsername(String token) {
|
||||
return Jwts.parserBuilder().setSigningKey(key).build()
|
||||
.parseClaimsJws(token)
|
||||
.getBody().getSubject();
|
||||
}
|
||||
|
||||
public boolean isTokenValid(String token, User user) {
|
||||
return extractUsername(token).equals(user.getEmail()) && !isTokenExpired(token);
|
||||
}
|
||||
|
||||
public boolean isTokenExpired(String token) {
|
||||
return Jwts.parserBuilder().setSigningKey(key).build()
|
||||
.parseClaimsJws(token)
|
||||
.getBody().getExpiration().before(new Date());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user