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 {
You cannot use dependency injection from a filter out of the box. Although you are using GenericFilterBean your Servlet Filter is not managed by spring. As noted by the javadocs
In plain English we cannot expect spring to inject the service, but we can lazy set it on the first call. E.g.
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
It's an old enough question, but I'll add my answer for those who like me google this issue.
You must inherit your filter from
GenericFilterBean
and mark it as a Spring@Component
And then register it in Spring context:
This properly autowires your components in the filter.
If your filter class extends GenericFilterBean you can get a reference to a bean in your app context this way:
And here is less explicit way for those who doesn't like hardcoding bean names or need to inject more than one bean reference into the filter:
I am late to the party but this solution worked for me.
Add a ContextLoaderListener in web.xml. applicationContext can have dependency beans.
Then add in MyFilter SpringBeanAutowiringSupport processInjectionBasedOnServletContext which will add the webapplicationcontext into the filter which will add all the dependencies.
}
You can configure your bean filter and pass as a parameter whatever you need. I know out of Spring context where the filter it is, you cannot get the dependency injection that the auto-scan of spring does. But not 100% sure if there´s a fancy annotation that you can put in your filter to do some magic stuff
and then inject bean in the spring.xml