manju manju - 1 month ago 11
Java Question

How to restrict access in Api's based on Roles with Jhipster

I am working on a jhipster project.If i have three roles say A,B and C and i want to limit access of an particular API to only A & B.How can i manage the security of Api in such a way that other user roles wont able to access it?

Answer

Depending on which type of JHipster application you are using, the file you need is called WebSecurityConfiguration (for monoliths) or MicroserviceSecurityConfiguration (for microservice appplications).

There, in the configure method you will find the default line

.antMatchers("/api/**").authenticated()

which means, you only need to be authenticated to get access to any url behind the /api prefix.

To apply some custom role based rule, you add some

.antMatchers("/api/my-url/").hasRole("A")

before the mentioned line, or similar methods, as hasAnyRole, hasAuthority, or access(), for more complex statements

As an alternative, you may use the @Secured or @PreAuthorize annotations on concrete methods, to have more fine grained access control