I am having some issues with spring web security and my database. If I use
@Configuration
@EnableWebSecurity
public class BBSecurity extends WebSecurityConfigurerAdapter {
@Autowired
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder> cfg = auth.jdbcAuthentication();
cfg.dataSource(dataSource);
cfg.usersByUsernameQuery("SELECT user_name, password, true FROM user_data WHERE user_name=?");
cfg.passwordEncoder(new MyPasswordEncoder());
cfg.authoritiesByUsernameQuery("SELECT user_name, concat('ROLE_',role) FROM user_data WHERE user_name=?");
}
}
The method is successfully called, but in the log I see this
Using default security password: 81456c65-b6fc-43ee-be41-3137d02b122b
and my database code is never used.
If, instead, I use (in the same class)
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception
JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder> cfg = auth.jdbcAuthentication();
... same config code as above
}
it works fine, but sometimes configureGlobal
is called before setDataSource
and I get an IllegalStateException
because dataSource
was not injected before it was used.
I would like to understand what else is needed to make the first method work.
Also is there any way to control the order of @Autowired
. Adding @DependsOn(DataSource)
to configureGlobal
has no effect.
Use Field Injection instead of Setter Injection :
@Configuration
@EnableWebSecurity
public class BBSecurity extends WebSecurityConfigurerAdapter {
@Autowired private DataSource dataSource;
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
// Same stuff
}
}
Or inject the Datasource
directly to the configureGlobal
method:
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth, DataSource dataSource) throws Exception {
// same stuff
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.