【问题标题】:How to use dynamic Role in Spring Security如何在 Spring Security 中使用动态角色
【发布时间】:2018-06-02 10:46:45
【问题描述】:

我正在开发一个 Web 服务,它使用 Spring Security 工具箱来授权“权威”的请求。当然,Web 服务有一个配置类,该类扩展为 WebSecurityConfigurerAdapter 类并覆盖了 configure(HttpSecurity http) 方法。

在该方法中,我使用以下代码编写了配置文件(角色或权限):

           http
              .authorizeRequests() 
                         .antMatchers("/**").hasAnyAuthority("PERFIL")      
                         .anyRequest().authenticated()
                         .and() 
             .logout().clearAuthentication(true)
                      .invalidateHttpSession(true)
                      .and()

             .csrf().disable(); 

它工作得很好,但是我想从数据库中收取动态配置文件(角色或权限),因为我想在不更改 Web 服务的情况下更改它们。

有人知道怎么做吗?

问候。

【问题讨论】:

    标签: java spring spring-mvc


    【解决方案1】:

    为了从数据库中传递这些详细信息,您必须更改许多配置。

    使用 jdbc-user-service 定义查询以执行数据库身份验证。

    <authentication-manager>
          <authentication-provider>
            <jdbc-user-service data-source-ref="dataSource"
              users-by-username-query=
                "select username,password, enabled from users where username=?"
              authorities-by-username-query=
                "select username, role from user_roles where username =?  " />
          </authentication-provider>
        </authentication-manager>
    

    关注 this 教程,了解 Spring Security 的工作原理。

    【讨论】:

    • 嗨罗汉。我已经在身份验证中更改了每个用户的权限,但是我正在尝试在 configure(HttpSecurity http) 方法中使用动态角色,即我想通过类似这样的方式更改代码.antMatchers("/**").hasAnyAuthority("PERFIL")(显然,此代码不存在): .antMatchers("/**").hasAnyAuthority("?"),这样? 必须在服务启动时根据对数据库的查询进行更改。是这样的想法,但我知道它的形式是否正确。
    • 嗨,Abel,您是否浏览过以下链接。 stackoverflow.com/questions/8321696/…
    【解决方案2】:

    您可以找到完整的工作示例here

    虽然我的项目中的逻辑是颠倒的,但您可以提取有助于您的案件的信息(如如何将这些权限“注入”弹簧安全性)

    在 Authorities 类中,我定义了 2 个静态 authorities。这是您可以从数据库中获取权限的地方。你可以有一个空的List&lt;Authority&gt;,它会在你的应用程序启动时自动从数据库中填充(参见@PostConstruct)。

    你的权威类应该像here那样实现spring的GrantedAuthority

    【讨论】:

      猜你喜欢
      • 2011-07-14
      • 2019-12-18
      • 2017-05-18
      • 2011-11-21
      • 2014-05-09
      • 1970-01-01
      • 2018-07-14
      • 1970-01-01
      • 2012-01-09
      相关资源
      最近更新 更多