Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I secure Spring controller methods for user roles?

I have USER, ROLE and USER_ROLE tables and a bunch Spring controllers ... is there an Spring annotation I can add to the controller methods that will specify the role(s) a user should have to be able to access it?

I guess it's going to be Spring security? Is that straighforward to wire up to an existing user/role schema?

I'm using Spring 2.5.4.

like image 804
blank Avatar asked Oct 31 '25 05:10

blank


1 Answers

Spring Security is going to be your easiest way to do it. What you're asking for specifically is Method Security Expressions. You can achieve this by using the following:

@PreAuthorize("hasRole('ROLE_ADMIN')")
public void deleteUser(User user) {
  ...
}

It's pretty straightforward to set up Spring Security with a database backend. I'd take a look at the DAOAuthenticationProvider as a starting point.

like image 108
Caps Avatar answered Nov 01 '25 19:11

Caps



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!