- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想在我的项目中实现Spring Security。但无论我尝试什么,我都会遇到同样的错误。
我创建了必要的类(TokenUtils
、AuthenticationTokenFilter
、SpringConfiguration
)。它们位于同一包下,但我收到以下错误。
这是我的堆栈跟踪
发生问题的部分
2018-12-31 23:58:10.616 INFO 9952 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default' 2018-12-31 23:58:11.444 ERROR 9952 --- [ main] o.s.b.web.embedded.tomcat.TomcatStarter : Error starting Tomcat context. Exception: org.springframework.beans.factory.UnsatisfiedDependencyException. Message: Error creating bean with name 'authenticationTokenFilterBean': Unsatisfied dependency expressed through field 'tokenUtils'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.sbvtransport.sbvtransport.security.TokenUtils' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 2018-12-31 23:58:11.479 INFO 9952 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat] 2018-12-31 23:58:11.495 WARN 9952 --- [ main] o.a.c.loader.WebappClassLoaderBase : The web application [ROOT] appears to have started a thread named [HikariPool-1 housekeeper] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread: java.base@11.0.1/jdk.internal.misc.Unsafe.park(Native Method) 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) WARNING: An illegal reflective access operation has occurred WARNING: Illegal reflective access by org.apache.catalina.loader.WebappClassLoaderBase (file:/C:/Users/Danijela/.m2/repository/org/apache/tomcat/embed/tomcat-embed-core/9.0.12/tomcat-embed-core-9.0.12.jar) to field java.io.ObjectStreamClass$Caches.localDescs WARNING: Please consider reporting this to the maintainers of org.apache.catalina.loader.WebappClassLoaderBase WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations WARNING: All illegal access operations will be denied in a future release 2018-12-31 23:58:11.502 WARN 9952 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat 2018-12-31 23:58:11.502 INFO 9952 --- [ main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default' 2018-12-31 23:58:11.502 INFO 9952 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated... 2018-12-31 23:58:11.517 INFO 9952 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed. 2018-12-31 23:58:11.533 INFO 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;
这些是我的安全类(class):
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 内的 Autowiring TokenUtils 有问题,但我也可能是错的。
我希望我的问题足够清楚,如果我可以做任何改进,请提出建议。
最佳答案
错误:错误消息清楚地表明未找到TokenUtils
bean
'com.sbvtransport.sbvtransport.security.TokenUtils' that could not be found.
您在 TokenUtils 上缺少 @Component
,使用 @Component
声明类会使组件扫描在应用程序上下文中创建此类的单例 bean
@Component
public class TokenUtils {
以及AuthenticationTokenFilter
上的@Configuration
@Configuration
public class AuthenticationTokenFilter extends UsernamePasswordAuthenticationFilter{
@SpringBootApplication 在其声明的包中启用组件扫描
@EnableAutoConfiguration: enable Spring Boot’s auto-configuration mechanism
@ComponentScan: enable @Component scan on the package where the application is located (see the best practices)
@Configuration: allow to register extra beans in the context or import additional configuration classes
The @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration, and @ComponentScan with their default attributes,
关于java - 创建名称为authenticationTokenFilterBean 的bean 时出错 : Unsatisfied dependency expressed through field tokenUtils,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53992171/
我的 Web 应用程序在后端使用 Node.js 和 Express。当违反内容安全策略 (CSP) 时,报告 URI 报告空对象。我的后台代码如下: app.use(bodyParser.urlen
在服务器端提供静态服务的方式在 Express 中似乎非常简单: To serve static files such as images, CSS files, and JavaScript fil
var express = require('express'); var app = express(); 这就是我们创建快速应用程序的方式。但是这个'express()'是什么?它是方法还是构造函
我在尝试安装时收到以下错误 express : npm ERR! code ERR_OSSL_PEM_NO_START_LINE npm ERR! errno ERR_OSSL_PEM_NO_STAR
如 express 所述routing guide和 this answer ,我们可以创建“迷你应用程序”并从主应用程序使用它。但是我看到一段代码,它在模块中使用 app 而不是 router ap
我正在写一个 NestJS应用。现在我想安装 Express中间件 express-openapi-validator . 但是,我无法让它工作。有一个 description for how to
我看过很多类似的帖子,似乎我声明的 var1 似乎需要在其他地方传递,但我似乎无法弄清楚。 public Expression> CreateEqualNameExpression(string ma
Express(或 Connect 的)bodyParser 中间件被标记为已弃用,建议用户改用: app.use(connect.urlencoded()) app.use(connect.json
我只是想知道这种看似尴尬的配置的原因是什么(来自 Getting Started w/ Apollo Server ), const server = new ApolloServer({ //
我正在尝试在表单组中写入表单控件特定的验证错误消息。我在网上找到了几个教程和示例 ( such as this one ),概述了一个看似简单的 *ngIf div,如果在控件上检测到错误,则显示错误
我有一个简单的 Express 应用程序,托管在 AWS 上,使用无服务器框架。 我正在使用 serverless-http 包装 express 应用程序以部署到 AWS lambda 函数,并使用
我最近在 mozilla 教程的帮助下安装了 node 和 express。我正在安装应用程序生成器的下一步,但是当我运行时 npm install express-generator -g 在我的终
我遇到过两种不同的方式来定义 express、use() 中间件,我想知道它们之间是否有任何区别,或者它是否只是语法糖? 一个 const app = express(); app.use(cors(
我试图让我的 Jade 模板编写一个相对于当前 URL 的超链接 ( )。 例如,我的 View 是从 http://localhost/cats 调用的它看起来像这样: extends layou
检查 Express 文档我在下面看到了这种解决方案: app.all('/*', function(req, res) { console.log('Intercepting request
我似乎无法弄清楚如何包含多个模型。 我有三个模型。Tabs, Servers, and PointsTabs hasMany ServerServers belongsTo Tabs and hasM
我已使用Web PI安装IIS Express。在托盘中,没有IIS Express图标。如何在不使用命令行的情况下启动IIS Express?我希望IIS永久运行,因此没有命令行。 最佳答案 参见R
我不想在我的网站上使用 Jade 或 EJS。如何在不默认使用 Jade 模板的情况下创建快速站点?谢谢 最佳答案 如果您想要的是直接为静态 html 文件提供缓存资源的可能性,同时仍然能够点击“/”
Express是否支持HTTP动词“PATCH”,例如: app.patch("/api/resource", function(req, res){ ... }); 我检查了文档,对我来说似乎还不清
我正在快速服务器中运行 vue SPA。问题是当使用历史模式并刷新页面时,我得到一个 404 not found 异常。我尝试使用 connect-history-api-fallback 但不起作用
我是一名优秀的程序员,十分优秀!