5

我正在创建一个 Spring Security 配置,供任何想要创建由 Spring Security 保护的 Stormpath Spring 应用程序的开发人员用作库。

为此,我WebSecurityConfigurerAdapter通过. 所有这些都可以在这个抽象类及其具体子类中看到:configure(HttpSecurity)AuthenticationProviderconfigure(AuthenticationManagerBuilder)

@Order(99)
public abstract class AbstractStormpathWebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    //Removed properties and beans for the sake of keeping focus on the important stuff

    /**
     * The pre-defined Stormpath access control settings are defined here.
     *
     * @param http the {@link HttpSecurity} to be modified
     * @throws Exception if an error occurs
     */
    protected void configure(HttpSecurity http, AuthenticationSuccessHandler successHandler, LogoutHandler logoutHandler)
            throws Exception {

        if (loginEnabled) {
            http
                    .formLogin()
                    .loginPage(loginUri)
                    .defaultSuccessUrl(loginNextUri)
                    .successHandler(successHandler)
                    .usernameParameter("login")
                    .passwordParameter("password");
        }

        if (logoutEnabled) {
            http
                    .logout()
                    .invalidateHttpSession(true)
                    .logoutUrl(logoutUri)
                    .logoutSuccessUrl(logoutNextUri)
                    .addLogoutHandler(logoutHandler);

        }

        if (!csrfProtectionEnabled) {
            http.csrf().disable();
        } else {
            //Let's configure HttpSessionCsrfTokenRepository to play nicely with our Controllers' forms
            http.csrf().csrfTokenRepository(stormpathCsrfTokenRepository());
        }
    }

    /**
     * Method to specify the {@link AuthenticationProvider} that Spring Security will use when processing authentications.
     *
     * @param auth the {@link AuthenticationManagerBuilder} to use
     * @param authenticationProvider the {@link AuthenticationProvider} to whom Spring Security will delegate authentication attempts
     * @throws Exception if an error occurs
     */
    protected void configure(AuthenticationManagerBuilder auth, AuthenticationProvider authenticationProvider) throws Exception {
        auth.authenticationProvider(authenticationProvider);
    }
}

@Configuration
public class StormpathWebSecurityConfiguration extends AbstractStormpathWebSecurityConfiguration {

    //Removed beans for the sake of keeping focus on the important stuff

    @Override
    protected final void configure(HttpSecurity http) throws Exception {
        configure(http, stormpathAuthenticationSuccessHandler(), stormpathLogoutHandler());
    }

    @Override
    protected final void configure(AuthenticationManagerBuilder auth) throws Exception {
        configure(auth, super.stormpathAuthenticationProvider);
    }
}

简而言之,我们基本上是在定义我们的登录和注销机制,并集成我们的 CSRF 代码以与 Spring Security 的代码完美配合。

到目前为止,一切正常。

但这只是“库”,我们希望用户在它之上构建自己的应用程序。

因此,我们创建了一个示例应用程序来演示用户将如何使用我们的库。

基本上用户会想要创建自己的WebSecurityConfigurerAdapter. 像这样:

@EnableStormpathWebSecurity
@Configuration
@ComponentScan
@PropertySource("classpath:application.properties")
@Order(1)
public class SpringSecurityWebAppConfig extends WebSecurityConfigurerAdapter {

