【问题标题】:Spring security Authorize Requests value from databaseSpring security Authorize Requests 来自数据库的值
【发布时间】:2015-10-20 16:17:12
【问题描述】:

我想在服务器启动时从数据库配置授权请求值。目前我在 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/** 从数据库而不是类文件中的硬代码值

【问题讨论】:

  • 如果无法访问数据库,期望的结果是什么?

标签: java spring-mvc spring-security


【解决方案1】:

您可以使用Spring JDBC 支持。首先你需要建立一个数据库。然后,您可以检索行并适当地处理它们。

您应该有一个表,其中有行和列,其中填充有 /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();

【讨论】:

  • 我已经有一个数据库设置。如何从数据库而不是类中的硬代码为 antMatchers 赋值。如果我遗漏了什么,请告诉我您希望我执行哪种数据库设置。
  • 所以当服务器启动时我必须读取数据库值然后迭代?
  • protected void configure(HttpSecurity http) throws Exception {} 功能在用户登录或应用启动服务器时起作用??
【解决方案2】:

我遇到了同样的问题。就我的角色而言,我分配了几条路线。有人可能需要它。应该注意的是,我将@mtyurt 答案作为参考。 我解决的方法如下:

List<Role> roles = roleRepository.findAll();
for (Role role : roles
        ) {
    List<Page> pages = pageRepository.findPagesPerRole(role.getId());
    List<String> pageslist = new ArrayList<>();
    for (Page page : pages
         ) {
        pageslist.add(page.getUrl());
    }
    String[] authorities = pageslist.toArray(new String[0]);
    http.authorizeRequests().antMatchers(authorities).hasAuthority(role.getAuthority().toString());
}

我有一个table 用于保存路由,另一个用于保存roles。在角色中我可以给你分配页面,一个页面可以有多个角色,所以生成了many-to-many表。从 SQL 我得到了分配给角色的路由列表。这就是我做两个循环的原因。最后,我为 http 分配了一个 strings 数组和角色名称。

【讨论】:

    猜你喜欢
    • 2017-05-17
    • 1970-01-01
    • 2013-04-24
    • 2011-08-09
    • 2011-02-19
    • 2017-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多