Spring Security从数据库授权请求值


问题内容

我想在服务器启动时从数据库配置“授权请求”值。目前,我在Java类文件中提供了核心价值,是否有任何方法可以从数据库中读取相同内容。

下面是示例代码:

protected void configure(HttpSecurity http) throws Exception {
http
    .authorizeRequests()                                                                
        .antMatchers("/resources/**", "/signup", "/about").permitAll()                  
        .antMatchers("/admin/**").hasRole("ADMIN")                                      
        .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")            
        .anyRequest().authenticated()                                                   
        .and()
    // ...
    .formLogin();
}

如何从数据库读取URL,例如:/ admin / **从数据库而不是类文件中的硬代码值


问题答案:

您可以使用Spring JDBC支持。首先,您需要设置一个数据库。然后,您可以检索行并进行适当处理。

您应该有一个表,其中有行,并且一列填充有like
/admin/**/db/**。另一列应填充角色访问信息。之后,通过遵循本教程,您应该检索这些行。假设您具有以下实体类:

class Matcher {
   public String name;
   public String roleInfo;
}

然后,您可以遍历Matcher实体进行配置:

    http.authorizeRequests()
            .antMatchers("/resources/**", "/signup", "/about").permitAll();

    for (Matcher matcher : matchers) {
        http.authorizeRequests().antMatchers(matcher.name).access(matcher.roleInfo);
    }
    http.authorizeRequests().anyRequest().authenticated()
            .and()
                    // ...
            .formLogin();