I'm trying to define access rules at method-level but it's not working what so ever.
SecurityConfiguration
@Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Override public void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication(). withUser("user").password("user").roles("USER").and(). withUser("admin").password("admin").roles("ADMIN"); } @Override protected void configure(HttpSecurity http) throws Exception { http .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .antMatchers("/v2/**").authenticated() .and() .httpBasic() .realmName("Secure api") .and() .csrf() .disable(); } }
ExampleController
@EnableAutoConfiguration @RestController @RequestMapping({"/v2/"}) public class ExampleController { @PreAuthorize("hasAuthority('ROLE_ADMIN')") @RequestMapping(value = "/home", method = RequestMethod.GET) String home() { return "Hello World"; } }
Whenever I try to access /v2/home using user:user
it executes just fine, shouldn't it give me an Access Denied error due to 'user' not having ROLE_ADMIN
?
I'm actually thinking of ditching access rules at method-level and stick to http() ant rules, but I have to know why it's not working for me.
@PreAuthorize annotation is used on a method level. For example, you can add the @PreAuthorize annotation above the @RequestMapping method that handles HTTP DELETE requests to allow only those users who have an ADMIN Role to invoke this method. @PreAuthorize annotation supports method security expressions.
A decision by your health insurer or plan that a health care service, treatment plan, prescription drug or durable medical equipment is medically necessary. Sometimes called prior authorization, prior approval or precertification.
Description. hasRole([role]) Returns true if the current principal has the specified role. hasAnyRole([role1,role2]) Returns true if the current principal has any of the supplied roles (given as a comma-separated list of strings)
Run the app using: ./gradlew bootRun . Navigate to the home endpoint, which is open: http://localhost:8080 . And the restricted endpoint, which requires authentication: http://localhost:8080/restricted . When Spring's login form appears, don't forget you can use the default credentials.
You have to add @EnableGlobalMethodSecurity(prePostEnabled = true)
in your WebSecurityConfig.
You can find it here: http://www.baeldung.com/spring-security-expressions-basic
@Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With