当前位置: 首页 > 知识库问答 >
问题:

创建名为authenticationTokenFilterBean的bean时出错:通过字段tokenUtils表示的未满足的依赖项

田曜瑞
2023-03-14

我想在我的项目中实现Spring Security性。但不管我怎么做,我总是会犯同样的错误。

我创建了必要的类(TokenUtilsAuthentiationTokenFilterSpringConfiguration)。它们在同一个包下,但我得到以下错误。

这是发生问题的Stack Trace的一部分

2018-12-31 23:58:10.616信息9952---[main]j.LocalContainerEntityManagerFactoryBean:初始化了持久性单元“默认”的JPA EntityManagerFactory 2018-12-31 23:58:11.444错误9952---[main]o.s.b.web。嵌入的公猫TomcatStarter:启动Tomcat上下文时出错。例外:组织。springframework。豆。工厂不满意的费用例外。消息:创建名为“authenticationTokenFilterBean”的bean时出错:通过字段“tokenUtils”表示的未满足的依赖关系;嵌套的异常是org。springframework。豆。工厂NoSuchBeanDefinitionException:没有类型为“com”的合格bean。SBV运输。SBV运输。安全TokenUtils可用:至少需要1个符合autowire候选条件的bean。依赖项注释:{@org.springframework.beans.factory.annotation.Autowired(required=true)}2018-12-31 23:58:11.479 INFO 9952---[main]o.apache。卡塔琳娜。果心标准服务:停止服务[Tomcat]2018-12-31 23:58:11.495警告9952---[main]o.a.c.装载机。WebappClassLoaderBase:web应用程序[ROOT]似乎启动了一个名为[HikariPool-1 housekeeper]的线程,但未能停止该线程。这很可能会造成内存泄漏。线程的堆栈跟踪:java。base@11.0.1/jdk。内部的杂项。不安全的park(本机方法)java。base@11.0.1/爪哇。util。同时发生的锁。锁支架。Parknos(LockSupport.java:234)java。base@11.0.1/爪哇。util。同时发生的锁。AbstractQueuedSynchronizer$ConditionObject。Waitnanos(AbstractQueuedSynchronizer.java:2123)java。base@11.0.1/爪哇。util。同时发生的ScheduledThreadPoolExecutor$DelayedWorkQueue。以(ScheduledThreadPoolExecutor.java:1182)java为例。base@11.0.1/爪哇。util。同时发生的ScheduledThreadPoolExecutor$DelayedWorkQueue。以(ScheduledThreadPoolExecutor.java:899)java为例。base@11.0.1/爪哇。util。同时发生的线程池执行器。getTask(ThreadPoolExecutor.java:1054)java。base@11.0.1/爪哇。util。同时发生的线程池执行器。runWorker(ThreadPoolExecutor.java:1114)java。base@11.0.1/爪哇。util。同时发生的线程池执行器$Worker。运行(ThreadPoolExecutor.java:628)java。base@11.0.1/爪哇。朗。丝线。运行(Thread.java:834)警告:发生非法反射访问操作警告:组织非法反射访问。阿帕奇。卡塔琳娜。加载器。WebappClassLoaderBase(文件:/C:/Users/Danijela/.m2/repository/org/apache/tomcat/embed/tomcat-embed-core/9.0.12/tomcat-embed-core-9.0.12.jar)到java字段。木卫一。ObjectStreamClass$缓存。请考虑向ORG的维护者报告。阿帕奇。卡塔琳娜。加载器。WebappClassLoaderBase警告:使用--非法访问=警告以启用进一步非法反射访问操作的警告警告:所有非法访问操作将在未来版本2018-12-31 23:58:11.502警告9952---[main]ConfigServletWebServerApplicationContext:上下文初始化期间遇到异常-正在取消刷新尝试:org。springframework。上下文ApplicationContextException:无法启动web服务器;嵌套的html" target="_blank">异常是org。springframework。靴子网状物服务器WebServerException:无法启动嵌入式Tomcat 2018-12-31 23:58:11.502信息9952---[main]j.LocalContainerEntityManagerFactoryBean:关闭持久性单元“默认”的JPA EntityManagerFactory 2018-12-31 23:58:11.502信息9952---[main]com。扎克塞尔。希卡里。HikariDataSource:HikariPool-1-已启动关机。。。2018-12-31 23:58:11.517信息9952---[main]com。扎克塞尔。希卡里。HikariDataSource:HikariPool-1-关闭完成。2018-12-31 23:58:11.533信息9952---[main]条件评估报告日志监听器:

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-12-31 23:58:11.845 ERROR 9952 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

   Field tokenUtils in      com.sbvtransport.sbvtransport.security.AuthenticationTokenFilter required a bean of type 'com.sbvtransport.sbvtransport.security.TokenUtils' 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 'com.sbvtransport.sbvtransport.security.TokenUtils' in your configuration.    
