Can't configure antMatchers after anyRequest? how to resolve - java

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalStateException: Can't configure antMatchers after anyRequest
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:650) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
... 22 common frames omitted
Caused by: java.lang.IllegalStateException: Can't configure antMatchers after anyRequest
#Configuration
#EnableOAuth2Security
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final String[] STATIC_RESOURCES = {
"/api/test-api"
};
#Override
public void configure(HttpSecurity http) throws Exception {
// #formatter:off
http.authorizeRequests().antMatchers(STATIC_RESOURCES).permitAll()
.anyRequest().authenticated();
// #formatter:on
}
}

Related

Can I ensure properties are autowired in a specific order using Spring, or use a non-default constructor?

I have a requirement to dynamically create a Spring managed class which relies on properties passed through before being able to set one of its instantiated properties.
Ideally I would like to pass the required properties in the constructor, but Spring doesn't seem to allow use of non-default constructors when instantiating beans.
SubBean.java:
#Configuration
public class SubBean extends SuperBean {
#Autowired
private LdapTemplate ldapTemplate;
public SubBean() {
super();
}
#Bean
public LdapTemplate setLdapTemplate() {
LdapContextSource contextSource= new LdapContextSource();
int separatorLocation = this.string.indexOf('/', 8);
contextSource.setUrl(this.string.substring(0, separatorLocation));
contextSource.setBase(this.string.substring(separatorLocation + 1));
contextSource.setAnonymousReadOnly(true);
return new LdapTemplate(contextSource);
}
public List<Computer> searchDirectory() {
SearchControls searchControls = new SearchControls();
searchControls.setCountLimit(25);
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
List<Computer> computers = (List<Computer>) ldapTemplate.search(
LdapQueryBuilder.query().filter("OU=Domain Controllers"), new ComputerAttributesMapper());
return computers;
}
private class ComputerAttributesMapper implements AttributesMapper<Computer> {
#Override
public Computer mapFromAttributes(Attributes attributes) throws NamingException {
Computer computer = new Computer();
computer.setName((String) attributes.get("name").get(0));
return computer;
}
}
#Override
public void doStuff() {
List<Computer> computers = searchDirectory();
System.out.println(computers);
}
}
SpringBootConfiguration.java:
There are multiple types of SubBean so they need to be referenced as the superclass.
#SpringBootApplication
public class SpringBootConfiguration {
#Autowired
private ConfigFile configFile;
#Autowired
private AutowireCapableBeanFactory beanFactory;
public static void main(String[] args) {
SpringApplication.run(SpringBootConfiguration.class, args);
}
#Bean
//Load configuration from a JSON file
public ConfigFile configFile() throws JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
File file = new File("configuration.json");
ConfigFile cf = mapper.readValue(file, ConfigFile.class);
cf.setFile(file);
return cf;
}
#Bean
public CommandLineRunner run(RestTemplate restTemplate, ApplicationContext ctx) throws Exception {
return args -> {
System.out.println(configFile);
List<Poller> configuredPollers = configFile.getConfiguration().getPollers();
for (Poller p : configuredPollers) {
//The class name is specified in the JSON configuration file.
Class<SuperBean> clazz = (Class<SuperBean>) Class.forName(p.getType());
//Use Spring to set up the object - this will try to autowire the ldapTemplate property and fail
SuperBean superBean = (SuperBean) beanFactory.createBean(clazz, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, true);
//Because the beanFactory only uses the default constructor, I have to explicitly set its properties
superBean.setString(p.getString());
superBean.doStuff();
}
};
}
}
When this runs, I get the Exception:
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'subBean': Unsatisfied dependency expressed through field 'ldapTemplate'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'setLdapTemplate' defined in class path resource [test/SubBean.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.ldap.core.LdapTemplate]: Circular reference involving containing bean 'subBean' - consider declaring the factory method as static for independence from its containing instance. Factory method 'setLdapTemplate' threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:643)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:130)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1422)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:882)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215)
at test.SpringBootConfiguration.main(SpringBootConfiguration.java:28)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'setLdapTemplate' defined in class path resource [test/SubBean.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.ldap.core.LdapTemplate]: Circular reference involving containing bean 'subBean' - consider declaring the factory method as static for independence from its containing instance. Factory method 'setLdapTemplate' threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:656)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:484)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1290)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1210)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640)
... 19 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.ldap.core.LdapTemplate]: Circular reference involving containing bean 'subBean' - consider declaring the factory method as static for independence from its containing instance. Factory method 'setLdapTemplate' threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651)
... 32 more
Caused by: java.lang.NullPointerException
at test.SubBean.setLdapTemplate(SubBean.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
... 33 more
This is because this.string isn't set at int separatorLocation = this.string.indexOf('/', 8); in SubBean.java. I would need to be able to set string in a constructor (which Spring doesn't allow in managed beans) or autowire ldapTemplate after I've set the object properties manually.
Do not use #Bean in a #Service class. #Bean methods belong in #Configuration classes.
Move the method, so it can be called before Spring tries to autowire the ldapTemplate field.

