Please Don't Close the question without understanding the problem. There is no similar scenario found in existing questions. If you think there is any, please comment with the link. Please don't close. Let others answer it
I wrote a utility class JwtUtils.java, annotated it as a component, and injected it into another class, CustomFilter.java, which is also annotated as a component. CustomFilter implements a Filter interface. After injecting I cannot access methods inside the util class. It's throwing NullPointerException.
Jakarta Filter is executing before the request controller for JWT Authentication.
JwtUtils class:
@Component
public class JwtUtils {
@Value("${JWT_SECRET}")
public String SECRET_KEY;
public String getUsernameFromToken(String token) {
Jws<Claims> claims = Jwts.parser()
.setSigningKey(SECRET_KEY)
.parseClaimsJws(token);
Object claimsBody = claims.getBody();
String jsonString = new Gson().toJson(claimsBody);
JSONObject obj = new JSONObject(jsonString);
return obj.getString("username");
}
public boolean validateToken(String token) {
try {
Jwts.parser()
.setSigningKey(SECRET_KEY)
.parseClaimsJws(token);
return true;
} catch (Exception e) {
return false;
}
}
public Authentication getAuthentication(String token) {
Authentication auth = new Authentication();
auth.setUsername(getUsernameFromToken(token));
System.out.println(auth.toString());
return auth;
}
}
CustomFilter class:
@Component
public class CustomFilter implements Filter {
@Autowired
JwtUtils util;
public CustomFilter() {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String token = extractTokenFromHeader(request.getHeader("Authorization"));
if (util.validateToken(token)) {
request.setAttribute("username", util.getUsernameFromToken(token));
filterChain.doFilter(request, response);
} else {
ErrorDetails errorDetails = new ErrorDetails(new Date(), "Access Unauthorized",
"Authorization Token is Missing/Invalid/Expired", 401);
response.setStatus(401);
response.setContentType("application/json");
response.getWriter().write(convertObjectToJson(errorDetails));
}
}
private String extractTokenFromHeader(String header) {
if (StringUtils.hasText(header) && header.startsWith("Bearer ")) {
return header.substring(7);
}
return null;
}
public String convertObjectToJson(Object object) throws JsonProcessingException {
if (object == null) {
return null;
}
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(object);
}
}
The Exception:
java.lang.NullPointerException: Cannot invoke "com.fp.common.util.JwtUtils.validateToken(String)" because "this.util" is null at com.fp.common.validation.CustomFilter.doFilter(CustomFilter.java:34)
I want to access util methods from the Jakarta custom filter class through the spring IoC container. Please leave a suggestion if this issue is in your scope