Difference between @Secured vs @RolesAllowed in Spring? And the concept of Role Based Security?

后端 未结 2 596
被撕碎了的回忆
被撕碎了的回忆 2021-02-07 11:44

I am studying Spring Security and I have the following doubts related the difference between the use of the @Secured annotation and the @RolesAllowed

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-07 12:46

    The accepted answer completely answers the question (heh), but I think this is a good place to say how to enable method level security in Spring.

    The only thing You need to add is the @EnableGlobalMethodSecurity annotation on a configuration class (see the example) with the following properties set to true (default is false)

    • securedEnabled (enables Spring's Secured annotation.),
    • jsr250Enabled (enables the JSR-250 standard java security annotations, like RolesAllowed),
    • prePostEnabled (enables Spring's PreAuthorize and PostAuthorize annotations).

    Example of annotation usage:

    @EnableGlobalMethodSecurity(
        securedEnabled = true,
        jsr250Enabled = true,
        prePostEnabled = true)
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    // ...
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .anyRequest().fullyAuthenticated()
            .and()
            .formLogin(); // You probably need more than this
    }
    
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        // your authentication manager config here
    }
    

    For more detailed example, see Spring Security Method Level Annotations Example.

提交回复
热议问题