admin管理员组

文章数量:1399936

I am trying to implement JWT authentication to one particular endpoint. I have SAML authentication already in place.

  • Spring Boot Version - 2.7.18
  • com.auth0 (java-jwt) version - 4.4.0
  • com.auth0 (jwks-rsa) version - 0.22.1

My Spring Security almost looks like the following one SpringSecurityConfig.java

Differences in Spring Security is like below,

SpringSecurityConfig.java

@Bean
public FilterChainProxy samlAuthFilter(HttpSecurity http) throws Exception {
    List<SecurityFilterChain> chains = new ArrayList<>();
    chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/**"), //SecurityContextHolderAwareRequestFilter as a bean);
    chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/**"), //SecurityContextHolderFilter as a bean);
    chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SSO/**"),
        //SAML Processing Filter as a bean));
    chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/metadata/**"),
        //Metadata Display Filter as a bean));
    chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SSOHoK/**"),
        //SAMLWebSSOHoKProcessingFilter as a bean with authentication success and failure handler));
    chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/employees"),
        //JWTFilter));

    return new FilterChainProxy(chains);
}

//Security Filter Chain configure method
@Bean
protected SecurityFilterChain configure(HttpSecurity http) throws Exception {
   http.csrf.disable();
   http.addFilterBefore(samlAuthFilter(), BasicAuthenticationFilter.class);
   //setting CSP and Referrer Policy to http headers.
   return http.build();
}

My JWT authentication prototype is as follows (using - com.auth0 library),

JWTTokenAuth.java

//All necessary import statements
public class JWTTokenAuth implements Filter {

   JwkProvider provider;

   @Autowired
   ApplicationContext applicationContext;

   public JWTTokenAuth() throws MalformedURLException {
      provider = new JwkProviderBuilder(new URL(/*keyProvider URL*/)).build();
   }

   @Override
   public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

       if(SecurityContextHolder.getContext().getAuthentication() == null &&
            ((HttpServletRequest) request).getHeader("Authorization") != null) {

            logger.info("Inside token validation");
            String tokenFromReq = ((HttpServletRequest) request).getHeader("Authorization").subString(7);
            
            DecodedJWT decodedToken = JWT.decode(tokenFromReq);

            try {

                Jwk jwk = jwkProvider.get(decodedToken.getKey);

                Algorithm algorithm = Algorithm.RSA256((RSAPublicKey) jwk.getPublicKey(), null);

                JWTVerifier verifier = JWT.require(algorithm).withIssuer(/*issuer here*/).withAudience(/*audience*/).build();

                verifier.verify(decodedToken);

                logger.info("Token Validated");

                String username = decodedToken.getClaim("Username").asString();

                UserDetails userDetails = applicationContext.getBean(AppUsersDetails.class).loadUserByUsername(username);

                UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authToken.setDetails(new WebAuthenticationDetailsSource.buildDetails(((HttpServletRequest) request)));

                SecurityContextHolder.getContext().setAuthentication(authToken);

            } catch (JwkException e) {
                e.printStackTrace();
            } catch(Exception e) {
                e.printStackTrace();
            }
            chain.doFilter(request,response);
       }
   }
}

After the above implementation and running the application in my local, I can see the response code as 200 when sending the valid token but I cannot see the response being sent from the endpoint.

If the endpoint is invoked then the response would be a list of all employees. But I don't see that data in the response body and it is empty. Also, I don't see any loggers getting printed in the logs or console which were added in the JWTTokenAuth.java.

Also, when these changes are deployed in the server the application homepage is not getting loaded and displayed blank. No errors or exceptions are getting printed in the logs or console.

Note: - I don't have any issues with normal SAML authentication previously. Also, please consider there is no compilation or runtime issues.

what am I missing here?

本文标签: Implement JWT authentication using comauth0 library in Spring Boot Using JavaStack Overflow