无法在Spring中的身份验证过滤器中自动装入服务 [英] Unable to autowire the service inside my authentication filter in Spring
问题描述
我试图通过令牌来验证用户,但是当我尝试在 AuthenticationTokenProcessingFilter
中自动连线我的服务时,我得到空指针异常。 因为autowired服务为空,我该如何解决这个问题?
My AuthenticationTokenProcessingFilter
class
@ComponentScan(basePackages = {com.marketplace})
public class AuthenticationTokenProcessingFilter extends GenericFilterBean {
@Autowired
@Qualifier(myServices)
私人MyServices服务;
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]; //获取第一个token参数
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); (用户!= null&& mins.getMinutes()<= 30){
System.out.println(找到有效的令牌);
列表<授权授权> authority = new ArrayList< GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority(ROLE_ADMIN));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getEmailId(),user.getPassword());
token.setDetails(新的WebAuthenticationDetails((HttpServletRequest)请求));
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);
}
//继续通过过滤链
chain.doFilter(request,response);
$ / code>
我试着在我的 AppConfig
@Bean(name =myServices)
MyServices stockService ){
return new MyServiceImpl();
}
我的AppConfig批注是
@Configuration
@EnableWebMvc
@ComponentScan(basePackages =com.marketplace)
公共类AppConfig扩展WebMvcConfigurerAdapter {
我只是通过添加
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
我不确定为什么我们应该这样做,即使当我尝试添加显式限定符。现在代码看起来像
public void doFilter(ServletRequest请求,ServletResponse响应,
FilterChain链)throws IOException, ServletException {
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
@SuppressWarnings(unchecked)
Map< String,String []> parms = request.getParameterMap();
if(parms.containsKey(token)){
I am trying to authenticate user by token, But when i try to auto wire one my services inside the AuthenticationTokenProcessingFilter
i get null pointer exception. because autowired service is null , how can i fix this issue ?
My AuthenticationTokenProcessingFilter
class
@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);
}
}
I Tried adding follwing in my AppConfig
@Bean(name="myServices")
public MyServices stockService() {
return new MyServiceImpl();
}
My AppConfig Annotations are
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.marketplace")
public class AppConfig extends WebMvcConfigurerAdapter {
I just made it work by adding
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
I am unsure why we should do this even when i tried adding explicit qualifier. and now the code looks like
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
@SuppressWarnings("unchecked")
Map<String, String[]> parms = request.getParameterMap();
if (parms.containsKey("token")) {
这篇关于无法在Spring中的身份验证过滤器中自动装入服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!