Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

271
Views
How @PreAuthorize checks the roles?

I have several REST APIs.

I would like to put Security on top of all of them, in order to allowed the functionalities only for certain roles.

I put the @EnableGlobalMethodSecurity(prePostEnabled = true) in the configuration class.

I have a DB with a table which stores the roles.

@RequestMapping(path = "/error", method = RequestMethod.GET)
@PreAuthorize("hasRole('ROLE_ADMIN')") 
public ResponseEntity<ResponseWrapper> getError(...


INSERT INTO table USER_ROLE VALUES ('ADMIN','PASSWORD','ROLE_ADMIN');

How can the method "hasRole" query the table USER_ROLE? Is there any setting that I must give to Spring in order to communicate with that table?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Ensure you add the following to your configuration:

Annotation style:

@EnableGlobalMethodSecurity(prePostEnabled = true)

XML Style:

<global-method-security pre-post-annotations="enabled"/>

It's all in the spring docs.

Using @Pre and @Post annotations requires you to have first set up spring security in your project. User roles are loaded during authentication in the standard implementation.

It doesn't check your table when checking the annotation (by default), it just checks the Principal (User) object in memory for the list of assigned GrantedAuthority (Roles).

A closer look...

Take a look at the UserDetailsService interface, this returns an instance of UserDetails (the Principal). This is where we fetch your "user" from the database.

The UserDetails interface defines a method called getAuthorities() that returns a Collection<? extends GrantedAuthority>, essentially your Role table. This is where the "Roles" make it into memory, and can be later checked by the @Pre and @Post annotations.

The implementation I've explained above can be found here.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!