Spring Security - 登录后不阻止访问

时间:2013-11-04 16:44:25

标签: spring spring-mvc spring-security

我正在尝试使用Roles的Java配置用于Spring Security,以便仅授予对经过身份验证的用户的访问权限。登录过程正在运行,但是当我使用应该具有有限访问权限的角色登录时,我仍然能够到达应该受到保护的路由。这是我的WebSecurityConfigurerAdapter类,其中包含http配置:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
DataConfig dataConfig;

private final String QUERY_USERS = "select email, password, enabled from Account where email=?";
private final String QUERY_AUTHORITIES = "select a.email, au.authority from Account a, Authority au where a.email = au.email and a.email =?  ";

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

    http
    .authorizeUrls()
    .antMatchers("/public/login.jsp").permitAll()
    .antMatchers("/public/home.jsp").permitAll()
    .antMatchers("/public/**").permitAll()

    .antMatchers("/secured/**").fullyAuthenticated()
    .antMatchers("/resources/clients/**").fullyAuthenticated()
    .antMatchers("/secured/user/**").hasRole("USER")
    .antMatchers("/secured/admin/**").hasRole("ADMIN")

    .and()
     .formLogin()
        .loginPage("/login")
        .loginProcessingUrl("/j_spring_security_check")
        .failureUrl("/loginfailed")
        .usernameParameter("j_username")
        .passwordParameter("j_password")

     .and()
     .logout()
        .logoutUrl("/j_spring_security_logout")     // The URL that triggers logout to occur on HTTP POST
        .logoutSuccessUrl("/logout")    // The URL to redirect to after logout has occurred
        .invalidateHttpSession(true);   // Clear the session
}

@Override
protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {

    // Use the database
    auth
    .jdbcAuthentication()
        .passwordEncoder(new org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder()) 
        .dataSource(dataConfig.dataSource())

        .withDefaultSchema()
        .usersByUsernameQuery(QUERY_USERS)
        .authoritiesByUsernameQuery(QUERY_AUTHORITIES);    
    }
}

这是我的WebApplicationInitializer类,我注册了安全过滤器链:

public class DatabaseWebApplicationInitializer implements WebApplicationInitializer {

private static final Class<?>[] configurationClasses = new Class<?>[] { 
                AppConfig.class, DbConfig.class, SecurityConfig.class};

private static final String DISPATCHER_SERVLET_NAME = "dispatcher";

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    registerListener(servletContext);           
    registerDispatcherServlet(servletContext);

    registerSpringSecurityFilterChain(servletContext);
}

private void registerDispatcherServlet(ServletContext servletContext) {

    // creates an application context for direct registration of 
    // @Configuration and other @Component-annotated classes
    AnnotationConfigWebApplicationContext dispatcherContext = createContext(AppConfig.class);

    ServletRegistration.Dynamic dispatcher = servletContext.addServlet(DISPATCHER_SERVLET_NAME,
            new DispatcherServlet(dispatcherContext));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");
}

private void registerListener(ServletContext servletContext) {
    AnnotationConfigWebApplicationContext rootContext = createContext(configurationClasses);
    servletContext.addListener(new ContextLoaderListener(rootContext));
    servletContext.addListener(new RequestContextListener());
}


private void registerSpringSecurityFilterChain(ServletContext servletContext) {
    FilterRegistration.Dynamic springSecurityFilterChain = servletContext.addFilter(
            BeanIds.SPRING_SECURITY_FILTER_CHAIN, new DelegatingFilterProxy());
    springSecurityFilterChain.addMappingForUrlPatterns(null, false, "/*");
}

private AnnotationConfigWebApplicationContext createContext(final Class<?>... annotatedClasses) {
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();

    // set the active profile
    context.getEnvironment().setActiveProfiles("dev");

    context.register(annotatedClasses);
    return context;
}

}

如果我使用仅具有USER(不是ADMIN)角色的凭据登录,我仍然可以访问 / secured / admin / ** 的路由,但我认为应限制为只有那些角色为ADMIN的人。如果您有任何建议或者可以向我指出一个很好的例子,请告诉我。

1 个答案:

答案 0 :(得分:3)

我有理由相信你的.antMatchers()陈述的顺序。

您目前.antMatchers("/secured/**").fullyAuthenticated()之前有.antMatchers("/secured/admin/**").hasRole("ADMIN")。 Spring Security可能与第一个匹配器匹配并应用fullyAuthenticated()检查,这意味着如果您只有角色USER,则会授予权限。

我建议您重新订购,以便.antMatchers()语句如下:

.antMatchers("/public/login.jsp").permitAll()
.antMatchers("/public/home.jsp").permitAll()
.antMatchers("/public/**").permitAll()
.antMatchers("/resources/clients/**").fullyAuthenticated()
.antMatchers("/secured/user/**").hasRole("USER")
.antMatchers("/secured/admin/**").hasRole("ADMIN")
.antMatchers("/secured/**").fullyAuthenticated()

在这种情况下,Spring会在回退到/secured/admin/**语句之前匹配早期的/secured/user/**/secured/**资源特定访问规则。

相关问题