如何在 Java 中使用 Spring security OAuth2 在资源服务器中动态配置 Httpsecurity?

KNo*_*Now 4 java spring spring-security oauth-2.0

我是 Spring OAuth 2 的新手。我想知道如何Httpsecurity使用 Spring OAuth 2.0 在资源服务器中动态配置。因为我有存储在数据库中的antMatchers和列表scopes(可能在将来antMatchers并且scopes可以添加)。

对于单身antMatchersscope我尝试过如下所示,并且按预期工作:

@Override
public void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/adminservice/")
        .access("#oauth2.hasScope('Products')");
}
Run Code Online (Sandbox Code Playgroud)

如果有一个antMatchersscopes存储在数据库中的列表,我应该如何配置它,例如:

**antMatchers**     **scopes**
/adminservice/      products
/xxxx/              yyyy
/yyyy/              xxxx
/jkjlk/             uyuuy
/klklk/             hjkskjk
Run Code Online (Sandbox Code Playgroud)

在这里,spring 启动本身想要在资源服务器中动态地从数据库中配置antMatchers相应scope的。

我怎样才能做到这一点?

小智 6

根据您的数据库访问机制,只需自动装配您的 jdbcTemplate、entityService 并执行以下操作:

@Override
public void configure(HttpSecurity http) throws Exception {
    List<Matcher> matchers=matchersService.getAll();
    for(Matcher m : matchers) {
      http.authorizeRequests()
        .antMatchers(m.getMapping())
        .access("#oauth2.hasScope('"+m.getScope()+"')");
    }
}
Run Code Online (Sandbox Code Playgroud)

现在这将解决启动期间的配置。如果您希望能够在运行时动态更改此设置,我建议您重新启动服务器(如果可以的话)。