refactor(SecurityFilter): Stop filters from being registered on all routes (#361)
* see pr message * fix: + use PathPattern for request matching + include common public route to whitelist + logging for failed queryjwt * forgot to remove debug code
This commit is contained in:
@@ -10,6 +10,7 @@ import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.http.server.PathContainer;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||
@@ -33,8 +34,11 @@ import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.web.util.pattern.PathPattern;
|
||||
import org.springframework.web.util.pattern.PathPatternParser;
|
||||
|
||||
@Slf4j
|
||||
@AllArgsConstructor
|
||||
@@ -44,7 +48,8 @@ public class SecurityConfig {
|
||||
|
||||
private static final Pattern ALLOWED = Pattern.compile("\\s*,\\s*");
|
||||
private final OpdsUserDetailsService opdsUserDetailsService;
|
||||
private final JwtAuthenticationFilter dualJwtAuthenticationFilter;
|
||||
private final JwtAuthenticationFilter jwtAuthenticationFilter;
|
||||
private final AuthenticationCheckFilter authenticationCheckFilter;
|
||||
private final Environment env;
|
||||
|
||||
private static final String[] COMMON_PUBLIC_ENDPOINTS = {
|
||||
@@ -122,7 +127,8 @@ public class SecurityConfig {
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
|
||||
.addFilterBefore(koreaderAuthFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
.addFilterBefore(koreaderAuthFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterAfter(authenticationCheckFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@@ -140,7 +146,7 @@ public class SecurityConfig {
|
||||
|
||||
@Bean
|
||||
@Order(4)
|
||||
public SecurityFilterChain coverJwtApiSecurityChain(HttpSecurity http, CoverJwtFilter coverJwtFilter) throws Exception {
|
||||
public SecurityFilterChain coverJwtApiSecurityChain(HttpSecurity http, QueryParameterJwtFilter queryParameterJwtFilter) throws Exception {
|
||||
http
|
||||
.securityMatcher("/api/v1/media/**")
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
@@ -151,15 +157,15 @@ public class SecurityConfig {
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.anyRequest().permitAll()
|
||||
)
|
||||
.addFilterBefore(coverJwtFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterBefore(dualJwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
|
||||
.addFilterBefore(queryParameterJwtFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterAfter(authenticationCheckFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(5)
|
||||
public SecurityFilterChain customFontSecurityChain(HttpSecurity http, CustomFontJwtFilter customFontJwtFilter) throws Exception {
|
||||
public SecurityFilterChain customFontSecurityChain(HttpSecurity http, QueryParameterJwtFilter queryParameterJwtFilter) throws Exception {
|
||||
http
|
||||
.securityMatcher("/api/v1/custom-fonts/*/file")
|
||||
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
|
||||
@@ -168,13 +174,15 @@ public class SecurityConfig {
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.anyRequest().permitAll()
|
||||
)
|
||||
.addFilterBefore(customFontJwtFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
.addFilterBefore(queryParameterJwtFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterAfter(authenticationCheckFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(6)
|
||||
public SecurityFilterChain epubStreamingSecurityChain(HttpSecurity http, EpubStreamingJwtFilter epubStreamingJwtFilter) throws Exception {
|
||||
public SecurityFilterChain epubStreamingSecurityChain(HttpSecurity http, QueryParameterJwtFilter queryParameterJwtFilter) throws Exception {
|
||||
http
|
||||
.securityMatcher("/api/v1/epub/*/file/**")
|
||||
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
|
||||
@@ -183,13 +191,15 @@ public class SecurityConfig {
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.anyRequest().permitAll()
|
||||
)
|
||||
.addFilterBefore(epubStreamingJwtFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
.addFilterBefore(queryParameterJwtFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterAfter(authenticationCheckFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(7)
|
||||
public SecurityFilterChain audiobookStreamingSecurityChain(HttpSecurity http, AudiobookStreamingJwtFilter audiobookStreamingJwtFilter) throws Exception {
|
||||
public SecurityFilterChain audiobookStreamingSecurityChain(HttpSecurity http, QueryParameterJwtFilter queryParameterJwtFilter) throws Exception {
|
||||
http
|
||||
.securityMatcher("/api/v1/audiobooks/*/stream/**", "/api/v1/audiobooks/*/track/*/stream/**", "/api/v1/audiobooks/*/cover")
|
||||
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
|
||||
@@ -198,16 +208,65 @@ public class SecurityConfig {
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.anyRequest().permitAll()
|
||||
)
|
||||
.addFilterBefore(audiobookStreamingJwtFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterBefore(queryParameterJwtFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterAfter(authenticationCheckFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(8)
|
||||
public SecurityFilterChain jwtApiSecurityChain(HttpSecurity http) throws Exception {
|
||||
List<String> publicEndpoints = new ArrayList<>(Arrays.asList(COMMON_PUBLIC_ENDPOINTS));
|
||||
public SecurityFilterChain wsSecurityChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.securityMatcher("/api/**", "/komga/**", "/ws/**")
|
||||
.securityMatcher("/ws/**")
|
||||
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.headers(headers -> headers
|
||||
.referrerPolicy(referrer -> referrer.policy(
|
||||
ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN))
|
||||
.contentTypeOptions(contentType -> {})
|
||||
.frameOptions(HeadersConfigurer.FrameOptionsConfig::deny)
|
||||
)
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.anyRequest().permitAll()
|
||||
);
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(9)
|
||||
public SecurityFilterChain jwtApiSecurityChain(HttpSecurity http) throws Exception {
|
||||
var parser = new PathPatternParser();
|
||||
final List<PathPattern> matchPatterns = Stream.of(
|
||||
"/api/**",
|
||||
"/komga/**"
|
||||
).map(parser::parse).toList();
|
||||
final List<PathPattern> whitelistedPatterns = Stream.concat(
|
||||
Arrays.stream(COMMON_PUBLIC_ENDPOINTS),
|
||||
Stream.of(
|
||||
"/api/v1/opds",
|
||||
"/api/v1/opds/**",
|
||||
"/api/v2/opds",
|
||||
"/api/v2/opds/**",
|
||||
"/api/kobo",
|
||||
"/api/kobo/**",
|
||||
"/api/v1/auth/refresh",
|
||||
"/api/v1/setup"
|
||||
)
|
||||
).map(parser::parse).toList();
|
||||
|
||||
http
|
||||
.securityMatcher(request -> {
|
||||
var pathContainer = PathContainer.parsePath(request.getRequestURI());
|
||||
if (matchPatterns.parallelStream().noneMatch(p -> p.matches(pathContainer))) {
|
||||
return false;
|
||||
}
|
||||
if (whitelistedPatterns.parallelStream().anyMatch(p -> p.matches(pathContainer))) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
})
|
||||
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
@@ -219,15 +278,15 @@ public class SecurityConfig {
|
||||
)
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.dispatcherTypeMatchers(DispatcherType.ASYNC).permitAll()
|
||||
.requestMatchers(publicEndpoints.toArray(new String[0])).permitAll()
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
.addFilterBefore(dualJwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterAfter(authenticationCheckFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(9)
|
||||
@Order(10)
|
||||
public SecurityFilterChain staticResourcesSecurityChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
|
||||
-84
@@ -1,84 +0,0 @@
|
||||
package org.booklore.config.security.filter;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.booklore.config.security.JwtUtils;
|
||||
import org.booklore.config.security.userdetails.UserAuthenticationDetails;
|
||||
import org.booklore.mapper.custom.BookLoreUserTransformer;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.entity.BookLoreUserEntity;
|
||||
import org.booklore.repository.UserRepository;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Component
|
||||
@AllArgsConstructor
|
||||
public class AudiobookStreamingJwtFilter extends OncePerRequestFilter {
|
||||
|
||||
private static final Pattern AUDIOBOOK_STREAMING_ENDPOINT_PATTERN =
|
||||
Pattern.compile("/api/v1/audiobooks/\\d+/(stream|track/\\d+/stream|cover).*");
|
||||
|
||||
private final JwtUtils jwtUtils;
|
||||
private final UserRepository userRepository;
|
||||
private final BookLoreUserTransformer bookLoreUserTransformer;
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||
String path = request.getRequestURI();
|
||||
return !AUDIOBOOK_STREAMING_ENDPOINT_PATTERN.matcher(path).matches();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
|
||||
String token = extractTokenFromHeader(request);
|
||||
if (token == null) {
|
||||
token = request.getParameter("token");
|
||||
}
|
||||
|
||||
if (token == null || token.isEmpty()) {
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing authentication token");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (jwtUtils.validateToken(token)) {
|
||||
authenticateUser(token, request);
|
||||
} else {
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token");
|
||||
return;
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed: " + ex.getMessage());
|
||||
return;
|
||||
}
|
||||
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
private String extractTokenFromHeader(HttpServletRequest request) {
|
||||
String bearer = request.getHeader("Authorization");
|
||||
return (bearer != null && bearer.startsWith("Bearer ")) ? bearer.substring(7) : null;
|
||||
}
|
||||
|
||||
private void authenticateUser(String token, HttpServletRequest request) {
|
||||
Long userId = jwtUtils.extractUserId(token);
|
||||
BookLoreUserEntity entity = userRepository.findByIdWithDetails(userId)
|
||||
.orElseThrow(() -> new UsernameNotFoundException("User not found with ID: " + userId));
|
||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||
UsernamePasswordAuthenticationToken authentication =
|
||||
new UsernamePasswordAuthenticationToken(user, null, null);
|
||||
authentication.setDetails(new UserAuthenticationDetails(request, user.getId()));
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package org.booklore.config.security.filter;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.boot.web.servlet.FilterRegistration;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@Component
|
||||
@AllArgsConstructor
|
||||
@FilterRegistration(enabled = false)
|
||||
public class AuthenticationCheckFilter extends OncePerRequestFilter {
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
|
||||
var auth = SecurityContextHolder.getContext().getAuthentication();
|
||||
|
||||
if (auth == null || !auth.isAuthenticated()) {
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
return;
|
||||
}
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package org.booklore.config.security.filter;
|
||||
|
||||
import org.booklore.config.security.JwtUtils;
|
||||
import org.booklore.mapper.custom.BookLoreUserTransformer;
|
||||
import org.booklore.repository.UserRepository;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class CoverJwtFilter extends AbstractQueryParameterJwtFilter {
|
||||
|
||||
public CoverJwtFilter(
|
||||
JwtUtils jwtUtils,
|
||||
UserRepository userRepository,
|
||||
BookLoreUserTransformer bookLoreUserTransformer) {
|
||||
super(jwtUtils, userRepository, bookLoreUserTransformer);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||
String path = request.getRequestURI();
|
||||
return !path.startsWith("/api/v1/media/");
|
||||
}
|
||||
}
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
package org.booklore.config.security.filter;
|
||||
|
||||
import org.booklore.config.security.JwtUtils;
|
||||
import org.booklore.mapper.custom.BookLoreUserTransformer;
|
||||
import org.booklore.repository.UserRepository;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class CustomFontJwtFilter extends AbstractQueryParameterJwtFilter {
|
||||
|
||||
public CustomFontJwtFilter(
|
||||
JwtUtils jwtUtils,
|
||||
UserRepository userRepository,
|
||||
BookLoreUserTransformer bookLoreUserTransformer) {
|
||||
super(jwtUtils, userRepository, bookLoreUserTransformer);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||
String path = request.getRequestURI();
|
||||
return !(path.startsWith("/api/v1/custom-fonts/") && path.endsWith("/file"));
|
||||
}
|
||||
}
|
||||
-82
@@ -1,82 +0,0 @@
|
||||
package org.booklore.config.security.filter;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.booklore.config.security.JwtUtils;
|
||||
import org.booklore.config.security.userdetails.UserAuthenticationDetails;
|
||||
import org.booklore.mapper.custom.BookLoreUserTransformer;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.entity.BookLoreUserEntity;
|
||||
import org.booklore.repository.UserRepository;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Component
|
||||
@AllArgsConstructor
|
||||
public class EpubStreamingJwtFilter extends OncePerRequestFilter {
|
||||
|
||||
private static final Pattern EPUB_STREAMING_ENDPOINT_PATTERN = Pattern.compile("/api/v1/epub/\\d+/file/.*");
|
||||
private final JwtUtils jwtUtils;
|
||||
private final UserRepository userRepository;
|
||||
private final BookLoreUserTransformer bookLoreUserTransformer;
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||
String path = request.getRequestURI();
|
||||
return !EPUB_STREAMING_ENDPOINT_PATTERN.matcher(path).matches();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
|
||||
String token = extractTokenFromHeader(request);
|
||||
if (token == null) {
|
||||
token = request.getParameter("token");
|
||||
}
|
||||
|
||||
if (token == null || token.isEmpty()) {
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing authentication token");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (jwtUtils.validateToken(token)) {
|
||||
authenticateUser(token, request);
|
||||
} else {
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token");
|
||||
return;
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed: " + ex.getMessage());
|
||||
return;
|
||||
}
|
||||
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
private String extractTokenFromHeader(HttpServletRequest request) {
|
||||
String bearer = request.getHeader("Authorization");
|
||||
return (bearer != null && bearer.startsWith("Bearer ")) ? bearer.substring(7) : null;
|
||||
}
|
||||
|
||||
private void authenticateUser(String token, HttpServletRequest request) {
|
||||
Long userId = jwtUtils.extractUserId(token);
|
||||
BookLoreUserEntity entity = userRepository.findByIdWithDetails(userId)
|
||||
.orElseThrow(() -> new UsernameNotFoundException("User not found with ID: " + userId));
|
||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||
UsernamePasswordAuthenticationToken authentication =
|
||||
new UsernamePasswordAuthenticationToken(user, null, null);
|
||||
authentication.setDetails(new UserAuthenticationDetails(request, user.getId()));
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
}
|
||||
}
|
||||
+5
-17
@@ -12,6 +12,7 @@ import org.booklore.mapper.custom.BookLoreUserTransformer;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.entity.BookLoreUserEntity;
|
||||
import org.booklore.repository.UserRepository;
|
||||
import org.springframework.boot.web.servlet.FilterRegistration;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
@@ -24,30 +25,21 @@ import java.util.List;
|
||||
@Slf4j
|
||||
@Component
|
||||
@AllArgsConstructor
|
||||
@FilterRegistration(enabled = false)
|
||||
public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
|
||||
private final BookLoreUserTransformer bookLoreUserTransformer;
|
||||
private final JwtUtils jwtUtils;
|
||||
private final UserRepository userRepository;
|
||||
|
||||
private static final List<String> WHITELISTED_PATHS = List.of(
|
||||
"/api/v1/opds/",
|
||||
"/api/v2/opds/",
|
||||
"/api/v1/auth/refresh",
|
||||
"/api/v1/setup/",
|
||||
"/api/kobo/"
|
||||
);
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
|
||||
String token = extractToken(request);
|
||||
String path = request.getRequestURI();
|
||||
|
||||
boolean isWhitelisted = WHITELISTED_PATHS.stream().anyMatch(path::startsWith);
|
||||
if (isWhitelisted) {
|
||||
if (SecurityContextHolder.getContext().getAuthentication() != null &&
|
||||
SecurityContextHolder.getContext().getAuthentication().isAuthenticated()) {
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
String token = extractToken(request);
|
||||
|
||||
if (token == null) {
|
||||
chain.doFilter(request, response);
|
||||
@@ -59,13 +51,9 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
authenticateUser(token, request);
|
||||
} else {
|
||||
log.debug("Invalid token. Rejecting request.");
|
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
return;
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
log.error("Authentication error: {}", ex.getMessage(), ex);
|
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
return;
|
||||
}
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.entity.UserPermissionsEntity;
|
||||
import org.booklore.repository.KoboUserSettingsRepository;
|
||||
import org.booklore.repository.UserRepository;
|
||||
import org.springframework.boot.web.servlet.FilterRegistration;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
@@ -26,6 +27,7 @@ import java.util.List;
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
@Component
|
||||
@FilterRegistration(enabled = false)
|
||||
public class KoboAuthFilter extends OncePerRequestFilter {
|
||||
|
||||
private final KoboUserSettingsRepository koboUserSettingsRepository;
|
||||
@@ -36,12 +38,6 @@ public class KoboAuthFilter extends OncePerRequestFilter {
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
|
||||
|
||||
String path = request.getRequestURI();
|
||||
|
||||
if (!path.startsWith("/api/kobo/")) {
|
||||
filterChain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
|
||||
String[] parts = path.split("/");
|
||||
if (parts.length < 4) {
|
||||
log.warn("KOBO token missing in path");
|
||||
|
||||
+34
-31
@@ -8,6 +8,7 @@ import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.boot.web.servlet.FilterRegistration;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
@@ -21,50 +22,52 @@ import java.util.List;
|
||||
@RequiredArgsConstructor
|
||||
@Component
|
||||
@Slf4j
|
||||
@FilterRegistration(enabled = false)
|
||||
public class KoreaderAuthFilter extends OncePerRequestFilter {
|
||||
|
||||
private final KoreaderUserRepository koreaderUserRepository;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
|
||||
String username = request.getHeader("x-auth-user");
|
||||
String key = request.getHeader("x-auth-key");
|
||||
|
||||
String path = request.getRequestURI();
|
||||
if (!path.startsWith("/api/koreader/")) {
|
||||
if (username == null || key == null) {
|
||||
log.info("Missing KOReader headers");
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
|
||||
String username = request.getHeader("x-auth-user");
|
||||
String key = request.getHeader("x-auth-key");
|
||||
|
||||
if (username != null && key != null) {
|
||||
koreaderUserRepository.findByUsername(username).ifPresentOrElse(user -> {
|
||||
if (user.getPasswordMD5().equalsIgnoreCase(key)) {
|
||||
Long bookLoreUserId = null;
|
||||
if (user.getBookLoreUser() != null) {
|
||||
bookLoreUserId = user.getBookLoreUser().getId();
|
||||
}
|
||||
|
||||
UserDetails userDetails = new KoreaderUserDetails(
|
||||
user.getUsername(),
|
||||
user.getPasswordMD5(),
|
||||
user.isSyncEnabled(),
|
||||
user.isSyncWithBookloreReader(),
|
||||
bookLoreUserId,
|
||||
List.of(new SimpleGrantedAuthority("ROLE_USER"))
|
||||
);
|
||||
|
||||
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
|
||||
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
} else {
|
||||
log.warn("KOReader auth failed: password mismatch");
|
||||
}
|
||||
}, () -> log.warn("KOReader user not found"));
|
||||
} else {
|
||||
log.warn("Missing KOReader headers");
|
||||
var user = koreaderUserRepository.findByUsername(username).orElse(null);
|
||||
if (user == null) {
|
||||
log.info("KOReader user not found");
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!user.getPasswordMD5().equalsIgnoreCase(key)) {
|
||||
log.info("KOReader user password not match");
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
|
||||
Long bookLoreUserId = null;
|
||||
if (user.getBookLoreUser() != null) {
|
||||
bookLoreUserId = user.getBookLoreUser().getId();
|
||||
}
|
||||
|
||||
UserDetails userDetails = new KoreaderUserDetails(
|
||||
user.getUsername(),
|
||||
user.getPasswordMD5(),
|
||||
user.isSyncEnabled(),
|
||||
user.isSyncWithBookloreReader(),
|
||||
bookLoreUserId,
|
||||
List.of(new SimpleGrantedAuthority("ROLE_USER"))
|
||||
);
|
||||
|
||||
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
+16
-6
@@ -5,21 +5,27 @@ import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.booklore.config.security.JwtUtils;
|
||||
import org.booklore.config.security.userdetails.UserAuthenticationDetails;
|
||||
import org.booklore.mapper.custom.BookLoreUserTransformer;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.entity.BookLoreUserEntity;
|
||||
import org.booklore.repository.UserRepository;
|
||||
import org.springframework.boot.web.servlet.FilterRegistration;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@AllArgsConstructor
|
||||
public abstract class AbstractQueryParameterJwtFilter extends OncePerRequestFilter {
|
||||
@FilterRegistration(enabled = false)
|
||||
public class QueryParameterJwtFilter extends OncePerRequestFilter {
|
||||
|
||||
protected final JwtUtils jwtUtils;
|
||||
protected final UserRepository userRepository;
|
||||
@@ -28,9 +34,15 @@ public abstract class AbstractQueryParameterJwtFilter extends OncePerRequestFilt
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
if (SecurityContextHolder.getContext().getAuthentication() != null &&
|
||||
SecurityContextHolder.getContext().getAuthentication().isAuthenticated()) {
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
String token = request.getParameter("token");
|
||||
|
||||
if (token == null || token.isEmpty()) {
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing authentication token");
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -38,12 +50,10 @@ public abstract class AbstractQueryParameterJwtFilter extends OncePerRequestFilt
|
||||
if (jwtUtils.validateToken(token)) {
|
||||
authenticateUser(token, request);
|
||||
} else {
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token");
|
||||
return;
|
||||
log.debug("Invalid token. Rejecting request.");
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed: " + ex.getMessage());
|
||||
return;
|
||||
log.error("Authentication error: {}", ex.getMessage(), ex);
|
||||
}
|
||||
|
||||
chain.doFilter(request, response);
|
||||
Reference in New Issue
Block a user