我想在我的项目中实现Spring Security性。但不管我怎么做,我总是会犯同样的错误。
我创建了必要的类(TokenUtils
,AuthentiationTokenFilter
,SpringConfiguration
)。它们在同一个包下,但我得到以下错误。
这是发生问题的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似乎有问题,但我也可能错了。
我希望我的问题足够清楚,如果我能做些什么来改进它,请提出建议。
错误:错误消息明确表示未找到TokenUtils
bean
'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及其默认属性,
我查了一些类似的问题,但这些答案帮不了我。 错误 组织。springframework。豆。工厂未满足的依赖项异常:创建名为“accountController”的bean时出错:未满足的依赖项通过字段“accountService”表示;嵌套的异常是org。springframework。豆。工厂NoSuchBeanDefinitionException:没有类型为“com”的合格bean。服务
我有以下代码和结构。我得到以下错误,这是很长的错误消息。 创建名称为'departmentController'的bean时出错:通过字段'departmentService'表示的不满意的依赖项;嵌套异常org.springframework.beans.factory.不满意依赖异常: 实体类 存储库接口 服务等级 控制器类 主课 项目结构 完整错误堆栈跟踪:
当我试图进入主页时,我有以下错误 在我的UserController中,我有以下代码 我的用户服务 我的UserServiceImpl 我的假设 web.xml 我的servlet上下文 根上下文为空。 我不知道哪里是可能的错误原因,我试图找到不同的选项,但如果我使用DAO模式,我会收到相同的错误,所以我想知道哪个是问题来解决它。 该项目的配置使用xml,但我认为解决这种情况并不重要。 问候!
我是Spring和hibernate框架的新手,我已经给出了依赖项上的注释,但是我不知道为什么会出现这个错误。 创建名为“customerController”的bean时出错:通过字段“customerDAO”表示的未满足的依赖关系;嵌套的异常是org。springframework。豆。工厂未满足的依赖项异常:创建名为“customerDAOImpl”的bean时出错:未满足的依赖项通过字段“
以下是跟踪: org.springframework.beans.factory.未满足的DependencyException:创建名称为'testController'的bean时出错:通过字段'testDAO'表示的依赖项未满足;嵌套异常org.springframework.beans.factory.BeanCreationException:创建名称为'testDAO'的bean时出错
我是sping-mvc的新手。我试图找到使用sping-mvc、hiberNate、mysql和jsf开发测试项目的好教程。最后我创建了示例项目。 我的第一个问题是, 就是这个Spring-mvc结构 但不幸的是,上面显示的是错误。 应用程序上下文。xml 人脸配置。xml web.xml 个人类 PersonDAOImpl类 个人服务Impl类 ManagedBeanClass类 错误是, 请给