In my application, I just want to authenticate two access token, one is in my 'Authorization barer header' and other is from a custom header. I just implemented a custom authenticator/filter for the same but while running it failed due to a null pointer as the dependency injection failed.
code snippet is given below
private XOauth2Authenticationfilter customAuthenticator=new XOauth2Authenticationfilter();
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId(resourceId);
resources.authenticationEntryPoint(authenticationEntryPoint);
resources.authenticationManager(customAuthenticator);
//super.configure(resources);
}
@Override
public void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf().disable();
httpSecurity.authorizeRequests().anyRequest().authenticated().and().addFilterAfter(customAuthenticator,SecurityContextPersistenceFilter.class);
httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
//super.configure(httpSecurity);
}
My custom authenticator do filter() is given below
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
List<Authentication> authList = tokenExtractor.extract((HttpServletRequest) req);
if(authList!=null)
{
for (Authentication authenticate : authList) {
authenticate(authenticate,(HttpServletRequest) req);
}
}
chain.doFilter(req, res);
}
private void authenticate(Authentication authentication,HttpServletRequest request ) {
final boolean debug = logger.isDebugEnabled();
if (authentication == null) {
if (stateless && isAuthenticated()) {
if (debug) {
logger.debug("Clearing security context.");
}
SecurityContextHolder.clearContext();
}
if (debug) {
logger.debug("No token in request, will continue chain.");
}
}
else {
request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, authentication.getPrincipal());
if (authentication instanceof AbstractAuthenticationToken) {
AbstractAuthenticationToken needsDetails = (AbstractAuthenticationToken) authentication;
needsDetails.setDetails(authenticationDetailsSource.buildDetails(request));
}
Authentication authResult = authenticationManager.authenticate(authentication);
if (debug) {
logger.debug("Authentication success: " + authResult);
}
eventPublisher.publishAuthenticationSuccess(authResult);
SecurityContextHolder.getContext().setAuthentication(authResult);
}
}
But while executing I am getting a null pointer at
Authentication authResult = authenticationManager.authenticate(authentication);
What I could do to implement a custom authenticator?