我正在尝试配置SpringSecurity以与“记住我”身份验证一起使用。

这是我的Java配置:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsService userDetailsService;
    @Autowired
    DatabasePersistentTokeRepositoryImpl databasePersistentTokeRepositoryImpl;

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .authenticationProvider(rememberMeAuthenticationProvider())
        .rememberMe().tokenRepository(databasePersistentTokeRepositoryImpl).tokenValiditySeconds((int) TimeUnit.SECONDS.convert(7, TimeUnit.DAYS))
        .and()
            .csrf().disable();
    }

    @Bean()
    public AuthenticationProvider rememberMeAuthenticationProvider() {
        return new RememberMeAuthenticationProvider("KEY");
    }

    @Bean()
    public TokenBasedRememberMeServices rememberMeServices() {
        TokenBasedRememberMeServices rememberMeServices = new TokenBasedRememberMeServices("KEY", userDetailsService);
        rememberMeServices.setAlwaysRemember(true);
        return rememberMeServices;
    }
}

我看到RememberMeConfigurer中没有注入RememberMeServices。结果导致创建了RememberMeAuthenticationFilter,它引用了错误的RememberMeServices。

Spring Security文档中有一节描述了使用XML的过程。
http://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#session-mgmt

我的注入有什么问题,而如果没有XML,这样做到底有可能吗?

最佳答案

您不是要注射它。 RememberMeConfigurer没有自动装配。还有为什么要配置这么多bean?
RememberMeAuthenticationProvider已经为您创建,如果您想使用其他密钥,请使用key("KEY")指定它。依次将其用于创建RememberMeServices

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsService userDetailsService;
    @Autowired
    DatabasePersistentTokeRepositoryImpl databasePersistentTokeRepositoryImpl;

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .rememberMe()
            .key("KEY")
            .tokenRepository(databasePersistentTokeRepositoryImpl)
                .tokenValiditySeconds((int) TimeUnit.SECONDS.convert(7, TimeUnit.DAYS))
        .and()
            .csrf().disable();
    }
}

如果确实需要将alwaysRemember属性设置为true,则可以使用ObjectPostProcessor对过滤器进行后期处理,并从此处配置RememberMeServices

您还会注入错误的RememberMeServices类型,因为配置的类型不使用PersistentTokeRepository

10-08 12:56