Harden auth: separate access/refresh JWT, atomic refresh rotation, admin checks
- Refresh JWT carried no role but was accepted by JwtAuthenticationFilter and the STOMP CONNECT as an access token; tokens now carry a typ claim and the filters accept only access tokens (legacy tokens are told apart by role). - Refresh rotation uses GETDEL, so one refresh token cannot be spent twice; refresh tokens are no longer written to logs. - isCurrentUserAdmin and file deletion compared authorities with "ADMIN" instead of "ROLE_ADMIN", so admins were never recognised. - getCurrentUser answers 401 for anonymous requests; profile update keeps the login when the field is not sent; registration rejects empty login/password. - GlobalExceptionHandler turned AccessDenied, BadCredentials, EntityNotFound, Spring MVC 4xx errors and upload limits into 500. - Presigned URL TTL is capped at 7 days. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -27,6 +27,7 @@ public class FileStorageController {
|
||||
* Вместе с кэшем ссылки (12ч) укладывается в её срок жизни (24ч).
|
||||
*/
|
||||
private static final Duration REDIRECT_CACHE_MAX_AGE = Duration.ofHours(6);
|
||||
private static final long MAX_PRESIGNED_TTL_HOURS = 7 * 24;
|
||||
|
||||
private final FileStorageService fileStorageService;
|
||||
|
||||
@@ -68,7 +69,8 @@ public class FileStorageController {
|
||||
@GetMapping("/url/{*objectName}")
|
||||
public ResponseEntity<Map<String, String>> getPresignedUrl(@PathVariable String objectName, @RequestParam(value = "ttlHours", required = false, defaultValue = "24") long ttlHours) {
|
||||
String key = objectName.startsWith("/") ? objectName.substring(1) : objectName;
|
||||
Duration ttl = ttlHours > 0 ? Duration.ofHours(ttlHours) : Duration.ofHours(24);
|
||||
// SigV4 не подписывает ссылки дольше 7 дней: больший ttlHours ронял presigner с 500
|
||||
Duration ttl = ttlHours > 0 ? Duration.ofHours(Math.min(ttlHours, MAX_PRESIGNED_TTL_HOURS)) : Duration.ofHours(24);
|
||||
String url = fileStorageService.generatePresignedDownloadUrl(key, ttl);
|
||||
return ResponseEntity.ok(Map.of("url", url));
|
||||
}
|
||||
|
||||
@@ -3,15 +3,23 @@ package com.krylov.refound.exception;
|
||||
import com.krylov.refound.ai.exception.ContentBlockedException;
|
||||
import com.krylov.refound.dto.ModerationErrorDetails;
|
||||
import com.krylov.refound.enums.ErrorCode;
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Map;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.validation.BindException;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
||||
import org.springframework.web.multipart.MaxUploadSizeExceededException;
|
||||
|
||||
@RestControllerAdvice
|
||||
@Slf4j
|
||||
@@ -44,8 +52,74 @@ public class GlobalExceptionHandler {
|
||||
return buildResponse(HttpStatus.BAD_REQUEST, ErrorCode.VALIDATION_ERROR, message, request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ошибки привязки параметров (@Valid на @ModelAttribute, неверный тип в query/path).
|
||||
* MethodArgumentNotValidException обрабатывается выше и сюда не попадает.
|
||||
*/
|
||||
@ExceptionHandler(BindException.class)
|
||||
public ResponseEntity<ErrorResponse> handleBind(BindException ex, HttpServletRequest request) {
|
||||
String message = ex.getBindingResult()
|
||||
.getFieldErrors()
|
||||
.stream()
|
||||
.findFirst()
|
||||
.map(e -> e.getField() + " " + e.getDefaultMessage())
|
||||
.orElse("Validation error");
|
||||
return buildResponse(HttpStatus.BAD_REQUEST, ErrorCode.VALIDATION_ERROR, message, request);
|
||||
}
|
||||
|
||||
@ExceptionHandler({MethodArgumentTypeMismatchException.class, HttpMessageNotReadableException.class})
|
||||
public ResponseEntity<ErrorResponse> handleBadInput(Exception ex, HttpServletRequest request) {
|
||||
log.debug("Bad request {}: {}", request.getRequestURI(), ex.getMessage());
|
||||
String message = ex instanceof MethodArgumentTypeMismatchException mismatch
|
||||
? "Некорректное значение параметра " + mismatch.getName()
|
||||
: "Некорректное тело запроса";
|
||||
return buildResponse(HttpStatus.BAD_REQUEST, ErrorCode.VALIDATION_ERROR, message, request);
|
||||
}
|
||||
|
||||
@ExceptionHandler(MaxUploadSizeExceededException.class)
|
||||
public ResponseEntity<ErrorResponse> handleMaxUploadSize(MaxUploadSizeExceededException ex, HttpServletRequest request) {
|
||||
return buildResponse(HttpStatus.PAYLOAD_TOO_LARGE, ErrorCode.VALIDATION_ERROR,
|
||||
"Файл или запрос слишком большой", request);
|
||||
}
|
||||
|
||||
/**
|
||||
* @PreAuthorize бросает AccessDeniedException внутри контроллера — без этого
|
||||
* обработчика её перехватывал handleUnknown и отвечал 500 вместо 403.
|
||||
*/
|
||||
@ExceptionHandler(AccessDeniedException.class)
|
||||
public ResponseEntity<ErrorResponse> handleAccessDenied(AccessDeniedException ex, HttpServletRequest request) {
|
||||
return buildResponse(HttpStatus.FORBIDDEN, ErrorCode.FORBIDDEN, "Forbidden", request);
|
||||
}
|
||||
|
||||
/** BadCredentialsException из /auth/refresh и т.п. — это 401, а не 500. */
|
||||
@ExceptionHandler(AuthenticationException.class)
|
||||
public ResponseEntity<ErrorResponse> handleAuthentication(AuthenticationException ex, HttpServletRequest request) {
|
||||
return buildResponse(HttpStatus.UNAUTHORIZED, ErrorCode.UNAUTHORIZED, ex.getMessage(), request);
|
||||
}
|
||||
|
||||
@ExceptionHandler(EntityNotFoundException.class)
|
||||
public ResponseEntity<ErrorResponse> handleEntityNotFound(EntityNotFoundException ex, HttpServletRequest request) {
|
||||
return buildResponse(HttpStatus.NOT_FOUND, ErrorCode.NOT_FOUND, ex.getMessage(), request);
|
||||
}
|
||||
|
||||
/** Гонка на уникальных ключах (повторная регистрация, двойной клик «в избранное»). */
|
||||
@ExceptionHandler(DataIntegrityViolationException.class)
|
||||
public ResponseEntity<ErrorResponse> handleDataIntegrity(DataIntegrityViolationException ex, HttpServletRequest request) {
|
||||
log.warn("Data integrity violation on {}: {}", request.getRequestURI(), ex.getMostSpecificCause().getMessage());
|
||||
return buildResponse(HttpStatus.CONFLICT, ErrorCode.BAD_REQUEST, "Конфликт данных, повторите запрос", request);
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<ErrorResponse> handleUnknown(Exception ex, HttpServletRequest request) {
|
||||
// Исключения Spring MVC (404 без маршрута, 405, 415, пропущенный параметр и т.п.)
|
||||
// сами знают свой HTTP-статус — без этой ветки они превращались в 500
|
||||
if (ex instanceof org.springframework.web.ErrorResponse springError) {
|
||||
HttpStatus status = HttpStatus.resolve(springError.getStatusCode().value());
|
||||
if (status != null && !status.is5xxServerError()) {
|
||||
return buildResponse(status, status == HttpStatus.NOT_FOUND ? ErrorCode.NOT_FOUND : ErrorCode.BAD_REQUEST,
|
||||
springError.getBody().getDetail(), request);
|
||||
}
|
||||
}
|
||||
log.error("Unexpected error", ex);
|
||||
|
||||
return buildResponse(
|
||||
|
||||
@@ -5,7 +5,6 @@ import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -37,7 +36,7 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
final String token = authHeader.substring(7);
|
||||
|
||||
try {
|
||||
if (jwtService.isTokenValid(token) && SecurityContextHolder.getContext().getAuthentication() == null) {
|
||||
if (jwtService.isAccessTokenValid(token) && SecurityContextHolder.getContext().getAuthentication() == null) {
|
||||
String login = jwtService.extractLogin(token);
|
||||
String role = jwtService.extractRole(token);
|
||||
|
||||
|
||||
@@ -16,6 +16,13 @@ import org.springframework.stereotype.Service;
|
||||
public class JwtService {
|
||||
|
||||
private static final String ROLE_CLAIM = "role";
|
||||
/**
|
||||
* Тип токена. Access- и refresh-токены подписаны одним ключом, поэтому без
|
||||
* этого claim долгоживущий refresh-токен принимался бы как access-токен.
|
||||
*/
|
||||
private static final String TYPE_CLAIM = "typ";
|
||||
private static final String ACCESS_TYPE = "access";
|
||||
private static final String REFRESH_TYPE = "refresh";
|
||||
|
||||
@Value("${jwt.secret}")
|
||||
private String secret;
|
||||
@@ -29,6 +36,7 @@ public class JwtService {
|
||||
public String generateAccessToken(String login, String role) {
|
||||
Map<String, Object> claims = new HashMap<>();
|
||||
claims.put(ROLE_CLAIM, role);
|
||||
claims.put(TYPE_CLAIM, ACCESS_TYPE);
|
||||
return buildToken(claims, login, accessExpiration);
|
||||
}
|
||||
|
||||
@@ -37,7 +45,9 @@ public class JwtService {
|
||||
* чтобы получить новый access-токен, а не для прямого доступа к API.
|
||||
*/
|
||||
public String generateRefreshToken(String login) {
|
||||
return buildToken(new HashMap<>(), login, refreshExpiration);
|
||||
Map<String, Object> claims = new HashMap<>();
|
||||
claims.put(TYPE_CLAIM, REFRESH_TYPE);
|
||||
return buildToken(claims, login, refreshExpiration);
|
||||
}
|
||||
|
||||
public long getRefreshExpirationMillis() {
|
||||
@@ -62,21 +72,35 @@ public class JwtService {
|
||||
return extractClaim(token, claims -> claims.get(ROLE_CLAIM, String.class));
|
||||
}
|
||||
|
||||
public boolean isTokenValid(String token) {
|
||||
/**
|
||||
* Токен годится для доступа к API (HTTP и WebSocket). Токены, выданные до
|
||||
* появления claim "typ", различаем по роли: она есть только у access-токена.
|
||||
*/
|
||||
public boolean isAccessTokenValid(String token) {
|
||||
try {
|
||||
String login = extractLogin(token);
|
||||
return login != null && !isTokenExpired(token);
|
||||
Claims claims = extractAllClaims(token);
|
||||
if (claims.getSubject() == null || claims.getExpiration().before(new Date())) {
|
||||
return false;
|
||||
}
|
||||
String type = claims.get(TYPE_CLAIM, String.class);
|
||||
return type == null ? claims.get(ROLE_CLAIM) != null : ACCESS_TYPE.equals(type);
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isTokenExpired(String token) {
|
||||
return extractExpiration(token).before(new Date());
|
||||
}
|
||||
|
||||
private Date extractExpiration(String token) {
|
||||
return extractClaim(token, Claims::getExpiration);
|
||||
/** Токен годится только для обмена на новую пару в /auth/refresh. */
|
||||
public boolean isRefreshTokenValid(String token) {
|
||||
try {
|
||||
Claims claims = extractAllClaims(token);
|
||||
if (claims.getSubject() == null || claims.getExpiration().before(new Date())) {
|
||||
return false;
|
||||
}
|
||||
String type = claims.get(TYPE_CLAIM, String.class);
|
||||
return type == null ? claims.get(ROLE_CLAIM) == null : REFRESH_TYPE.equals(type);
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
|
||||
|
||||
@@ -53,7 +53,6 @@ public class SecurityConfig {
|
||||
.requestMatchers(HttpMethod.GET, "/api/v1/ads-media/**").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/api/v1/posts/**").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/api/v1/reviews/**").permitAll()
|
||||
.requestMatchers("/files/**", "/uploads/**").permitAll()
|
||||
.requestMatchers("/ws/**").permitAll() // авторизация чата — на уровне STOMP CONNECT interceptor, см. заметку ниже
|
||||
|
||||
// изменяющие операции — только для авторизованных
|
||||
|
||||
@@ -12,23 +12,30 @@ import com.krylov.refound.exception.InvalidCredentialsException;
|
||||
import com.krylov.refound.exception.LoginAlreadyExistsException;
|
||||
import com.krylov.refound.repository.UserRepository;
|
||||
import com.krylov.refound.security.JwtService;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.authentication.BadCredentialsException;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AuthService {
|
||||
|
||||
private static final int MAX_LOGIN_LENGTH = 255;
|
||||
private static final int MIN_PASSWORD_LENGTH = 1;
|
||||
private static final int MAX_PASSWORD_BYTES = 72;
|
||||
|
||||
private final UserRepository userRepository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final JwtService jwtService;
|
||||
private final RefreshTokenService refreshTokenService;
|
||||
|
||||
public UserRegisterDto registerUser(RegisterRequest request) {
|
||||
validateRegistration(request);
|
||||
if (userRepository.findByLogin(request.getLogin()).isPresent()) {
|
||||
log.warn("registration failed: login {} already taken", request.getLogin());
|
||||
throw new LoginAlreadyExistsException("Логин уже занят");
|
||||
@@ -42,23 +49,21 @@ public class AuthService {
|
||||
|
||||
String accessToken = jwtService.generateAccessToken(user.getLogin(), user.getRole().name());
|
||||
String refreshToken = refreshTokenService.issue(user.getLogin());
|
||||
log.info("Refresh token returned = {}", refreshToken);
|
||||
UserDto userDto = getUserDto(user);
|
||||
|
||||
return new UserRegisterDto(userDto, accessToken, refreshToken);
|
||||
}
|
||||
|
||||
public UserRegisterDto loginUser(AuthRequest request) {
|
||||
User user = userRepository.findByLogin(request.getLogin()).orElse(null);
|
||||
User user = request.getLogin() == null ? null : userRepository.findByLogin(request.getLogin()).orElse(null);
|
||||
|
||||
if (user == null || !passwordEncoder.matches(request.getPassword(), user.getPassword())) {
|
||||
if (user == null || request.getPassword() == null || !passwordEncoder.matches(request.getPassword(), user.getPassword())) {
|
||||
log.warn("login failed: login or password incorrect for {}", request.getLogin());
|
||||
throw new InvalidCredentialsException("Неверный логин или пароль");
|
||||
}
|
||||
|
||||
String accessToken = jwtService.generateAccessToken(user.getLogin(), user.getRole().name());
|
||||
String refreshToken = refreshTokenService.issue(user.getLogin());
|
||||
log.info("Refresh token returned = {}", refreshToken);
|
||||
UserDto userDto = getUserDto(user);
|
||||
|
||||
return new UserRegisterDto(userDto, accessToken, refreshToken);
|
||||
@@ -69,18 +74,15 @@ public class AuthService {
|
||||
}
|
||||
|
||||
public AuthResponse refresh(RefreshRequest request) {
|
||||
String login = refreshTokenService.validateAndGetLogin(request.getRefreshToken())
|
||||
// ротация: consume отзывает старый refresh-токен, выдаём новую пару
|
||||
String login = refreshTokenService.consume(request.getRefreshToken())
|
||||
.orElseThrow(() -> new BadCredentialsException("Invalid or expired refresh token"));
|
||||
|
||||
User user = userRepository.findByLogin(login)
|
||||
.orElseThrow(() -> new BadCredentialsException("User not found"));
|
||||
|
||||
// ротация: старый refresh-токен отзываем, выдаём новую пару
|
||||
refreshTokenService.revoke(request.getRefreshToken());
|
||||
|
||||
String newAccessToken = jwtService.generateAccessToken(user.getLogin(), user.getRole().name());
|
||||
String newRefreshToken = refreshTokenService.issue(user.getLogin());
|
||||
log.info("Refresh token returned = {}", newRefreshToken);
|
||||
return new AuthResponse(newAccessToken, newRefreshToken, getUserDto(user));
|
||||
}
|
||||
|
||||
@@ -88,6 +90,23 @@ public class AuthService {
|
||||
refreshTokenService.revoke(request.getRefreshToken());
|
||||
}
|
||||
|
||||
/**
|
||||
* Без проверки пустой логин сохранялся в БД, а null-пароль ронял BCrypt с 500.
|
||||
* Ответ при ошибке — тот же формат {"message"}, что и у занятого логина.
|
||||
*/
|
||||
private static void validateRegistration(RegisterRequest request) {
|
||||
if (!StringUtils.hasText(request.getLogin()) || request.getLogin().length() > MAX_LOGIN_LENGTH) {
|
||||
throw new InvalidCredentialsException("Логин не может быть пустым или длиннее " + MAX_LOGIN_LENGTH + " символов");
|
||||
}
|
||||
String password = request.getPassword();
|
||||
// BCrypt учитывает только первые 72 байта пароля
|
||||
if (password == null || password.length() < MIN_PASSWORD_LENGTH
|
||||
|| password.getBytes(StandardCharsets.UTF_8).length > MAX_PASSWORD_BYTES) {
|
||||
throw new InvalidCredentialsException("Пароль должен быть от " + MIN_PASSWORD_LENGTH + " до "
|
||||
+ MAX_PASSWORD_BYTES + " символов");
|
||||
}
|
||||
}
|
||||
|
||||
private static UserDto getUserDto(User user) {
|
||||
return new UserDto(
|
||||
user.getId(),
|
||||
|
||||
@@ -3,7 +3,6 @@ package com.krylov.refound.service;
|
||||
import com.krylov.refound.config.MinioProperties;
|
||||
import com.krylov.refound.dto.DownloadedFile;
|
||||
import com.krylov.refound.enums.ErrorCode;
|
||||
import com.krylov.refound.enums.Role;
|
||||
import com.krylov.refound.exception.ApiException;
|
||||
import java.io.IOException;
|
||||
import java.net.URLDecoder;
|
||||
@@ -269,7 +268,7 @@ public class FileStorageService {
|
||||
}
|
||||
|
||||
boolean isAdmin = authentication.getAuthorities().stream()
|
||||
.anyMatch(authority -> Role.ADMIN.name().equals(authority.getAuthority()));
|
||||
.anyMatch(authority -> UserService.ADMIN_AUTHORITY.equals(authority.getAuthority()));
|
||||
if (isAdmin) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,14 @@ import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/**
|
||||
* Refresh-токены. Клиент получает строку вида {@code <tokenId>.<jwt>}: JWT
|
||||
* проверяется по подписи, а tokenId — ключ записи {@code refresh_token:<tokenId>}
|
||||
* в Redis со значением login и TTL, равным сроку жизни токена. Запись в Redis
|
||||
* делает токен отзываемым (logout, ротация при refresh).
|
||||
*
|
||||
* <p>Сами токены в лог не пишем: по ним можно войти от имени пользователя.
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@@ -18,80 +26,60 @@ public class RefreshTokenService {
|
||||
private final StringRedisTemplate redisTemplate;
|
||||
private final JwtService jwtService;
|
||||
|
||||
/**
|
||||
* Создаёт refresh-токен, сохраняет его в Redis с TTL и привязкой к логину.
|
||||
* В качестве ключа используем не сам JWT, а отдельный UUID —
|
||||
* так тело токена не обязано быть валидным JWT для проверки существования в Redis,
|
||||
* упрощает revoke без необходимости парсить токен.
|
||||
*/
|
||||
/** Создаёт refresh-токен и сохраняет его в Redis с TTL и привязкой к логину. */
|
||||
public String issue(String login) {
|
||||
String tokenId = UUID.randomUUID().toString();
|
||||
String refreshJwt = jwtService.generateRefreshToken(login);
|
||||
log.info("Saving refresh token: key={}, login={}",
|
||||
KEY_PREFIX + tokenId,
|
||||
login);
|
||||
redisTemplate.opsForValue().set(
|
||||
KEY_PREFIX + tokenId,
|
||||
login,
|
||||
Duration.ofMillis(jwtService.getRefreshExpirationMillis())
|
||||
);
|
||||
|
||||
// Кодируем tokenId в сам JWT через отдельный claim, чтобы при refresh
|
||||
// можно было найти запись в Redis по этому id, а не по всему телу токена
|
||||
log.debug("Refresh token issued for login={}", login);
|
||||
return tokenId + "." + refreshJwt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверяет refresh-токен: валиден ли JWT и существует ли запись в Redis.
|
||||
* Возвращает login, если всё ок, иначе — пусто.
|
||||
* Проверяет refresh-токен и сразу отзывает его (одноразовый токен для ротации).
|
||||
* Запись в Redis удаляется атомарно (GETDEL), поэтому два параллельных
|
||||
* /auth/refresh с одним токеном не получат две новые пары.
|
||||
*
|
||||
* @return login владельца или пусто, если токен невалиден, отозван или истёк
|
||||
*/
|
||||
public java.util.Optional<String> validateAndGetLogin(String rawToken) {
|
||||
log.info("Incoming refresh token = {}", rawToken);
|
||||
|
||||
String[] parts = rawToken.split("\\.", 2);
|
||||
|
||||
log.info("parts.length = {}", parts.length);
|
||||
|
||||
|
||||
if (parts.length == 2) {
|
||||
log.info("tokenId={}", parts[0]);
|
||||
log.info("jwt={}", parts[1]);
|
||||
}
|
||||
|
||||
if (parts.length != 2) {
|
||||
public Optional<String> consume(String rawToken) {
|
||||
TokenParts parts = TokenParts.parse(rawToken);
|
||||
if (parts == null || !jwtService.isRefreshTokenValid(parts.jwt())) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
boolean valid = jwtService.isTokenValid(parts[1]);
|
||||
log.info("jwt valid={}", valid);
|
||||
|
||||
if (!valid) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
|
||||
String tokenId = parts[0];
|
||||
String jwt = parts[1];
|
||||
|
||||
if (!jwtService.isTokenValid(jwt)) {
|
||||
return java.util.Optional.empty();
|
||||
}
|
||||
|
||||
String storedLogin = redisTemplate.opsForValue().get(KEY_PREFIX + tokenId);
|
||||
String jwtLogin = jwtService.extractLogin(jwt);
|
||||
String storedLogin = redisTemplate.opsForValue().getAndDelete(KEY_PREFIX + parts.tokenId());
|
||||
String jwtLogin = jwtService.extractLogin(parts.jwt());
|
||||
|
||||
if (storedLogin == null || !storedLogin.equals(jwtLogin)) {
|
||||
return java.util.Optional.empty();
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
return java.util.Optional.of(jwtLogin);
|
||||
return Optional.of(jwtLogin);
|
||||
}
|
||||
|
||||
/** Ротация: старый токен удаляется, выпускается новый. */
|
||||
/** Отзыв токена при logout. Невалидный или пустой токен просто игнорируется. */
|
||||
public void revoke(String rawToken) {
|
||||
String[] parts = rawToken.split("\\.", 2);
|
||||
if (parts.length == 2) {
|
||||
redisTemplate.delete(KEY_PREFIX + parts[0]);
|
||||
TokenParts parts = TokenParts.parse(rawToken);
|
||||
if (parts != null) {
|
||||
redisTemplate.delete(KEY_PREFIX + parts.tokenId());
|
||||
}
|
||||
}
|
||||
|
||||
private record TokenParts(String tokenId, String jwt) {
|
||||
|
||||
static TokenParts parse(String rawToken) {
|
||||
if (rawToken == null || rawToken.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
String[] parts = rawToken.split("\\.", 2);
|
||||
if (parts.length != 2 || parts[0].isBlank() || parts[1].isBlank()) {
|
||||
return null;
|
||||
}
|
||||
return new TokenParts(parts[0], parts[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,27 +10,32 @@ import com.krylov.refound.repository.UserRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.authentication.AnonymousAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class UserService {
|
||||
public static final String ADMIN_AUTHORITY = "ROLE_" + Role.ADMIN.name();
|
||||
|
||||
private final UserRepository repository;
|
||||
private final FileStorageService fileStorageService;
|
||||
|
||||
public User getCurrentUser() {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
|
||||
if (authentication == null || authentication.getPrincipal() == null) {
|
||||
// Анонимный запрос тоже несёт Authentication (principal "anonymousUser") —
|
||||
// раньше он искался в БД как логин и давал 404 вместо 401
|
||||
if (authentication == null || authentication instanceof AnonymousAuthenticationToken
|
||||
|| !(authentication.getPrincipal() instanceof String login)) {
|
||||
throw new ApiException(ErrorCode.UNAUTHORIZED, "Пользователь не авторизован", HttpStatus.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
String login = (String) authentication.getPrincipal();
|
||||
|
||||
return repository.findByLogin(login)
|
||||
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "User not found", HttpStatus.NOT_FOUND));
|
||||
}
|
||||
@@ -41,8 +46,10 @@ public class UserService {
|
||||
if (authentication == null) {
|
||||
return false;
|
||||
}
|
||||
// JwtAuthenticationFilter кладёт роль с префиксом: "ROLE_ADMIN". Сравнение
|
||||
// с "ADMIN" никогда не срабатывало, и администратор не мог править чужой профиль
|
||||
return authentication.getAuthorities().stream()
|
||||
.anyMatch(authority -> Role.ADMIN.name().equals(authority.getAuthority()));
|
||||
.anyMatch(authority -> ADMIN_AUTHORITY.equals(authority.getAuthority()));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -73,12 +80,13 @@ public class UserService {
|
||||
User user = repository.findById(id)
|
||||
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "User not found", HttpStatus.NOT_FOUND));
|
||||
|
||||
if (dto.getLogin() != null && !dto.getLogin().equals(user.getLogin())
|
||||
&& repository.existsByLogin(dto.getLogin())) {
|
||||
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Логин уже занят", HttpStatus.BAD_REQUEST);
|
||||
// Логин не прислали — оставляем прежний: null в login ломал вход в аккаунт
|
||||
if (StringUtils.hasText(dto.getLogin()) && !dto.getLogin().equals(user.getLogin())) {
|
||||
if (repository.existsByLogin(dto.getLogin())) {
|
||||
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Логин уже занят", HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
user.setLogin(dto.getLogin());
|
||||
}
|
||||
|
||||
user.setLogin(dto.getLogin());
|
||||
user.setName(dto.getFirstName());
|
||||
user.setLastName(dto.getLastName());
|
||||
user.setPhone(dto.getPhone());
|
||||
|
||||
@@ -65,7 +65,7 @@ public class WsStompInterceptor implements ChannelInterceptor {
|
||||
|
||||
String token = authorization.substring(7);
|
||||
|
||||
if (!jwtService.isTokenValid(token)) {
|
||||
if (!jwtService.isAccessTokenValid(token)) {
|
||||
throw new IllegalArgumentException("Invalid JWT token");
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user