    /**
     * {@inheritDoc}
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/restricted").fullyAuthenticated();
    }

}

如果确实需要,则WebApplicationInitializer如下所示:

public class WebAppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext sc) throws ServletException {

        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(SpringSecurityWebAppConfig.class);
        context.register(StormpathMethodSecurityConfiguration.class);
        sc.addListener(new ContextLoaderListener(context));

        ServletRegistration.Dynamic dispatcher = sc.addServlet("dispatcher", new DispatcherServlet(context));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");

        //Stormpath Filter
        FilterRegistration.Dynamic filter = sc.addFilter("stormpathFilter", new DelegatingFilterProxy());
        EnumSet<DispatcherType> types =
                EnumSet.of(DispatcherType.ERROR, DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.REQUEST);
        filter.addMappingForUrlPatterns(types, false, "/*");

        //Spring Security Filter
        FilterRegistration.Dynamic securityFilter = sc.addFilter(AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME, DelegatingFilterProxy.class);
        securityFilter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/*");
    }
}

所有这些代码都能正确启动。如果我去,localhost:8080我会看到欢迎屏幕。如果我去,localhost:8080/login我会看到登录屏幕。但是,如果我去,localhost:8080/restricted我应该被重定向到登录页面,因为我们有这一行:http.authorizeRequests().antMatchers("/restricted").fullyAuthenticated();。但是我看到的是Access Denied页面。

然后,如果我在应用程序的访问控制中添加登录 url,如下所示:

protected void configure(HttpSecurity http) throws Exception {
    http
            .formLogin().loginPage("/login")
            .and()
            .authorizeRequests().antMatchers("/restricted").fullyAuthenticated();
}

它现在将我重定向到登录页面,但是一旦我提交凭据,我就会遇到 CSRF 问题,这意味着我们所有的配置实际上都不是这个过滤器链的一部分。

当我调试它时,似乎每个WebApplicationInitializer都有自己的实例和自己的过滤器链。我希望它们以某种方式连接起来,但似乎它实际上并没有发生......

有人尝试过这样的事情吗?

顺便说一句:作为一种解决方法,用户可以public class SpringSecurityWebAppConfig extends StormpathWebSecurityConfiguration代替SpringSecurityWebAppConfig extends WebSecurityConfigurerAdapter. 这种方式可以工作,但我希望用户拥有纯 Spring Security 代码,并从我们StormpathWebSecurityConfiguration与该目标的分歧中延伸出来。

所有代码都可以在这里看到。Spring 的 Stormpath Spring Security 库位于extensions/spring/stormpath-spring-security-webmvc. 使用该库的示例应用程序位于examples/spring-security-webmvc.

运行起来非常简单……您只需要按照此处的说明注册到 Stormpath 即可。然后您可以签出spring_security_extension_redirect_to_login_not_working分支并像这样启动示例应用程序:

$ git clone git@github.com:mrioan/stormpath-sdk-java.git
$ git checkout spring_security_extension_redirect_to_login_not_working
$ mvn install -DskipTests=true
$ cd examples/spring-security-webmvc
$ mvn jetty:run

然后你可以去localhost:8080/restricted看看你没有被重定向到登录页面。

很感谢任何形式的帮助!

4

2 回答 2

3

以我的经验,在启动时有多个WebSecurityConfigurers 与安全配置混淆的问题。

解决此问题的最佳方法是使您的库配置SecurityConfigurerAdapters可以在适当的地方应用。

public class StormpathHttpSecurityConfigurer
        extends AbstractStormpathWebSecurityConfiguration
        implements SecurityConfigurer<DefaultSecurityFilterChain, HttpSecurity> {

    //Removed beans for the sake of keeping focus on the important stuff

    @Override
    protected final void configure(HttpSecurity http) throws Exception {
        configure(http, stormpathAuthenticationSuccessHandler(), stormpathLogoutHandler());
    }
}

public class StormpathAuthenticationManagerConfigurer
        extends AbstractStormpathWebSecurityConfiguration
        implements SecurityConfigurer<AuthenticationManager, AuthenticationManagerBuilder> {

    //Removed beans for the sake of keeping focus on the important stuff

    @Override
    protected final void configure(AuthenticationManagerBuilder auth) throws Exception {
        configure(auth, super.stormpathAuthenticationProvider);
    }
}

然后,您可以让您的用户apply在他们自己的配置中:

@EnableStormpathWebSecurity
@Configuration
@ComponentScan
@PropertySource("classpath:application.properties")
@Order(1)
public class SpringSecurityWebAppConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/restricted").fullyAuthenticated()
                .and()
            .apply(new StormPathHttpSecurityConfigurer(...))
        ;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.apply(new StormPathAuthenticationManagerConfigurer(...));
    }
}
于 2016-10-04T07:56:39.857 回答
-2

这绝对是关于您的 Antmatchers 顺序的问题,或者没有指定您允许访问 URL 的用户角色。

你在“/restricted”之上有什么?

是否有东西完全阻止了该 URL 下方的任何内容?您应该首先指定更具体的 URL,然后是通用 URL。

尝试正确配置上面的 URL(或告诉我它是什么,以便我可以帮助你),也许在“/restricted”的父 URL 上应用“fullyAuthenticated”和“permitAll”ROLE。

于 2015-10-06T04:02:32.947 回答