Error creating bean with name 'projectingArgumentResolverBeanPostProcessor'

Im setting my web security in my project , but i see an error.
this is the error
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'projectingArgumentResolverBeanPostProcessor'
defined in class path resource
[org/springframework/data/web/config/ProjectingArgumentResolverRegistrar.class]:
BeanPostProcessor before instantiation of bean failed; nested
exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'metaDataSourceAdvisor': Cannot resolve
reference to bean 'methodSecurityMetadataSource' while setting
constructor argument; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'methodSecurityMetadataSource' defined in
class path resource
[org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfiguration.class]:
Bean instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate
[org.springframework.security.access.method.MethodSecurityMetadataSource]:
Factory method 'methodSecurityMetadataSource' threw exception; nested
exception is java.lang.IllegalStateException: In the composition of
all global method configuration, no annotation support was actually
activated at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:510)
~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE] at
org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE] at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE] at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE] at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:204)
~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE] at
org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(PostProcessorRegistrationDelegate.java:240)
~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE] at
org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:721)
~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE] at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:534)
~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE] at
org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142)
~[spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE] at
org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775)
[spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE] at
org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
[spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE] at
org.springframework.boot.SpringApplication.run(SpringApplication.java:316)
[spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE] at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1260)
[spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE] at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1248)
[spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE] at
com.supermarket.SupermarketApplication.main(SupermarketApplication.java:19)
[classes/:na]
my cod is :
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
#Autowired
private Environment env;
#Autowired
private UserSecurityService usersecurityservice;
private BCryptPasswordEncoder passwordencoder(){
return SecurityUtility.passwordEncoder();
}
private static final String[]PUBLIC_MATCHES = {
"/css/**",
"/js/**",
"/img/**",
"/signUp",
"/",
"/newUser",
"/forgetPassword",
"/login",
"/fonts/**",
"/bookshelf/**",
"/bookDetail/**",
"/hours",
"/faq",
"/searchByCategory",
"/searchBook"
};
#Override
protected void configure(HttpSecurity http)throws Exception{
http
.authorizeRequests().
/*antMatchers("/**").*/
antMatchers(PUBLIC_MATCHES).
permitAll().anyRequest().authenticated();
http
.csrf().disable().cors().disable()
.formLogin().failureUrl("/login?error")
.defaultSuccessUrl("/")
.successForwardUrl("/login")
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/?logout").deleteCookies("remember-me").permitAll()
.and()
.rememberMe();
}
#Autowired
public void configureGlobal (AuthenticationManagerBuilder auth) throws Exception{
auth.userDetailsService(usersecurityservice).passwordEncoder(passwordencoder());
}
}
userSecurity class is:
#Service
public class UserSecurityService implements UserDetailsService {
#Autowired()
private UserRepository userRepository;
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// TODO Auto-generated method stub
try{
}catch(Exception ex){
System.out.println("Error acoured hear:");
}
User user=userRepository.findByUsername(username);
if(null==user){
throw new UsernameNotFoundException("Username not found");
}
return user;
}
When i delete '#EnableGlobalMethodSecurity' annotation program run correctly
I had used this cod before and it worked correctly.
Did you update spring recently? In previous versions it was ok to have a null MethodSecurityMetadataSource, but now they added this check where if you don't have at least one method security metadata source enabled, they throw the exception that you are getting ("In the composition of all global method configuration, no annotation support was actually activated"). This happened to me when I updated from spring 5.0.7 to 5.1.5. Here is the issue where this change was discussed
To fix it, either enable one of the metadata sources in the #EnableGlobalMethodSecurity annotation properties, or, if like me, you are using some kind of GlobalMethodSecurityConfiguration, make sure the method customMethodSecurityMetadataSource returns not-null
You are having this issue because you have not annotation correctly. You should add it like this: #EnableGlobalMethodSecurity(prePostEnabled = true)

