Integration tests for secure endpoint in quarkus

51 views Asked by At

I have a quarkus application, created a custom annotation with interceptor to secure endpoints.

// Custom annotation

@InterceptorBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.TYPE })
public @interface PermitRole {
}

//Interceptor binded with annotation

@Interceptor
@PermitRole
public class LiveTraderRolesAuthorization { 
   @Inject
   HttpHeaders headers;

   @Inject
   JWTTokenParser jwtTokenParser;

   @AroundInvoke
   public Object authorize(InvocationContext context) throws Exception {
       // here i have logic to ***parse Authorization header JWT token using nimbus-jose*** and setting authorized flag. 
      if(authorized) {
        return context.proceed();
      }
    }
}

// my controller method

    @GET
    @PermitRole
    @Produces(MediaType.APPLICATION_JSON)
    public RestResponse<MResponse> getSome(@PathParam("Id") String Id) {
        //logic
    }

Question : Now integration tests for my controller is failing after adding the custom annotation. One way to solve this is I can mock JWTTokenParser in tests and return the mocked claims, But is there a better way to write integration tests for interceptor and controller together so that whole interceptor and token parsing logic can be tested like real application. Really appreciate any help !!

NOTE: I am using nimbus-jose-jwt library to parse the Jwt token, not anything specific to quarkus.

1

There are 1 answers

3
Serkan On

In your application.properties define an apart JWT for your tests:

%test.smallrye.jwt.sign.key.location=dummy-private-key.pem
%test.mp.jwt.verify.publickey.location=dummy-public-key.pem 
%test.mp.jwt.verify.issuer=test-issuer

And now you can use this token in your test:

String jwt = Jwt.sign("test-claims.json");

@Test
void authentication() {
   given().oauth2().bearer(this.jwt)
   .when() //etc
}

Note that your roles in the claims should be called “groups”, that’s what Quarkus expects. There is also a configuration to change this.

The other way to test, is to include quarkus-security-test dependency in your pom.xml. Read the “Test” section of the documentation for this: https://quarkus.io/guides/security-jwt