Для поля jwtFilter требовался компонент типа filter.JwtFilter’, который не удалось найти.?

#java #spring #jwt

#java #весна #jwt

Вопрос:

Я хочу запустить свое весеннее приложение после того, как я выполнил некоторую конфигурацию аутентификации jwt. но у меня есть эти проблемы :

Описание:

 Field jwtFilter in com.soheibKehal.CashApi.config.SecurityConfig required a bean of type 'filter.JwtFilter' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'filter.JwtFilter' in your configuration.
 

Дело в том, что в моем классе SecurityConfig я уже использовал свой метод AuthentificationManager, поэтому я не знаю, в чем проблема?

     package com.soheibKehal.CashApi.config;

import com.soheibKehal.CashApi.services.CustomUserDetailService;
import filter.JwtFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Autowired
        private CustomUserDetailService userDetailsService;
    
        @Autowired
        private JwtFilter jwtFilter;
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService);
        }
        @Bean
        public PasswordEncoder passwordEncoder(){
            return NoOpPasswordEncoder.getInstance();
        }
    
        @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
        @Override
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable().authorizeRequests().antMatchers("/authenticate")
                    .permitAll().anyRequest().authenticated()
                    .and().exceptionHandling().and().sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
            http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);;
        }
    }
 

мой класс jwtFilter :

   package filter;

import com.soheibKehal.CashApi.Util.JwtUtil;
import com.soheibKehal.CashApi.services.CustomUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
    @Component
    public class JwtFilter extends OncePerRequestFilter {
    
        @Autowired
        private JwtUtil jwtUtil;
        @Autowired
        private CustomUserDetailService service;
    
    
        @Override
        protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException, IOException, ServletException {
    
            String authorizationHeader = httpServletRequest.getHeader("Authorization");
    
            String token = null;
            String userName = null;
    
            if (authorizationHeader != null amp;amp; authorizationHeader.startsWith("Bearer ")) {
                token = authorizationHeader.substring(7);
                userName = jwtUtil.extractUsername(token);
            }
    
            if (userName != null amp;amp; SecurityContextHolder.getContext().getAuthentication() == null) {
    
                UserDetails userDetails = service.loadUserByUsername(userName);
    
                if (jwtUtil.validateToken(token, userDetails)) {
    
                    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                            new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    usernamePasswordAuthenticationToken
                            .setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
                    SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
                }
            }
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        }
    }
 

У вас есть какие — нибудь идеи , в чем проблема ?

Комментарии:

1. Является ли ваш jwtFilter расширением OncePerRequestFilter?

2. Я отредактировал с помощью своего фильтра jwt, как вы можете видеть, да! @OnomeSotu

3. Можете ли вы проверить структуру своего пакета? Каковы имена пакетов для вашего класса filter и SecurityConfig?

4. Я редактировал с помощью пакета bro! @OnomeSotu

Ответ №1:

Я думаю, что проблема кроется в вашей структуре пакета. Springboot просканирует ваше приложение на предмет автоконфигурации, начиная с пакета, в котором у вас есть класс этой структуры

 @SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

}
 

Он должен быть в упаковке com.soheibKehal.CashApi .

Решение будет заключаться в том, чтобы переместить пакет с фильтром в com.soheibKehal.CashApi соседний с вашим config пакет.

Тогда spring сможет найти JwtFilter для автоконфигурации.

Комментарии:

1. О боже, как же я это пропустила, да, моя посылка была отправлена … я чувствую себя такой глупой прямо сейчас …. спасибо

2. Это случается. Не кори себя за это. Просто всегда создавайте свои пакеты таким образом, чтобы автоконфигурация работала.