Spring boot : delegateBuilder cannot be null on autowiring authenticationManager in custom UserDetailsService

Hi i'm new to spring boot and trying implement the security to my rest apis.
i'm using spring boot 2.0.7.release
i have configures my WebSecurityConfig as following
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Resource(name = "userService")
private UserDetailsService userDetailsService;
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(encoder());
}
#Bean
public JwtAuthenticationFilter authenticationTokenFilterBean() throws Exception {
return new JwtAuthenticationFilter();
}
#Bean
public PasswordEncoder encoder(){
PasswordEncoder encoder = new CustomPasswordEncoder();
return encoder;
}
....
}
I have add the resource name so that i can point the to custom userDetailsService.
I have tried configuring authenticationManager Bean by came and pointing the bean by Qualifier authenticationManager bean still it the error remains same.
my pom.xml looks like for security
......
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
......
and my implemented UserServiceImpl is
#Service(value = "userService")
public class UserServiceImpl implements UserService, UserDetailsService {
#Autowired
private UserDAOService userDao;
#Autowired
private AuthenticationManager authenticationManager;
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userDao.findByUsername(username);
if(user == null){
throw new UsernameNotFoundException("Invalid username or password.");
}
return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), getAuthority());
}
#Override
public String login(LoginUser user) {
// valid user if it exits then do the following
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));
//generate the token and do other process.
}
following are the error logs. i have provided only mail errors
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'webSecurityConfig': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'authenticationManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authenticationManager' defined in class path resource [com/saikrishna/security/config/WebSecurityConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.AuthenticationManager]: Circular reference involving containing bean 'webSecurityConfig' - consider declaring the factory method as static for independence from its containing instance. Factory method 'authenticationManagerBean' threw exception; nested exception is java.lang.IllegalArgumentException: delegateBuilder cannot be null
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'authenticationManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authenticationManager' defined in class path resource [com/saikrishna/security/config/WebSecurityConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.AuthenticationManager]: Circular reference involving containing bean 'webSecurityConfig' - consider declaring the factory method as static for independence from its containing instance. Factory method 'authenticationManagerBean' threw exception; nested exception is java.lang.IllegalArgumentException: delegateBuilder cannot be null
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authenticationManager' defined in class path resource [com/saikrishna/security/config/WebSecurityConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.AuthenticationManager]: Circular reference involving containing bean 'webSecurityConfig' - consider declaring the factory method as static for independence from its containing instance. Factory method 'authenticationManagerBean' threw exception; nested exception is java.lang.IllegalArgumentException: delegateBuilder cannot be null
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.AuthenticationManager]: Circular reference involving containing bean 'webSecurityConfig' - consider declaring the factory method as static for independence from its containing instance. Factory method 'authenticationManagerBean' threw exception; nested exception is java.lang.IllegalArgumentException: delegateBuilder cannot be null
Caused by: java.lang.IllegalArgumentException: delegateBuilder cannot be null
at org.springframework.util.Assert.notNull(Assert.java:193) ~[spring-core-5.0.11.RELEASE.jar:5.0.11.RELEASE]
In order to help you better, it is better if you indicate which reference you are following to implement JWT mechansim.
Conceptually, this part of the source code is wrong:
#Override
public String login(LoginUser user) {
// valid user if it exits then do the following
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));
//generate the token and do other process.
}
See if the modifications below can help you
1) Consider using Java Config to declare your beans, in a seperate Configuration class
#Configuration
public class ServiceConfig{
#Bean
protected UserDAOService daoService()
{
return new UserDAOServiceImpl();
}
#Bean
protected UserDetailsService userDetailService( UserDAOService dao )
{
return new UserServiceImpl( dao );
}
#Bean
public PasswordEncoder encoder(){
PasswordEncoder encoder = new CustomPasswordEncoder();
return encoder;
}
#Bean
public JwtAuthenticationFilter authenticationTokenFilterBean() throws Exception{ {
return new JwtAuthenticationFilter();
}
}
2) Modification to your WebSecurityConfig
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
#Autowired
private PasswordEncoder passwordEncoder;
#Override
protected void configure( AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService( userDetailsService ).passwordEncoder( passwordEncoder );
}
}

My bean allways returns null after injection

Here is my code, I don't know why my bean MouvementToMapItemProcessor is not injected, it's always null in constructor
#Autowired
private MouvementToMapItemProcessor mvts;
private Iterator it;
public InMemoryMouvementReader() {
it = mvts.getMouvmentFileRowMap().entrySet().iterator();
}
Here is my configuration class:
#Configuration
#EnableBatchProcessing
public class BatchConfiguration {
public BatchConfiguration() {
}
#Bean
public ItemReader<MouvementFileRow> mouvementMapReader() {
return new InMemoryMouvementReader();
}
#Bean
public ItemProcessor<MouvementFileRow, MouvementFileRow> mouvementMapProcessor() {
return new MouvementToMapItemProcessor();
}
#Bean
public Step generateDemmandeCommunication() {
return stepBuilderFactory.get("generateDemmandeCommunication")
.<MouvementFileRow, DemandeCommunication>chunk(10)
.faultTolerant().skipLimit(Integer.MAX_VALUE).skip(CustomReaderSkipException.class)
.reader(mouvementMapReader())
.processor(mouvementProcessor())
.writer(demandeCommunicationItemWriter())
.listener(customStepListener())
.build();
}
public class InMemoryMouvementReader implements ItemReader<MouvementFileRow> {
#Autowired
private MouvementToMapItemProcessor mvts;
private Iterator it;
public InMemoryMouvementReader() {
it = mvts.getMouvmentFileRowMap().entrySet().iterator();
}
private void initialize() {
}
#Override
public MouvementFileRow read() throws Exception {
if (it.hasNext()) {
return mvts.getMouvmentFileRowMap().get(it.next());
} else return null;
}
}
#Component
public class MouvementToMapItemProcessor implements ItemProcessor<MouvementFileRow, MouvementFileRow> {
private static final Logger log = LoggerFactory.getLogger(MouvementToMapItemProcessor.class);
private Map<Long, MouvementFileRow> mouvmentFileRowMap;
public MouvementToMapItemProcessor() {
mouvmentFileRowMap = new HashMap<Long, MouvementFileRow>();
}
#Override
public MouvementFileRow process(final MouvementFileRow mouvement) throws Exception {
........
return null;
}
public Map<Long, MouvementFileRow> getMouvmentFileRowMap() {
return mouvmentFileRowMap;
}
My stack trace
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
11:55:29.139 [restartedMain] ERROR o.s.boot.SpringApplication - Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mouvementMapReader' defined in class path resource [fr/gouv/justice/spark/fileToBaseBatch/BatchConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.batch.item.ItemReader]: Factory method 'mouvementMapReader' threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107)
at fr.gouv.justice.spark.fileToBaseBatch.Application.main(Application.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.batch.item.ItemReader]: Factory method 'mouvementMapReader' threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
... 22 common frames omitted
Caused by: java.lang.NullPointerException: null
at fr.gouv.justice.spark.fileToBaseBatch.readers.InMemoryMouvementReader.(InMemoryMouvementReader.java:19)
at fr.gouv.justice.spark.fileToBaseBatch.BatchConfiguration.mouvementMapReader(BatchConfiguration.java:74)
at fr.gouv.justice.spark.fileToBaseBatch.BatchConfiguration$$EnhancerBySpringCGLIB$$e3e5804e.CGLIB$mouvementMapReader$34()
at fr.gouv.justice.spark.fileToBaseBatch.BatchConfiguration$$EnhancerBySpringCGLIB$$e3e5804e$$FastClassBySpringCGLIB$$8f516405.invoke()
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358)
at fr.gouv.justice.spark.fileToBaseBatch.BatchConfiguration$$EnhancerBySpringCGLIB$$e3e5804e.mouvementMapReader()
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
... 23 common frames omitted
Your MouvementToMapItemProcessor is not injected into InMemoryMouvementReader until after it is constructed, which is what causes the constructor to fail with a NullPointerException. Use constructor injection instead:
#Autowired
public InMemoryMouvementReader(MouvementToMapItemProcessor mvts) {
this.mvts = mvts;
it = mvts.getMouvmentFileRowMap().entrySet().iterator();
}
and
#Bean
public ItemReader<MouvementFileRow> mouvementMapReader(MouvementToMapItemProcessor mvts) {
return new InMemoryMouvementReader(mvts);
}
and
#Bean
public Step generateDemmandeCommunication(InMemoryMouvementReader reader, MouvementToMapItemProcessor mvts) {
return stepBuilderFactory.get("generateDemmandeCommunication")
.<MouvementFileRow, DemandeCommunication>chunk(10)
.faultTolerant().skipLimit(Integer.MAX_VALUE).skip(CustomReaderSkipException.class)
.reader(reader)
.processor(mvts)
.writer(demandeCommunicationItemWriter())
.listener(customStepListener())
.build();
}

Spring security error in native spring class during OpenId Client Implementation

MY app Initializer
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
#Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return new Class[]{ApplicationConfiguration.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String[]{"/"};
}
}
ApplicationConfiguration.java
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "base package name")
public class ApplicationConfiguration extends WebMvcConfigurerAdapter {
private static final Logger LOGGER = LoggerFactory
.getLogger(ApplicationConfiguration.class);
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/secured/resources/**").addResourceLocations(
"/secured/resources/");
}
#Override
public void addInterceptors(InterceptorRegistry intRegistry) {
UserInfoInterceptor interceptor = new UserInfoInterceptor();
intRegistry.addInterceptor(interceptor);
}
#Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public InternalResourceViewResolver jspViewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setPrefix("/secured/resources/html/");
bean.setSuffix(".html");
bean.setOrder(1);
return bean;
}
#Bean(name = "messageSource")
public ReloadableResourceBundleMessageSource getMessageSource() {
ReloadableResourceBundleMessageSource resource = new ReloadableResourceBundleMessageSource();
resource.setBasename("classpath:messages");
resource.setDefaultEncoding("UTF-8");
return resource;
}
#Bean
public PropertyPlaceholderConfigurer getPropertyPlaceHolder() {
PropertyPlaceholderConfigurer prop = new PropertyPlaceholderConfigurer();
Resource[] resource = new ClassPathResource[] { new ClassPathResource(
"application.properties") };
prop.setLocations(resource);
return prop;
}
}
SecurityConfiguration.java
#Configuration
#EnableWebSecurity
//#Order(Ordered.HIGHEST_PRECEDENCE)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
#Bean
#Override
public AuthenticationManager authenticationManager() throws Exception{
return super.authenticationManager();
}
#Override
public void configure(WebSecurity web) throws Exception {
DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler();
web.expressionHandler(handler).ignoring().antMatchers("/resources/**");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(getopenIdConnectAuthenticationFilter(),
AbstractPreAuthenticatedProcessingFilter.class);
http.exceptionHandling().authenticationEntryPoint(
openIdAuthenticationEntryPoint());
http.authorizeRequests().antMatchers("/**");
http.logout();
// http.authenticationProvider(getAuthenticationProvider());
}
#Bean
public void setObjectPostProcessor(ObjectPostProcessor<Object> objectPostProcessor) {
super.setObjectPostProcessor(objectPostProcessor);
}
}
MethodSecurityConfiguration.java
#Configuration
#EnableGlobalMethodSecurity(securedEnabled=true,prePostEnabled = true, proxyTargetClass = true)
public class MethodSecurityConfiguration {
#Autowired
SecurityConfiguration secConfig;
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.authenticationProvider(secConfig.getAuthenticationProvider());
}
}
SpringSecurityInitializer.java
public class SpringSecurityInitializer extends
AbstractSecurityWebApplicationInitializer {
}
I have been trying to implement open id connect Mitreid client and have configured the security config as given above.Configurations based on MITREID Client
When I deploy I get the below error
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1904) [jboss-msc-1.2.2.Final.jar:1.2.2.Final]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [rt.jar:1.8.0_40]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [rt.jar:1.8.0_40]
at java.lang.Thread.run(Thread.java:745) [rt.jar:1.8.0_40]
Caused by: java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalStateException: org.springframework.security.config.annotation.ObjectPostProcessor is a required bean. Ensure you have used #EnableWebSecurity and #Configuration
at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:222)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:87)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.start(UndertowDeploymentService.java:72)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1948) [jboss-msc-1.2.2.Final.jar:1.2.2.Final]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1881) [jboss-msc-1.2.2.Final.jar:1.2.2.Final]
... 3 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalStateException: org.springframework.security.config.annotation.ObjectPostProcessor is a required bean. Ensure you have used #EnableWebSecurity and #Configuration
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1119)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1014)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at io.undertow.servlet.core.ApplicationListeners.contextInitialized(ApplicationListeners.java:173)
at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:193)
... 7 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalStateException: org.springframework.security.config.annotation.ObjectPostProcessor is a required bean. Ensure you have used #EnableWebSecurity and #Configuration
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
... 25 more
Caused by: java.lang.IllegalStateException: org.springframework.security.config.annotation.ObjectPostProcessor is a required bean. Ensure you have used #EnableWebSecurity and #Configuration
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$1.postProcess(WebSecurityConfigurerAdapter.java:78)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.getHttp(WebSecurityConfigurerAdapter.java:175)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:283)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:68)
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.init(AbstractConfiguredSecurityBuilder.java:367)
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:320)
at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:39)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:92)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$96834940.CGLIB$springSecurityFilterChain$3(<generated>)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$96834940$$FastClassBySpringCGLIB$$7ad1d6c4.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:309)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$96834940.springSecurityFilterChain(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.8.0_40]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) [rt.jar:1.8.0_40]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.8.0_40]
at java.lang.reflect.Method.invoke(Method.java:497) [rt.jar:1.8.0_40]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
... 26 more
Have included relevant part of the security configuration.Tried to override ObjectPostProcessor as suggested here but am getting same error. Note: Am not using spring boot or spring loaded.
I am not able to figure out the mistake I am making.Any help is greatly appreciated.Thanks in advance.
Spring version : 4.1.6.RELEASE
Spring security verison : 4.0.1.RELEASE
The jwtstore configuration was causing an issue with the spring security configuration.Moved the relevant code to another class and it got working.

Categories