简体   繁体   中英

Spring security requests authorization

I am new to spring security and was checking how to authorize requests to URLs in my application.

According to the documentation here , we add authorization as follow:

protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .antMatchers("/resources/**", "/signup", "/about").permitAll()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
            .anyRequest().authenticated()
            .and()
        // ...
        .formLogin();
}

As this method worked fine for me, I was wondering if there's another dynamic way to specify this configuration. By using some sort of annotations for our REST controllers for example?

I have a solution in mind that would be really practical, but I wanted to make sure that there's no other way to do this before starting to develop my own code.

Thank you for your help.

Yes there is an annotations as @Secured/@PreAuthorize/@PostAuthorize . this annotations are preferred way for applying method-level security, and supports Spring Expression Language out of the box, and provide expression-based access control.

for eg

@PreAuthorize("hasRole('ADMIN')") public String yourControllerMethod() { return response; }

for detail check here.

The only other way is to use the @Secured/@PreAuthorize/@PostAuthorize annotations. But you must put them on all webservices you want to secure.

Usually, when I build a webservices application, I like to authorize all requests on the WebSecurityConfigurerAdapter, and then secure requests one by one with these annotations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM