Описание:
Параметр 0 конструктора в dev.spring.hibernatedemo.security. JwtAuthenticationFilter потребовался bean-компонент типа org.springframework.security.core.userdetails.UserDetailsService, который не удалось найти.
Действие:
Рассмотрите возможность определения bean-компонента типа org.springframework.security.core.userdetails.UserDetailsService в вашей конфигурации.
SecurityConfig.java:
Код: Выделить всё
package dev.spring.hibernatedemo.config;
import dev.spring.hibernatedemo.security.JwtAuthenticationEntryPoint;
import dev.spring.hibernatedemo.security.JwtAuthenticationFilter;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@AllArgsConstructor
public class SecurityConfig {
private JwtAuthenticationFilter jwtAuthenticationFilter;
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.cors(AbstractHttpConfigurer::disable)
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests((auth) -> auth.requestMatchers("/authenticate").permitAll().anyRequest().authenticated())
.exceptionHandling(ex -> ex.authenticationEntryPoint(jwtAuthenticationEntryPoint))
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.build();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
}
Код: Выделить всё
package dev.spring.hibernatedemo.security;
import io.jsonwebtoken.ExpiredJwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
@Component
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtHelper jwtHelper;
private final UserDetailsService userDetailsService;
public JwtAuthenticationFilter(UserDetailsService userDetailsService, JwtHelper jwtHelper) {
this.jwtHelper = jwtHelper;
this.userDetailsService = userDetailsService;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String requestHeader = request.getHeader("Authentication"); //Bearer
log.info("Header: {}", requestHeader);
String username = null;
String token = null;
if (requestHeader != null && requestHeader.startsWith("Bearer")) {
token = requestHeader.substring(7);
try {
username = jwtHelper.getUsernameFromToken(token);
} catch (IllegalArgumentException e) {
logger.info("Illegal Argument while fetching the username !!");
logger.error(e.getMessage());
} catch (ExpiredJwtException e) {
logger.info("Given jwt token is expired !!");
logger.error(e.getMessage());
} catch (Exception e) {
logger.error(e.getMessage());
}
} else {
logger.info("Invalid header!!");
}
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
Boolean validatedToken = this.jwtHelper.validateToken(token, userDetails);
if (validatedToken) {
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
} else {
logger.info("Validation failed!!!");
}
}
filterChain.doFilter(request, response);
}
}
Примечание: я следовал инструкциям Githublink.
Подробнее здесь: https://stackoverflow.com/questions/792 ... ecurity-co