Integration test for API that has @Secured

Viewed 29

I have a spring REST API that is secured by spring security and Keycloak, and I am using keycloak testcontainers for the integration test. I can add a user to keycloak and get a token to use while testing most of the APIs.

The question is, If I have an API that is annotated with @Secured to limit its access to only users with a specific role, how to assign that role to the created user or mock this role to run the integration test

1 Answers

You may simply want to add the role to the user, e.g. like this:

RoleRepresentation role = new RoleRepresentation("rolename", "role desc", false);
KeycloakContainer container = new KeycloakContainer();        
RealmResource realm = container.getKeycloakAdminClient().realm("realm");
realm.roles().create(role);
realm
  .users()
  .get("user")
  .roles()
  .realmLevel()
  .add(List.of(role));
Related