弹簧安全激活始终记住我的功能

时间:2015-08-13 07:44:15

标签: spring spring-mvc spring-security

我使用基于持久令牌方法记住我功能实现了 spring security 的示例。实际上,我正在使用自定义身份验证管理器如何在不添加复选框的情况下永远激活选项remember-me记住我在登录表单上记住我(我也不想放置复选框)输入隐藏并默认激活)。我怎样才能实现这一目标? 这里是我做的spring security java配置:

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

    RequestMatcher matcher = new RequestHeaderRequestMatcher("X-Requested-With");

    LOGGER.debug("Creating Security Context ...");
    http.
    sessionManagement()
    .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().
    csrf().requireCsrfProtectionMatcher(createCSRFMathers()).and();

    //Add autologin filter
    http.addFilter(autoLoginFilter)
            .addFilterBefore(new TransactionIdRequestFilter(), AutoLoginFilter.class)
            .exceptionHandling().defaultAuthenticationEntryPointFor(new Http401TimeoutEntryPoint(), matcher)
            .and();

    //Add form login
    http.formLogin()
            .successHandler(savedRequestAwareAuthenticationSuccessHandler())
            .loginPage("/page/login")
            .loginProcessingUrl("/page/login/authenticate")
            .failureUrl("/page/login?loginError=true")
            .and();

    // Configures the logout function
    http.logout()
            .deleteCookies("JSESSIONID")
            .logoutUrl("/logout")
            .logoutSuccessUrl("/page/login?loginError=false")
            .and();

    // Configures url based authorization
    // Anyone can access the following urls
    http.authorizeRequests()
            .antMatchers("posc://**",
                    "/connectedUser/mobileInfos",
                    "/dashboard/config/**",
                    "/page/checklogintoken/**",
                    "/page/httpError",
                    "/page/login/**",
                    "/page/manifest",
                    "/page/token/**",
                    "/service-scripting/**",
                    "/script/**")
            .permitAll()
            .antMatchers("/**")
            .hasRole("USER").and().rememberMe().rememberMeServices(rememberMeServices());

  }

@Bean   
  public AbstractRememberMeServices rememberMeServices() {

      PersistentTokenBasedRememberMeServices rememberMeServices =
          new PersistentTokenBasedRememberMeServices("AppKey",customUserDetailsService,persistentTokenRepository());
      rememberMeServices.setAlwaysRemember(true);
      return rememberMeServices;
  }
@Bean
    public PersistentTokenRepository persistentTokenRepository() {
        CassandraTokenRepository db = new CassandraTokenRepository(persistanceTokenDao);
        return db;
    }

    @Bean
    public SavedRequestAwareAuthenticationSuccessHandler savedRequestAwareAuthenticationSuccessHandler() {
        SavedRequestAwareAuthenticationSuccessHandler auth = new SavedRequestAwareAuthenticationSuccessHandler();
        auth.setTargetUrlParameter("targetUrl");
        return auth;
    }   

我有一个AbstractPreAuthenticatedProcessingFilter,其中包含一个自定义身份验证管理器,用于在对用户进行身份验证之前创建自定义功能。如何使用此过滤器将remember me选项设置为true?

@Component
public class AutoLoginFilter extends AbstractPreAuthenticatedProcessingFilter {

 @Override
  public void doFilter(final ServletRequest request,
                       final ServletResponse response,
                       final FilterChain chain) throws IOException, ServletException {
...
}

}

感谢。

2 个答案:

答案 0 :(得分:2)

您可以配置tokenRepository,而不是配置rememberMeService。创建rememberMe服务时,可以设置alwaysRemember标志。像这样:

@Bean   
public AbstractRememberMeServices rememberMeServices() {

    PersistentTokenBasedRememberMeServices rememberMeServices =
        new PersistentTokenBasedRememberMeServices(...
    ...
    rememberMeServices.setAlwaysRemember(true);
    ...
    return rememberMeServices;
}

然后可以将上面的rememberMeServices提供给Spring Security:

...
.rememberMe()
    .rememberMeServices(rememberMeServices())
...

答案 1 :(得分:2)

我实现了一个解决问题的完整示例。启用记住我功能而不在登录表单上添加输入复选框,并使用持久令牌方法在身份验证时将令牌保存在数据库中。

这是Spring security conf:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;
    @Autowired
    AuthenticationService customUserDetailsService;

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth)
            throws Exception {

        auth.userDetailsService(customUserDetailsService);
    }

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

        http.rememberMe().rememberMeServices(rememberMeServices()).key("posc").and();
        http.csrf()
                .disable()
                .authorizeRequests()
                .antMatchers("/admin/**")
                .access("hasRole('ROLE_ADMIN')")
                .antMatchers("/admin/update**")
                .access("hasRole('ROLE_ADMIN')")
                .and()
                .formLogin()
                .successHandler(savedRequestAwareAuthenticationSuccessHandler())
                .loginPage("/login").failureUrl("/login?error")
                .loginProcessingUrl("/auth/login_check")
                .usernameParameter("username").passwordParameter("password")
                .and().logout().logoutUrl("/logout")
                .logoutSuccessUrl("/login?logout");
    }

    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl db = new JdbcTokenRepositoryImpl();
        db.setDataSource(dataSource);
        return db;
    }

    @Bean   
      public AbstractRememberMeServices rememberMeServices() {
          PersistentTokenBasedRememberMeServices rememberMeServices =
              new PersistentTokenBasedRememberMeServices("posc",customUserDetailsService,persistentTokenRepository());
          rememberMeServices.setAlwaysRemember(true);
          rememberMeServices.setCookieName("remember-me-posc");
          rememberMeServices.setTokenValiditySeconds(1209600);
          return rememberMeServices;
      }

    @Bean
    public SavedRequestAwareAuthenticationSuccessHandler savedRequestAwareAuthenticationSuccessHandler() {
        SavedRequestAwareAuthenticationSuccessHandler auth = new SavedRequestAwareAuthenticationSuccessHandler();
        auth.setTargetUrlParameter("targetUrl");
        return auth;
    }

}

这里是我的github上的完整示例: https://github.com/Moussi/SpringSecurity-RememberMe-AlwaysEnabled-JavaConfig