【发布时间】:2017-03-25 09:50:57
【问题描述】:
我有一个 Spring Boot 应用程序,在该应用程序启动期间,我尝试使用 Javaassist 注入 Spring-Security Java 配置。我正在从 DB 中的值动态生成 java 配置。这是代码,
public class WarLock implements SpringApplicationRunListener {
private final SpringApplication application;
public WarLock(SpringApplication application, String[] args) throws IOException {
this.application = application;
}
@Override
public void started() {
try {
System.out.println("Re-write security config called");
rewriteSecurityConfigClass();
} catch (NotFoundException | CannotCompileException e) {
e.printStackTrace();
}
}
private void rewriteSecurityConfigClass() throws NotFoundException, CannotCompileException {
SecurityConfig config = new SecurityConfig();
ClassPool cp = ClassPool.getDefault();
cp.appendClassPath(new LoaderClassPath(application.getClassLoader()));
CtClass compiledClass = cp.get(config.getClass().getName());
CtClass[] argClasses = { cp.get(HttpSecurity.class.getName()) };
CtMethod method = compiledClass.getDeclaredMethod("configure",argClasses);
method.setBody("http .csrf().disable() "+
".authorizeRequests() "+
" .antMatchers(\"/css/**\", \"/index\").permitAll() "+
" .antMatchers(\"/user/**\").hasAuthority(\"USER\") "+
" .antMatchers(\"/tryadmin\").hasAuthority(\"ADMIN\") "+
" .antMatchers(\"/try\").hasAuthority(\"USER\") "+
" .and() "+
".authenticationProvider(authenticationProvider()) "+
" .exceptionHandling() "+
" .authenticationEntryPoint(entryPoint) "+
" .and() "+
".formLogin() "+
" .usernameParameter(\"username\") "+
" .passwordParameter(\"password\") "+
" .successHandler(loginSuccessHandler) "+
" .failureHandler(loginFailureHandler) "+
" .and() "+
".logout() "+
" .permitAll() "+
" .logoutRequestMatcher(new AntPathRequestMatcher(\"/login\", \"DELETE\")) "+
" .logoutSuccessHandler(logoutSuccessHandler) "+
" .deleteCookies(\"JSESSIONID\") "+
" .invalidateHttpSession(true) "+
" .and() "+
".sessionManagement() "+
" .enableSessionUrlRewriting(true) "+
" .maximumSessions(1); ");
compiledClass.toClass();
但代码在启动时失败,
javassist.CannotCompileException: [source error] authorizeRequests() not found in org.springframework.security.config.annotation.web.HttpSecurityBuilder
它正在 HTTPSecurityBuilder 类中寻找 authorizeRequests() 但它实际上必须查看“HttpSecurity”类。我怎样才能解决这个问题?提前致谢。
【问题讨论】: