ResouraseServerConfiger中antMancher的动态URL

时间:2019-02-01 13:34:27

标签: spring-boot spring-security spring-security-oauth2

在Spring Resourse配置中使用h2 db加载应用程序时如何获取db数据,并将该数据传递给antMatcher和访问。

例如: 公共类ResourceServerConfig扩展了ResourceServerConfigurerAdapter {

public void configure(HttpSecurity http)引发异常{

    System.out.println(dataSource.getConnection());
    //here i am getting db object
    http.requestMatchers().and().authorizeRequests()
    .antMatchers("/bitcash/profile/find-user**").access("hasRole('ROLE_USER')")
    .antMatchers("/bitcash/profile/find-admin**").access("hasRole('ROLE_ADMIN')").and()
            .exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());

    http.csrf().disable();
    http.headers().frameOptions().disable();
}

}

请帮助我。

public void configure(HttpSecurity http)引发异常{

    System.out.println(repo.getResourse());
    System.out.println(dataSource.getConnection());

    http.requestMatchers().and().authorizeRequests()
    .antMatchers("/bitcash/profile/find-user**").access("hasRole('ROLE_USER')")
    .antMatchers("/bitcash/profile/find-admin**").access("hasRole('ROLE_ADMIN')").and()
            .exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());

    http.csrf().disable();
    http.headers().frameOptions().disable();
}

1 个答案:

答案 0 :(得分:0)

Spring Web提供以下界面

public interface RequestMatcher {

    boolean matches(HttpServletRequest request);

}

和Spring Security,您可以使用

对其进行配置
    http
        .authorizeRequests()
            .requestMatchers(new MyMatcher(db), someOtherMatcher)
                .fullyAuthenticated()

如何实现我的匹配器完全取决于您。可能是

public class MyMatcher implements RequestMatcher {

    @Override
    public boolean matches(HttpServletRequest request) {
        String antPatternFromDB = db.getAntPattern(request);
        return new AntPathRequestMatcher(antPatternFromDB).matches(request);
    }
}

这假设db是可以访问数据库的Bean。

@Bean
public Db db() {
  return new Db(DriverManager.getConnection("jdbc:h2:~/test", "sa", ""));
}

请注意:您应该使用连接池而不是DriverManager.getConnection 。我认为这不在此答案的范围内。