web-dev-qa-db-de.com

So aktivieren Sie gesicherte Anmerkungen mit Java-basierter Konfiguration

Ich möchte @Secured-Annotationen für meine Controller-Aktionen verwenden. Da ich eine Java-basierte Konfiguration habe, muss ich wissen, wie ich das einstellen kann 

<security:global-method-security secured-annotations="enabled" />

option ohne die XML-Datei.

Upate 1:

Ich habe @EnableGlobalMethodSecurity(securedEnabled = true) meiner Sicherheitskonfigurationsklasse zugewiesen:

@Configuration
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class LIRSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authenticationProvider(preAuthenticatedAuthenticationProvider())
            .addFilter(cookiePreAuthenticationFilter())
            .authorizeRequests()
            .antMatchers("/**")
            .hasAnyAuthority("ROLE_USER")
            ;
    }

    ...
}

Beim Start verursacht dies diese Ausnahme

Jul 21, 2014 3:32:54 PM org.Apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'methodSecurityInterceptor' defined in class path resource [org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfiguration.class]: Invocation of init method failed; nested exception is Java.lang.IllegalArgumentException: An AuthenticationManager is required
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.Java:1512)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.Java:521)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.Java:458)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.Java:296)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.Java:223)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.Java:293)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.Java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.Java:633)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.Java:932)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.Java:479)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.Java:410)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.Java:306)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.Java:112)
    at org.Apache.catalina.core.StandardContext.listenerStart(StandardContext.Java:4937)
    at org.Apache.catalina.core.StandardContext.startInternal(StandardContext.Java:5434)
    at org.Apache.catalina.util.LifecycleBase.start(LifecycleBase.Java:150)
    at org.Apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.Java:1559)
    at org.Apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.Java:1549)
    at Java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.Java:303)
    at Java.util.concurrent.FutureTask.run(FutureTask.Java:138)
    at Java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.Java:895)
    at Java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.Java:918)
    at Java.lang.Thread.run(Thread.Java:695)
Caused by: Java.lang.IllegalArgumentException: An AuthenticationManager is required
    at org.springframework.util.Assert.notNull(Assert.Java:112)
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.afterPropertiesSet(AbstractSecurityInterceptor.Java:121)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.Java:1571)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.Java:1509)
    ... 22 more
Jul 21, 2014 3:32:54 PM org.Apache.catalina.core.StandardContext

Update 2:

Nach dem Hinzufügen

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

Ich bekomme eine andere Ausnahme:

Caused by: org.springframework.beans.FatalBeanException: A dependency cycle was detected when trying to resolve the AuthenticationManager. Please ensure you have configured authentication.
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$AuthenticationManagerDelegator.validateBeanCycle(WebSecurityConfigurerAdapter.Java:462)
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$AuthenticationManagerDelegator.<init>(WebSecurityConfigurerAdapter.Java:430)
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.authenticationManagerBean(WebSecurityConfigurerAdapter.Java:220)
    at com.galexis.lir.config.LIRSecurityConfig.authenticationManagerBean(LIRSecurityConfig.Java:36)
    at com.galexis.lir.config.LIRSecurityConfig$$EnhancerBySpringCGLIB$$88306f96.CGLIB$authenticationManagerBean$3(<generated>)
    at com.galexis.lir.config.LIRSecurityConfig$$EnhancerBySpringCGLIB$$88306f96$$FastClassBySpringCGLIB$$a4d1ea33.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.Java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.Java:293)
    at com.galexis.lir.config.LIRSecurityConfig$$EnhancerBySpringCGLIB$$88306f96.authenticationManagerBean(<generated>)
    at Sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at Sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.Java:39)
    at Sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.Java:25)
    at Java.lang.reflect.Method.invoke(Method.Java:597)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.Java:160)
    ... 77 more
21
BetaRide

Sie müssen das verwenden 

@EnableGlobalMethodSecurity(securedEnabled = true)

anmerkung, wie in docs definiert.

14
Stefan

Sie sollten auch eine Bean für Manager hinzufügen. Überprüfen Sie dies heraus:

@Configuration
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Resource(name = "authService")
    private UserDetailsService userDetailsService;

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        Md5PasswordEncoder encoder = new Md5PasswordEncoder();
        auth.userDetailsService(userDetailsService).passwordEncoder(encoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .formLogin()
            .loginPage("/login")
            .and()
            .logout()
            .logoutSuccessUrl("/");
    }
}

Wichtige Sache ist

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
10
astrohome

Nur für die anderen, die versuchen zu lösen: "Beim Auflösen des AuthenticationManagers wurde ein Abhängigkeitszyklus erkannt. Stellen Sie sicher, dass Sie die Authentifizierung konfiguriert haben." Problem.

Die Lösung ist, die folgende Methode hinzuzufügen:

@Override
@Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    // do NOT call super.configure() !
    ...
}
6
kulatamicuda

So hat das die Arbeit gemacht:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().
                withUser("user").password("user").roles("USER").and().
                withUser("admin").password("admin").roles("USER", "ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .httpBasic();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }
}

die wichtigen teile sind

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().
                withUser("user").password("user").roles("USER").and().
                withUser("admin").password("admin").roles("USER", "ADMIN");
    }
5
Mickaël Gauvin

Stefan hat recht und fügt hinzu 

@EnableGlobalMethodSecurity(securedEnabled = true)

macht den Trick.

In meiner besonderen Situation musste ich hinzufügen, um die Exzesse loszuwerden.

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth
        .inMemoryAuthentication()
            .withUser("user").password("password").authorities("ROLE_USER");
}
1
BetaRide

Folgen Sie den Klassen innerhalb der Anmerkungen

 @Configuration
    @EnableGlobalMethodSecurity(securedEnabled = true)
    public class SecurityConfigProvider extends GlobalMethodSecurityConfiguration {

        @Override
        protected MethodSecurityExpressionHandler createExpressionHandler() {
            return new OAuth2MethodSecurityExpressionHandler();
        }

    }


@Configuration
@EnableOAuth2Client
@EnableWebSecurity
public class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    OAuth2ClientContext oauth2ClientContext;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //TODO
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        //TODO
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}
0
Tiago Medici