如何在 Java 中使用 Spring security OAuth2 在资源服务器中动态配置 Httpsecurity? [英] How to dynamically configure Httpsecurity in the Resource server using Spring security OAuth2 in Java?

查看:105
本文介绍了如何在 Java 中使用 Spring security OAuth2 在资源服务器中动态配置 Httpsecurity?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to Spring OAuth 2. I would like to know how configure Httpsecurity in Resource server dynamically using Spring OAuth 2.0. Since I have list of antMatchers and scopes that are stored in the database (may be in future antMatchers and scopes can be added).

对于单个 antMatchersscope 我已经像下面这样尝试过,它按预期工作:

For single antMatchers and scope I have tried it like below and it worked as expected:

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

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

How should I configure it if there are a list of antMatchers and scopes that are stored in the database such as:

**antMatchers**     **scopes**
/adminservice/      products
/xxxx/              yyyy
/yyyy/              xxxx
/jkjlk/             uyuuy
/klklk/             hjkskjk

在这里,当 spring 启动本身时,希望在资源服务器中动态地从数据库中配置 antMatchers 与各自的 scope.

Here while spring booting itself want to configure the antMatchers with respective scope from the database dynamically in the resource server.

我怎样才能做到这一点?

How can I achieve this?

推荐答案

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

Depending on your database access mechanism just autowire your jdbcTemplate, entityService and do:

@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()+"')");
    }
}

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

Now that will solve the configuration during startup. If you want to be able to dynamically change this during runtime I would simply suggest restarting the server if it's an option.

这篇关于如何在 Java 中使用 Spring security OAuth2 在资源服务器中动态配置 Httpsecurity?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