added refresh token

This commit is contained in:
SlimusMinus
2026-08-03 02:43:46 +03:00
parent d3a231f3fc
commit 7660128d96
21 changed files with 309 additions and 138 deletions

View File

@@ -6,9 +6,12 @@ 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;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
@@ -36,13 +39,19 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
try {
if (jwtService.isTokenValid(token) && SecurityContextHolder.getContext().getAuthentication() == null) {
String login = jwtService.extractLogin(token);
String role = jwtService.extractRole(token);
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(login, null, new ArrayList<>());
List<GrantedAuthority> authorities = role != null
? List.of(new SimpleGrantedAuthority("ROLE_" + role))
: List.of();
UsernamePasswordAuthenticationToken authToken =
new UsernamePasswordAuthenticationToken(login, null, authorities);
authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authToken);
}
} catch (Exception e) {
// Token invalid — continue as unauthenticated
log.warn("Token invalid — continue as unauthenticated: {}", e.getMessage());
}
filterChain.doFilter(request, response);

View File

@@ -15,20 +15,38 @@ import org.springframework.stereotype.Service;
@Service
public class JwtService {
private static final String ROLE_CLAIM = "role";
@Value("${jwt.secret}")
private String secret;
@Value("${jwt.expiration}")
private long expiration;
@Value("${jwt.access-expiration}")
private long accessExpiration;
public String generateToken(String login) {
@Value("${jwt.refresh-expiration}")
private long refreshExpiration;
public String generateAccessToken(String login, String role) {
Map<String, Object> claims = new HashMap<>();
return generateToken(claims, login);
claims.put(ROLE_CLAIM, role);
return buildToken(claims, login, accessExpiration);
}
public String generateToken(Map<String, Object> extraClaims, String login) {
/**
* Refresh-токен не несёт роли и прав — он нужен только для того,
* чтобы получить новый access-токен, а не для прямого доступа к API.
*/
public String generateRefreshToken(String login) {
return buildToken(new HashMap<>(), login, refreshExpiration);
}
public long getRefreshExpirationMillis() {
return refreshExpiration;
}
private String buildToken(Map<String, Object> claims, String login, long expiration) {
return Jwts.builder()
.claims(extraClaims)
.claims(claims)
.subject(login)
.issuedAt(new Date(System.currentTimeMillis()))
.expiration(new Date(System.currentTimeMillis() + expiration))
@@ -40,6 +58,10 @@ public class JwtService {
return extractClaim(token, Claims::getSubject);
}
public String extractRole(String token) {
return extractClaim(token, claims -> claims.get(ROLE_CLAIM, String.class));
}
public boolean isTokenValid(String token) {
try {
String login = extractLogin(token);

View File

@@ -1,10 +1,17 @@
package com.krylov.refound.security;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
@@ -24,22 +31,42 @@ public class SecurityConfig {
private final JwtAuthenticationFilter jwtAuthenticationFilter;
@Value("${app.cors.allowed-origins}")
private String allowedOrigins;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
.csrf(AbstractHttpConfigurer::disable)
.csrf(AbstractHttpConfigurer::disable) // токен только в Authorization header, cookie не используется — CSRF не актуален
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.exceptionHandling(ex -> ex
.authenticationEntryPoint(this::handleUnauthorized)
.accessDeniedHandler(this::handleForbidden)
)
.authorizeHttpRequests(auth -> auth
// публичные эндпоинты
.requestMatchers("/api/v1/auth/**").permitAll()
.requestMatchers("/api/v1/test/**").permitAll()
.requestMatchers(HttpMethod.GET, "/api/v1/files/**").permitAll()
.requestMatchers(HttpMethod.POST, "/api/v1/files/**").permitAll()
.requestMatchers(HttpMethod.DELETE, "/api/v1/files/**").permitAll()
.requestMatchers(HttpMethod.GET, "/api/v1/posts/**").permitAll()
.requestMatchers("/api/v1/reviews/**").permitAll()
.requestMatchers(HttpMethod.GET, "/api/v1/reviews/**").permitAll()
.requestMatchers("/files/**", "/uploads/**").permitAll()
.requestMatchers("/ws/**").permitAll()
.requestMatchers("/ws/**").permitAll() // авторизация чата — на уровне STOMP CONNECT interceptor, см. заметку ниже
// изменяющие операции — только для авторизованных
.requestMatchers(HttpMethod.POST, "/api/v1/files/**").authenticated()
.requestMatchers(HttpMethod.DELETE, "/api/v1/files/**").authenticated()
.requestMatchers(HttpMethod.POST, "/api/v1/reviews/**").authenticated()
.requestMatchers(HttpMethod.PUT, "/api/v1/reviews/**").authenticated()
.requestMatchers(HttpMethod.DELETE, "/api/v1/reviews/**").authenticated()
.requestMatchers(HttpMethod.POST, "/api/v1/posts/**").authenticated()
.requestMatchers(HttpMethod.PUT, "/api/v1/posts/**").authenticated()
.requestMatchers(HttpMethod.DELETE, "/api/v1/posts/**").authenticated()
// пример разграничения по ролям — раскомментировать и адаптировать под свои admin-эндпоинты
// .requestMatchers("/api/v1/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
@@ -47,15 +74,33 @@ public class SecurityConfig {
return http.build();
}
private void handleUnauthorized(HttpServletRequest request, HttpServletResponse response,
org.springframework.security.core.AuthenticationException authException)
throws IOException {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.getWriter().write("{\"message\":\"Unauthorized\"}");
}
private void handleForbidden(HttpServletRequest request, HttpServletResponse response,
org.springframework.security.access.AccessDeniedException accessDeniedException)
throws IOException {
response.setStatus(HttpStatus.FORBIDDEN.value());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.getWriter().write("{\"message\":\"Forbidden\"}");
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOriginPatterns(List.of("*"));
List<String> origins = Arrays.stream(allowedOrigins.split(","))
.map(String::trim)
.filter(s -> !s.isEmpty())
.toList();
config.setAllowedMethods(List.of(
"GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"
));
config.setAllowedOrigins(origins);
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
config.setAllowedHeaders(List.of("*"));
config.setAllowCredentials(true);
config.setMaxAge(3600L);