gpt4 book ai didi

java - 无法在 Spring 中自动连接我的身份验证过滤器中的服务

转载 作者:IT老高 更新时间:2023-10-28 13:03:27 25 4
gpt4 key购买 nike

我正在尝试通过 token 对用户进行身份验证,但是当我尝试在 AuthenticationTokenProcessingFilter 内自动连接我的服务时,我得到空指针异常。 因为 autowired 服务为空,我该如何解决这个问题?

我的 AuthenticationTokenProcessingFilter

@ComponentScan(basePackages = {"com.marketplace"})
public class AuthenticationTokenProcessingFilter extends GenericFilterBean {

@Autowired
@Qualifier("myServices")
private MyServices service;

public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
@SuppressWarnings("unchecked")
Map<String, String[]> parms = request.getParameterMap();

if (parms.containsKey("token")) {
try {
String strToken = parms.get("token")[0]; // grab the first "token" parameter

User user = service.getUserByToken(strToken);
System.out.println("Token: " + strToken);

DateTime dt = new DateTime();
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime createdDate = fmt.parseDateTime(strToken);
Minutes mins = Minutes.minutesBetween(createdDate, dt);


if (user != null && mins.getMinutes() <= 30) {
System.out.println("valid token found");

List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getEmailId(), user.getPassword());
token.setDetails(new WebAuthenticationDetails((HttpServletRequest) request));
Authentication authentication = new UsernamePasswordAuthenticationToken(user.getEmailId(), user.getPassword(), authorities); //this.authenticationProvider.authenticate(token);

SecurityContextHolder.getContext().setAuthentication(authentication);
}else{
System.out.println("invalid token");
}
} catch(Exception e) {
e.printStackTrace();
}
} else {
System.out.println("no token found");
}
// continue thru the filter chain
chain.doFilter(request, response);
}
}

我尝试在 AppConfig

中添加以下内容
@Bean(name="myServices")
public MyServices stockService() {
return new MyServiceImpl();
}

我的 AppConfig 注释是

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.marketplace")
public class AppConfig extends WebMvcConfigurerAdapter {

最佳答案

您不能从开箱即用的过滤器中使用依赖注入(inject)。尽管您使用的是 GenericFilterBean,但您的 Servlet 过滤器不是由 spring 管理的。正如 javadocs 所指出的

This generic filter base class has no dependency on the Spring org.springframework.context.ApplicationContext concept. Filters usually don't load their own context but rather access service beans from the Spring root application context, accessible via the filter's ServletContext (see org.springframework.web.context.support.WebApplicationContextUtils).

简单地说,我们不能期望 spring 注入(inject)服务,但我们可以在第一次调用时懒惰地设置它。例如

public class AuthenticationTokenProcessingFilter extends GenericFilterBean {
private MyServices service;
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if(service==null){
ServletContext servletContext = request.getServletContext();
WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
service = webApplicationContext.getBean(MyServices.class);
}
your code ...
}

}

关于java - 无法在 Spring 中自动连接我的身份验证过滤器中的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32494398/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com