Affichage des articles dont le libellé est Spring Boot Security. Afficher tous les articles
Affichage des articles dont le libellé est Spring Boot Security. Afficher tous les articles

mardi 21 juillet 2015

Grails 3 and Spring boot security with Secured annotation

It is possible to use Spring Boot Security in order to replace Spring Security Core plugin. This is explained in two blog post:

Grails 3 App with Security (Part 1)
Grails 3 App with Security (Part 2) - Gorm-based authentication

However, if you want to use the Secured annotation, you have to care about 2 things:

  • Roles names have "ROLE_" string prepended to the role name you create with the "AuthenticationManagerBuilder"
  • Add simply "@EnableGlobalMethodSecurity(securedEnabled = true)" annotation to the SecurityConfiguration class
All in all, here is a sample controller:

package test

import org.springframework.security.access.annotation.Secured
class ToProtectController {

    @Secured(value = ["ROLE_USER"])
    def index() {
        println session.SPRING_SECURITY_CONTEXT?.getAuthentication()?.getPrincipal()

        render "index"    }

    def toto() {
        render 'toto'    }
}
 A sample WebSecurityConfigurerAdapter:


@Configuration@EnableWebMvcSecurity@EnableGlobalMethodSecurity(securedEnabled = true)class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers('/admin*//**').hasAnyRole('ADMIN')
                .antMatchers('/home*//**').hasAnyRole('USER', 'ADMIN')
                .antMatchers('/').permitAll()
                .and()
                .formLogin().permitAll()
                .and()
                .logout().permitAll()
    }
    
    @Autowired    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser('user').password('user').roles('USER')
                .and()
                .withUser('admin').password('admin').roles('ADMIN');
    }
}
 Notice the "EnableGlobalMethodSecurity" annotation.

Hope this helps!