package com.sbvtransport.sbvtransport.security;

这些是我的安全类:

AuthenticationTokenFilter

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

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.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;

public class AuthenticationTokenFilter  extends UsernamePasswordAuthenticationFilter{

@Autowired
TokenUtils tokenUtils;

@Autowired
private UserDetailsService userDetailsService;

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String authToken = httpRequest.getHeader("Authorization");
    String username = tokenUtils.getUsernameFromToken(authToken);

    if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
        UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
        if (tokenUtils.validateToken(authToken, userDetails)) {
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                    userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }

    chain.doFilter(request, response);
}

}

TokenUtils

package com.sbvtransport.sbvtransport.security;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class TokenUtils {

@Value("SuperSecreat")
private String secret;

@Value("86400") // 24 hours(in seconds)
private Long expiration;

public String getUsernameFromToken(String token) {
    String username;
    try {
        Claims claims = this.getClaimsFromToken(token);
        username = claims.getSubject();
    } catch (Exception e) {
        username = null;
    }
    return username;
}

private Claims getClaimsFromToken(String token) {
    Claims claims;
    try {
        claims = Jwts.parser().setSigningKey(this.secret).parseClaimsJws(token).getBody();
    } catch (Exception e) {
        claims = null;
    }
    return claims;
}

public Date getExpirationDateFromToken(String token) {
    Date expirationDate;
    try {
        final Claims claims = this.getClaimsFromToken(token);
        expirationDate = claims.getExpiration();
    } catch (Exception e) {
        expirationDate = null;
    }
    return expirationDate;
}

private boolean isTokenExpired(String token) {
    final Date expirationDate = this.getExpirationDateFromToken(token);
    return expirationDate.before(new Date(System.currentTimeMillis()));
}

public boolean validateToken(String token, UserDetails userDetails) {
    final String username = getUsernameFromToken(token);
    return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
}

public String generateToken(UserDetails userDetails) {
    Map<String, Object> claims = new HashMap<String, Object>();
    claims.put("sub", userDetails.getUsername());
    claims.put("created", new Date(System.currentTimeMillis()));
    return Jwts.builder().setClaims(claims).setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
            .signWith(SignatureAlgorithm.HS512, secret).compact();
}

}

证券配置

package com.sbvtransport.sbvtransport.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
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.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@SpringBootApplication
@Configuration
@EnableWebSecurity
@EnableAutoConfiguration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;

@Autowired
public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {

    authenticationManagerBuilder.userDetailsService(this.userDetailsService).passwordEncoder(passwordEncoder());
}

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

@Bean
public AuthenticationTokenFilter authenticationTokenFilterBean() throws Exception {
    AuthenticationTokenFilter authenticationTokenFilter = new AuthenticationTokenFilter();
    authenticationTokenFilter.setAuthenticationManager(authenticationManagerBean());
    return authenticationTokenFilter;
}

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .authorizeRequests().antMatchers("").permitAll();

    httpSecurity.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
}

  }

AuthenticationTokenFilter内部的自动连接TokenUtils似乎有问题,但我也可能错了。

我希望我的问题足够清楚,如果我能做些什么来改进它,请提出建议。

共有1个答案

田博易
2023-03-14

错误:错误消息明确表示未找到TokenUtilsbean

'com。SBV运输。SBV运输。安全找不到的TokenUtils。

您在TokenUtils上缺少@Component,使用@Component声明类使组件扫描在应用程序上下文中创建该类的单例bean

@Component
public class TokenUtils {

AuthenticationTokenFilter

@Configuration
public class AuthenticationTokenFilter  extends UsernamePasswordAuthenticationFilter{

@SpringBootApplication在声明的包中启用组件扫描

启用Spring Boot的自动配置机制

@ComponentScan:在应用程序所在的包上启用@Component扫描(请参阅最佳实践)

@配置:允许在上下文中注册额外的bean或导入其他配置类

@SpringBootApplication注释相当于使用@Configuration、@EnableAutoConfiguration和@ComponentScan及其默认属性,

 类似资料: