0

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

@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 角色的人。如果您有任何建议或可以指出一个很好的例子,请告诉我。

4

1 回答 1

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/**

于 2013-11-04T16:52:54.597 回答