使用名称authenticationTokenFilterBean创建bean时出错:通过字段tokenUtils

时间:2018-12-31 23:45:38

标签: java spring-boot spring-security jwt

我想在我的项目中实现Spring Security。但是无论尝试如何,我都会遇到相同的错误。

我创建了必要的类(TokenUtilsAuthenticationTokenFilterSpringConfiguration)。它们在同一个程序包下,但是出现以下错误。

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

  

2018-12-31 23:58:10.616信息9952 --- [主] j.LocalContainerEntityManagerFactoryBean:持久性单元“默认”的已初始化JPA EntityManagerFactory       2018-12-31 23:58:11.444错误9952 --- [main] o.s.b.web.embedded.tomcat.TomcatStarter:启动Tomcat上下文时出错。异常:org.springframework.beans.factory.UnsatisfiedDependencyException。消息:创建名称为“ authenticationTokenFilterBean”的bean时出错:通过字段“ tokenUtils”表示的不满意的依赖关系;嵌套异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:没有类型为'com.sbvtransport.sbvtransport.security.TokenUtils'的合格Bean:预计至少有1个有资格作为自动装配候选的Bean。依赖项注释:{@ org.springframework.beans.factory.annotation.Autowired(required = true)}       2018-12-31 23:58:11.479信息9952 --- [main] o.apache.catalina.core.StandardService:停止服务[Tomcat]       2018-12-31 23:58:11.495 WARN 9952 --- [main] o.a.c.loader.WebappClassLoaderBase:Web应用程序[ROOT]似乎已启动名为[HikariPool-1管家]的线程,但未能停止它。这很可能造成内存泄漏。线程的堆栈跟踪:        java.base@11.0.1/jdk.internal.misc.Unsafe.park(本机方法)         java.base@11.0.1/java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:234)       java.base@11.0.1/java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:2123)        java.base@11.0.1/java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:1182)        java.base@11.0.1/java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:899)        java.base@11.0.1/java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1054)        java.base@11.0.1/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1114)        java.base@11.0.1/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)        java.base@11.0.1/java.lang.Thread.run(Thread.java:834)       警告:发生了非法的反射访问操作       警告:org.apache.catalina.loader.WebappClassLoaderBase(文件:/ C:/Users/Danijela/.m2/repository/org/apache/tomcat/embed/tomcat-embed-core/9.0.12/tomcat的非法反射访问-embed-core-9.0.12.jar)到字段java.io.ObjectStreamClass $ Caches.localDescs       警告:请考虑将此报告给org.apache.catalina.loader.WebappClassLoaderBase的维护者       警告:使用--illegal-access = warn启用有关进一步非法反射访问操作的警告       警告:所有非法访问操作将在以后的版本中被拒绝       2018-12-31 23:58:11.502 WARN 9952 --- [main] ConfigServletWebServerApplicationContext:上下文初始化期间遇到异常-取消刷新尝试:org.springframework.context.ApplicationContextException:无法启动Web服务器;无法启动Web服务器。嵌套的异常是org.springframework.boot.web.server.WebServerException:无法启动嵌入式Tomcat       2018-12-31 23:58:11.502信息9952 --- [main] j.LocalContainerEntityManagerFactoryBean:关闭持久性单元'default'的JPA EntityManagerFactory       2018-12-31 23:58:11.502信息9952 --- [main] com.zaxxer.hikari.HikariDataSource:HikariPool-1-关闭启动...       2018-12-31 23:58:11.517信息9952 --- [main] com.zaxxer.hikari.HikariDataSource:HikariPool-1-关闭已完成。       2018-12-31 23:58:11.533信息9952 --- [[main] ConditionEvaluationReportLoggingListener:

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 个答案:

答案 0 :(得分:1)

错误:错误消息明确指出未找到TokenUtils bean

  找不到

'com.sbvtransport.sbvtransport.security.TokenUtils'。

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

@Component
public class TokenUtils {

还有@Configuration上的AuthenticationTokenFilter

@Configuration
public class AuthenticationTokenFilter  extends UsernamePasswordAuthenticationFilter{

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

  

@EnableAutoConfiguration:启用Spring Boot的自动配置机制

     

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

     

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

     

@SpringBootApplication注释等效于使用@ Configuration,@ EnableAutoConfiguration和@ComponentScan及其默认属性,