How to validate JWT by passing to custom auth server in spring boot

Viewed 23

I have an Auth server which will do authentication and return a JWT. It does the JWT validation as well.

I have another service called B and before any API call it lands, there should be a filter which extract the JWT and pass to Auth server to do the JWT validation and role base authorization.

What Im doing is as follows.

 @Autowired
    private RestTemplate restTemplate;


    @Override
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        URI myURI = null;
        String token  = req.getHeader("AUTHORIZATION");
        token = token.trim();
        try {
            myURI = new URI("http://localhost:8092/auth-user/validate");
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
        HttpHeaders headers = new HttpHeaders();
        tokenValidateRequest.setToken(token);
        HttpEntity<TokenValidateRequest> requestEntity =
                new HttpEntity<>(tokenValidateRequest, headers);
        log.info("Request intercepted: " + req.getHeader("AUTHORIZATION"));
        restTemplate.exchange(myURI, HttpMethod.POST, requestEntity,
                String.class);

    }

When I debug the application, Null pointer exception thrown from Rest Template.

Am I doing the correct thing? If yes why rest template throwing that?

Thanks.

1 Answers

I did a research on this. there are two ways of achieving this.

  • By writing filter in other services to validate JWT.

  • By doing a REST call.

    public class RequestValidationFilter extends OncePerRequestFilter {

     @Override
     protected void doFilterInternal(HttpServletRequest request,
                                     HttpServletResponse response,
                                     FilterChain filterChain) throws ServletException, IOException {
    
         String token  = request.getHeader("AUTHORIZATION");
         if(!token.isEmpty()){
             try {
                 Claims claims = Jwts.parser()
                         .setSigningKey("superdupersecretkey")
                         .parseClaimsJws(token).getBody();
                 String username = String.valueOf(claims.get("username"));
                 String authorities = (String) claims.get("authorities");
                 String sessionId = (String) claims.get("sessionId");
                     Authentication auth = new UsernamePasswordAuthenticationToken(username,null,
                             AuthorityUtils.commaSeparatedStringToAuthorityList(authorities));
                     SecurityContextHolder.getContext().setAuthentication(auth);
    
    
             }catch (Exception e) {
                 throw new BadCredentialsException("Invalid Token received!");
             }
         }
         filterChain.doFilter(request, response);
     }
    

    }

Related