authentication with spring security
This commit is contained in:
@@ -1,13 +1,12 @@
|
||||
package com.example.mtusi_messenger.service;
|
||||
|
||||
import com.example.mtusi_messenger.exception.ApiExceptions;
|
||||
import com.example.mtusi_messenger.model.Session;
|
||||
import com.example.mtusi_messenger.model.User;
|
||||
import com.example.mtusi_messenger.repository.SessionRepository;
|
||||
import com.example.mtusi_messenger.repository.UserRepository;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import com.example.mtusi_messenger.security.SessionPrincipal;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.authentication.BadCredentialsException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
@@ -16,24 +15,19 @@ import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.Enumeration;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
public class AuthenticationService {
|
||||
private static final String AUTHORIZATION = "Authorization";
|
||||
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
|
||||
|
||||
private final UserRepository users;
|
||||
private final SessionRepository sessions;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final long ttlSeconds;
|
||||
private final String dummyPasswordHash;
|
||||
|
||||
public AuthenticationService(
|
||||
UserRepository users,
|
||||
SessionRepository sessions,
|
||||
PasswordEncoder passwordEncoder,
|
||||
@Value("${messenger.session.ttl-seconds:3600}") long ttlSeconds
|
||||
) {
|
||||
if (ttlSeconds <= 0) {
|
||||
@@ -41,30 +35,10 @@ public class AuthenticationService {
|
||||
}
|
||||
this.users = users;
|
||||
this.sessions = sessions;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.ttlSeconds = ttlSeconds;
|
||||
this.dummyPasswordHash = passwordEncoder.encode("dummy-password-used-only-for-timing");
|
||||
}
|
||||
|
||||
public IssuedSession login(HttpServletRequest request) {
|
||||
BasicCredentials credentials = parseBasic(singleAuthorizationHeader(request, true));
|
||||
var stored = users.findCredentialsByUsername(credentials.username());
|
||||
String passwordHash = stored.map(UserRepository.UserCredentials::passwordHash)
|
||||
.filter(hash -> hash.startsWith("$argon2"))
|
||||
.orElse(dummyPasswordHash);
|
||||
|
||||
boolean passwordMatches;
|
||||
try {
|
||||
passwordMatches = passwordEncoder.matches(credentials.password(), passwordHash);
|
||||
} catch (IllegalArgumentException e) {
|
||||
passwordMatches = false;
|
||||
}
|
||||
|
||||
if (stored.isEmpty() || !passwordMatches) {
|
||||
throw ApiExceptions.unauthorizedBasic("Invalid credentials");
|
||||
}
|
||||
|
||||
User user = stored.get().user();
|
||||
public IssuedSession issueSession(User user) {
|
||||
String token = newToken();
|
||||
Instant createdAt = Instant.now();
|
||||
Instant expiresAt = createdAt.plusSeconds(ttlSeconds);
|
||||
@@ -74,69 +48,24 @@ public class AuthenticationService {
|
||||
hashToken(token),
|
||||
createdAt,
|
||||
expiresAt));
|
||||
|
||||
return new IssuedSession(token, expiresAt, user);
|
||||
}
|
||||
|
||||
public User requireBearer(HttpServletRequest request) {
|
||||
String token = parseBearer(singleAuthorizationHeader(request, false));
|
||||
UUID userId = sessions.findActiveUserId(hashToken(token))
|
||||
.orElseThrow(() -> ApiExceptions.unauthorizedBearer("Invalid or expired session"));
|
||||
return users.findById(userId)
|
||||
.orElseThrow(() -> ApiExceptions.unauthorizedBearer("Invalid or expired session"));
|
||||
public SessionPrincipal authenticateBearer(String token) {
|
||||
byte[] tokenHash = hashToken(token);
|
||||
UUID userId = sessions.findActiveUserId(tokenHash)
|
||||
.orElseThrow(() -> new BadCredentialsException("Invalid or expired session"));
|
||||
User user = users.findById(userId)
|
||||
.orElseThrow(() -> new BadCredentialsException("Invalid or expired session"));
|
||||
return new SessionPrincipal(user, tokenHash);
|
||||
}
|
||||
|
||||
public void logout(HttpServletRequest request) {
|
||||
String token = parseBearer(singleAuthorizationHeader(request, false));
|
||||
if (!sessions.revoke(hashToken(token))) {
|
||||
throw ApiExceptions.unauthorizedBearer("Invalid or expired session");
|
||||
public void revoke(SessionPrincipal principal) {
|
||||
if (!sessions.revoke(principal.tokenHash())) {
|
||||
throw new BadCredentialsException("Invalid or expired session");
|
||||
}
|
||||
}
|
||||
|
||||
private String singleAuthorizationHeader(HttpServletRequest request, boolean basic) {
|
||||
Enumeration<String> values = request.getHeaders(AUTHORIZATION);
|
||||
if (values == null || !values.hasMoreElements()) {
|
||||
throw basic
|
||||
? ApiExceptions.unauthorizedBasic("Authentication required")
|
||||
: ApiExceptions.unauthorizedBearer("Authentication required");
|
||||
}
|
||||
String value = values.nextElement();
|
||||
if (values.hasMoreElements()) {
|
||||
throw basic
|
||||
? ApiExceptions.unauthorizedBasic("Invalid Authorization header")
|
||||
: ApiExceptions.unauthorizedBearer("Invalid Authorization header");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private BasicCredentials parseBasic(String header) {
|
||||
if (!header.startsWith("Basic ") || header.length() == 6) {
|
||||
throw ApiExceptions.unauthorizedBasic("Invalid credentials");
|
||||
}
|
||||
try {
|
||||
byte[] decoded = Base64.getDecoder().decode(header.substring(6));
|
||||
String value = new String(decoded, StandardCharsets.UTF_8);
|
||||
int separator = value.indexOf(':');
|
||||
if (separator <= 0) {
|
||||
throw ApiExceptions.unauthorizedBasic("Invalid credentials");
|
||||
}
|
||||
return new BasicCredentials(value.substring(0, separator), value.substring(separator + 1));
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw ApiExceptions.unauthorizedBasic("Invalid credentials");
|
||||
}
|
||||
}
|
||||
|
||||
private String parseBearer(String header) {
|
||||
if (!header.startsWith("Bearer ") || header.length() == 7) {
|
||||
throw ApiExceptions.unauthorizedBearer("Invalid bearer token");
|
||||
}
|
||||
String token = header.substring(7);
|
||||
if (!token.matches("[A-Za-z0-9_-]{43}")) {
|
||||
throw ApiExceptions.unauthorizedBearer("Invalid bearer token");
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
private String newToken() {
|
||||
byte[] bytes = new byte[32];
|
||||
SECURE_RANDOM.nextBytes(bytes);
|
||||
@@ -153,5 +82,4 @@ public class AuthenticationService {
|
||||
}
|
||||
|
||||
public record IssuedSession(String token, Instant expiresAt, User user) {}
|
||||
private record BasicCredentials(String username, String password) {}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user