I have probem with spring application. I trying connect jwt with my rest api app. When I try run app, I get error and I don't know where I make mistake. Thanks for all answers.
Console log
2020-10-02 18:09:10.938 WARN 2052 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-10-02 18:09:10.955 INFO 2052 --- [ task-1] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.21.Final
2020-10-02 18:09:11.027 WARN 2052 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: 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.RuntimeException: Could not postProcess org.springframework.security.authentication.dao.DaoAuthenticationProvider#3eb3232b of type class org.springframework.security.authentication.dao.DaoAuthenticationProvider
2020-10-02 18:09:11.027 INFO 2052 --- [ main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-10-02 18:09:11.051 INFO 2052 --- [ task-1] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-10-02 18:09:11.119 INFO 2052 --- [ task-1] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-10-02 18:09:11.223 INFO 2052 --- [ task-1] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-10-02 18:09:11.235 INFO 2052 --- [ task-1] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL55Dialect
2020-10-02 18:09:11.722 INFO 2052 --- [ task-1] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-10-02 18:09:11.730 INFO 2052 --- [ task-1] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-10-02 18:09:11.734 INFO 2052 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
2020-10-02 18:09:11.735 INFO 2052 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2020-10-02 18:09:11.744 INFO 2052 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
Exception in thread "task-2" org.springframework.beans.factory.BeanCreationNotAllowedException: Error creating bean with name 'springApplicationAdminRegistrar': Singleton bean creation not allowed while singletons of this factory are in destruction (Do not request a bean from a BeanFactory in a destroy method implementation!)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:220)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207)
at org.springframework.context.event.AbstractApplicationEventMulticaster.retrieveApplicationListeners(AbstractApplicationEventMulticaster.java:245)
at org.springframework.context.event.AbstractApplicationEventMulticaster.getApplicationListeners(AbstractApplicationEventMulticaster.java:197)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:134)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:404)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:361)
at org.springframework.boot.autoconfigure.orm.jpa.DataSourceInitializedPublisher.publishEventIfRequired(DataSourceInitializedPublisher.java:99)
at org.springframework.boot.autoconfigure.orm.jpa.DataSourceInitializedPublisher.access$100(DataSourceInitializedPublisher.java:50)
at org.springframework.boot.autoconfigure.orm.jpa.DataSourceInitializedPublisher$DataSourceSchemaCreatedPublisher.lambda$postProcessEntityManagerFactory$0(DataSourceInitializedPublisher.java:200)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:835)
2020-10-02 18:09:11.746 INFO 2052 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2020-10-02 18:09:11.759 INFO 2052 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-10-02 18:09:11.772 ERROR 2052 --- [ main] o.s.boot.SpringApplication : Application run failed
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.RuntimeException: Could not postProcess org.springframework.security.authentication.dao.DaoAuthenticationProvider#3eb3232b of type class org.springframework.security.authentication.dao.DaoAuthenticationProvider
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:655) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:483) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1336) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1176) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:556) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:311) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:897) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:879) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:551) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) ~[spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) ~[spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) ~[spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) ~[spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) ~[spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) ~[spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at com.joledzki.baserest.BaserestApplication.main(BaserestApplication.java:13) ~[classes/:na]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.RuntimeException: Could not postProcess org.springframework.security.authentication.dao.DaoAuthenticationProvider#3eb3232b of type class org.springframework.security.authentication.dao.DaoAuthenticationProvider
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.RuntimeException: Could not postProcess org.springframework.security.authentication.dao.DaoAuthenticationProvider#3eb3232b of type class org.springframework.security.authentication.dao.DaoAuthenticationProvider
at org.springframework.security.config.annotation.configuration.AutowireBeanFactoryObjectPostProcessor.postProcess(AutowireBeanFactoryObjectPostProcessor.java:72) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.security.config.annotation.SecurityConfigurerAdapter$CompositeObjectPostProcessor.postProcess(SecurityConfigurerAdapter.java:122) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.security.config.annotation.SecurityConfigurerAdapter.postProcess(SecurityConfigurerAdapter.java:81) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.security.config.annotation.authentication.configurers.userdetails.AbstractDaoAuthenticationConfigurer.configure(AbstractDaoAuthenticationConfigurer.java:87) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.security.config.annotation.authentication.configurers.userdetails.DaoAuthenticationConfigurer.configure(DaoAuthenticationConfigurer.java:32) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.security.config.annotation.authentication.configurers.userdetails.AbstractDaoAuthenticationConfigurer.configure(AbstractDaoAuthenticationConfigurer.java:37) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.configure(AbstractConfiguredSecurityBuilder.java:383) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:329) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:41) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.authenticationManager(WebSecurityConfigurerAdapter.java:272) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.getHttp(WebSecurityConfigurerAdapter.java:202) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:322) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:94) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at com.joledzki.baserest.config.SecurityConfig$$EnhancerBySpringCGLIB$$fcfee8a9.init(<generated>) ~[classes/:na]
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.init(AbstractConfiguredSecurityBuilder.java:370) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:324) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:41) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:104) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:567) ~[na:na]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
... 23 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authentication.dao.DaoAuthenticationProvider#3eb3232b': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: A UserDetailsService must be set
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1794) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:406) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.security.config.annotation.configuration.AutowireBeanFactoryObjectPostProcessor.postProcess(AutowireBeanFactoryObjectPostProcessor.java:67) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
... 45 common frames omitted
Caused by: java.lang.IllegalArgumentException: A UserDetailsService must be set
at org.springframework.util.Assert.notNull(Assert.java:201) ~[spring-core-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.doAfterPropertiesSet(DaoAuthenticationProvider.java:100) ~[spring-security-core-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.afterPropertiesSet(AbstractUserDetailsAuthenticationProvider.java:123) ~[spring-security-core-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1853) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1790) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
... 47 common frames omitted
application.properties
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/baserest
spring.datasource.username=root
spring.datasource.password=
spring.application.admin.enabled=true
spring.application.admin.jmx-name=org.springframework.boot:type=Admin,name=BaserestApplication
SecurityConfig.java
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private AuthenticationConverter authenticationConverter;
private UserServiceImpl userService;
public SecurityConfig() {
}
#Bean
protected PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable();
http.authorizeRequests()
.antMatchers("/user").permitAll()
.and()
.addFilter(new AuthenticationFilter(authenticationManager()))
.addFilter(new AuthorizationFilter(authenticationManager()))
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
AuthenticationFilter.java
public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private AuthenticationManager authenticationManager;
public AuthenticationFilter(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
setFilterProcessesUrl("/login");
}
#Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
try {
User creds = new ObjectMapper().readValue(request.getInputStream(),User.class);
return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(creds.getUsername(), creds.getPassword(), new ArrayList<>()));
} catch (IOException e) {
throw new RuntimeException("Could not read request " + e);
}
}
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain, Authentication authentication){
String token = Jwts.builder()
.setSubject(((User)authentication.getPrincipal()).getUsername())
.setExpiration(new Date(System.currentTimeMillis() + 864_000_000))
.signWith(SignatureAlgorithm.HS256, "aaa".getBytes())
.compact();
response.addHeader("Authorization", "Bearer "+token);
}
}
AuthorizationFilter.java
public class AuthorizationFilter extends BasicAuthenticationFilter {
public AuthorizationFilter(AuthenticationManager authenticationManager) {
super(authenticationManager);
}
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
String header = request.getHeader("Authorization");
if(header == null || !header.startsWith("Bearer")){
chain.doFilter(request,response);
return;
}
UsernamePasswordAuthenticationToken authenticationToken = getAuthentication(request);
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
chain.doFilter(request,response);
}
private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request){
String token = request.getHeader("Authorization");
if(token != null){
String user = Jwts.parser().setSigningKey("aaa".getBytes())
.parseClaimsJws(token.replace("Bearer ",""))
.getBody()
.getSubject();
if(user != null){
return new UsernamePasswordAuthenticationToken(user,null, new ArrayList<>());
}
else return null;
}
else {
return null;
}
}
}
I trying to fix it for 2 hours, but I still don't know where I'm making a mistake
Your problem is this:
Caused by: java.lang.IllegalArgumentException: A UserDetailsService must be set
at org.springframework.util.Assert.notNull(Assert.java:201) ~[spring-core-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.doAfterPropertiesSet(DaoAuthenticationProvider.java:100) ~[spring-security-core-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.afterPropertiesSet(AbstractUserDetailsAuthenticationProvider.java:123) ~[spring-security-core-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1853) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1790) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
... 47 common frames omitted
You need to set UserDetailsService in your class SecurityConfig extends WebSecurityConfigurerAdapter.
Do one thing, create a class which implements UserDetailsService and then use UserServiceImpl in that.
Ultimately you need UserDetailsService in the SecurityConfig class.
Related
I work on simple authentication app using spring security & encounter by an access denied error. I must mention that registration works perfectly & I've already created 1 record with bcrypted password but on login I'm failed to understand that what did I miss. Grateful for the help
User.java
public class User implements UserDetails {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
private String username;
private String email;
private String password;
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JsonIgnore
private Set<UserRole> userRoles = new HashSet<>();
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Set<GrantedAuthority>authorities = new HashSet<>();
userRoles.forEach(ur -> authorities.add(new
Authority(ur.getRole().getName())));
return authorities;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
}
SecurityConfig
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private UserSecurityService userSecurityService;
public SecurityConfig(UserSecurityService userSecurityService) {
this.userSecurityService = userSecurityService;
}
#Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/api/**").permitAll()
.antMatchers("/api/auth/**").permitAll()
.anyRequest()
.authenticated()
.and()
.httpBasic();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws
Exception {
auth.userDetailsService(userSecurityService).passwordEncoder
(passwordEncoder());
}
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws
Exception {return super.authenticationManagerBean();
}
}
UserSecurityService (loaduser)
#Service
public class UserSecurityService implements UserDetailsService {
private static final Logger LOG =
LoggerFactory.getLogger(UserSecurityService.class);
#Autowired
private UserRepository userRepository;
#Override
public UserDetails loadUserByUsername(String username) throws
UsernameNotFoundException {
User user = userRepository.findUserByUsername(username);
if (null == user) {
LOG.warn("Username {} not found", username);
throw new UsernameNotFoundException("Username " + username + "
not found");
}
return user;
}
}
AuthController
#RestController
#RequestMapping("/api/auth")
public class AuthController {
#Autowired
private AuthenticationManager authenticationManager;
#Autowired
private UserRepository userRepository;
#Autowired
private RoleRepository roleRepository;
#Autowired
private PasswordEncoder passwordEncoder;
#Autowired
private UserService userService;
#PostMapping("/register")
public ResponseEntity<User> register(#RequestBody User user) throws Exception {
return new ResponseEntity<>(userService.register(user), HttpStatus.OK);
}
#PostMapping("/login")
public ResponseEntity<String> login(#RequestBody String username, String password ) throws
Exception {
Authentication authentication = authenticationManager.authenticate(new
UsernamePasswordAuthenticationToken(
username, password
));
SecurityContextHolder.getContext().setAuthentication(authentication);
return new ResponseEntity<>("User signed -in succesfully", HttpStatus.OK);
}
}
Error
2022-01-14 14:49:13.604 INFO 24600 --- [ restartedMain]
c.kash.bankingAPI.BankingApiApplication : Starting
BankingApiApplication using Java 11.0.12 on LAPTOP-BQ48GM36 with PID
24600 (B:\spring\bankingAPI\target\classes started by The Kash in
B:\spring\bankingAPI)
2022-01-14 14:49:13.605 INFO 24600 --- [ restartedMain]
c.kash.bankingAPI.BankingApiApplication : No active profile set,
falling back to default profiles: default
2022-01-14 14:49:13.673 INFO 24600 --- [ restartedMain]
.e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults
active! Set 'spring.devtools.add-properties' to 'false' to disable
2022-01-14 14:49:13.674 INFO 24600 --- [ restartedMain]
.e.DevToolsPropertyDefaultsPostProcessor : For additional web related
logging consider setting the 'logging.level.web' property to 'DEBUG'
2022-01-14 14:49:14.557 INFO 24600 --- [ restartedMain]
.s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data
JPA
repositories in DEFAULT mode.
2022-01-14 14:49:14.646 INFO 24600 --- [ restartedMain]
.s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data
repository scanning in 74 ms. Found 2 JPA repository interfaces.
2022-01-14 14:49:15.876 INFO 24600 --- [ restartedMain]
o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with
port(s): 8088 (http)
2022-01-14 14:49:15.890 INFO 24600 --- [ restartedMain]
o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-01-14 14:49:15.890 INFO 24600 --- [ restartedMain]
org.apache.catalina.core.StandardEngine : Starting Servlet engine:
[Apache Tomcat/9.0.56]
2022-01-14 14:49:16.008 INFO 24600 --- [ restartedMain] o.a.c.c.C.
[Tomcat].[localhost].[/] : Initializing Spring embedded
WebApplicationContext
2022-01-14 14:49:16.008 INFO 24600 --- [ restartedMain]
w.s.c.ServletWebServerApplicationContext : Root
WebApplicationContext:
initialization completed in 2334 ms
2022-01-14 14:49:16.264 INFO 24600 --- [ restartedMain]
o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing
PersistenceUnitInfo [name: default]
2022-01-14 14:49:16.332 INFO 24600 --- [ restartedMain]
org.hibernate.Version : HHH000412: Hibernate ORM
core
version 5.6.3.Final
2022-01-14 14:49:16.542 INFO 24600 --- [ restartedMain]
o.hibernate.annotations.common.Version : HCANN000001: Hibernate
Commons Annotations {5.1.2.Final}
2022-01-14 14:49:16.661 INFO 24600 --- [ restartedMain]
com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-01-14 14:49:17.128 INFO 24600 --- [ restartedMain]
com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start
completed.
2022-01-14 14:49:17.145 INFO 24600 --- [ restartedMain]
org.hibernate.dialect.Dialect : HHH000400: Using dialect:
org.hibernate.dialect.MySQL57Dialect
2022-01-14 14:49:18.469 INFO 24600 --- [ restartedMain]
o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using
JtaPlatform implementation:
[org.hibernate.engine.transaction.jta.platform.internal.
NoJtaPlatform]
2022-01-14 14:49:18.478 INFO 24600 --- [ restartedMain]
j.LocalContainerEntityManagerFactoryBean : Initialized JPA
EntityManagerFactory for persistence unit 'default'
2022-01-14 14:49:19.173 WARN 24600 --- [ restartedMain]
JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is
enabled by default. Therefore, database queries may be performed
during
view rendering. Explicitly configure spring.jpa.open-in-view to
disable
this warning
2022-01-14 14:49:19.453 DEBUG 24600 --- [ restartedMain]
edFilterInvocationSecurityMetadataSource : Adding web access control
expression [permitAll] for Ant [pattern='/api/**', GET]
2022-01-14 14:49:19.455 DEBUG 24600 --- [ restartedMain]
edFilterInvocationSecurityMetadataSource : Adding web access control
expression [permitAll] for Ant [pattern='/api/auth/**']
2022-01-14 14:49:19.456 DEBUG 24600 --- [ restartedMain]
edFilterInvocationSecurityMetadataSource : Adding web access control
expression [authenticated] for any request
2022-01-14 14:49:19.468 INFO 24600 --- [ restartedMain]
o.s.s.web.DefaultSecurityFilterChain : Will secure any request
with
[org.springframework.security.web.context.request.async.
WebAsyncManagerIntegrationFilter#4b607819,
org.springframework.security.web.context.SecurityContextPersistence
Filter#146dcdcf,
org.springframework.security.web.header.HeaderWriterFilter#74f0174b,
org.springframework.security.web.authentication.logout.
LogoutFilter#839ff7f,
org.springframework.security.web.authentication.www.
BasicAuthenticationFilter#4f78b9a2,
org.springframework.security.web.savedrequest.
RequestCacheAwareFilter#7e2b3eef,
org.springframework.security.web.servletapi.SecurityContextHolder
AwareRequestFilter#1996d59a,
org.springframework.security.web.authentication.Anonymous
AuthenticationFilter#d82cd0b,
org.springframework.security.web.session.SessionManagement
Filter#47842f0b,
org.springframework.security.web.access.ExceptionTranslation
Filter#6fdc8d32, org.springframework.security.web.access.intercept.
FilterSecurityInterceptor#3619bc38]
2022-01-14 14:49:19.922 INFO 24600 --- [ restartedMain]
o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is
running
on port 35729
2022-01-14 14:49:19.959 INFO 24600 --- [ restartedMain]
o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s):
8088 (http) with context path ''
2022-01-14 14:49:19.970 INFO 24600 --- [ restartedMain]
c.kash.bankingAPI.BankingApiApplication : Started
BankingApiApplication
in 6.835 seconds (JVM running for 7.645)
2022-01-14 14:49:51.914 INFO 24600 --- [nio-8088-exec-2] o.a.c.c.C.
[Tomcat].[localhost].[/] : Initializing Spring
DispatcherServlet
'dispatcherServlet'
2022-01-14 14:49:51.915 INFO 24600 --- [nio-8088-exec-2]
o.s.web.servlet.DispatcherServlet : Initializing Servlet
'dispatcherServlet'
2022-01-14 14:49:51.916 INFO 24600 --- [nio-8088-exec-2]
o.s.web.servlet.DispatcherServlet : Completed initialization
in
1 ms
2022-01-14 14:49:51.931 DEBUG 24600 --- [nio-8088-exec-2]
o.s.security.web.FilterChainProxy : Securing POST /api/auth/login
2022-01-14 14:49:51.936 DEBUG 24600 --- [nio-8088-exec-2]
s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder
to
empty SecurityContext
2022-01-14 14:49:51.939 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder
to
anonymous SecurityContext
2022-01-14 14:49:51.940 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.w.session.SessionManagementFilter : Request requested invalid
session id 1E5E812360CC1B8291311CA85ACAC55A
2022-01-14 14:49:51.945 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.w.a.i.FilterSecurityInterceptor : Authorized filter
invocation
[POST /api/auth/login] with attributes [permitAll]
2022-01-14 14:49:51.946 DEBUG 24600 --- [nio-8088-exec-2]
o.s.security.web.FilterChainProxy : Secured POST
/api/auth/login
Hibernate: select user0_.id as id1_7_, user0_.email as email2_7_,
user0_.name as name3_7_, user0_.password as password4_7_,
user0_.primary_account_id as primary_6_7_, user0_.savings_account_id
as
savings_7_7_, user0_.username as username5_7_ from users user0_ where
user0_.username=?
2022-01-14 14:49:52.305 WARN 24600 --- [nio-8088-exec-2]
c.k.b.s.serviceImpl.UserSecurityService : Username {
"username": "seeshee",
"password": "12345"
} not found
2022-01-14 14:49:52.313 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.a.dao.DaoAuthenticationProvider : Failed to find user '{
"username": "seeshee",
"password": "1234"
}'
2022-01-14 14:49:52.698 WARN 24600 --- [nio-8088-exec-2]
o.a.c.util.SessionIdGeneratorBase : Creation of SecureRandom
instance for session ID generation using [SHA1PRNG] took [364]
milliseconds.
2022-01-14 14:49:52.700 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.w.s.HttpSessionRequestCache : Saved request
http://localhost:8088/api/auth/login to session
2022-01-14 14:49:52.701 DEBUG 24600 --- [nio-8088-exec-2]
s.w.a.DelegatingAuthenticationEntryPoint : Trying to match using
Reque
tHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expec
edHeaderValue=XMLHttpRequest]
2022-1-14 14:49:52.701 DEBUG 24600 --- [nio-8088-exec-2]
s.w.a.DelegatingAuthenticationEntryPoint : No match found. Using
default entry point
org.springframework.security.web.authentication.www.
BasicAuthenticationEntryPoint#691634d7
2022-01-14 14:49:52.702 DEBUG 24600 --- [nio-8088-exec-2]
w.c.HttpSessionSecurityContextRepository : Did not store empty
SecurityContext
2022-01-14 14:49:52.702 DEBUG 24600 --- [nio-8088-exec-2]
w.c.HttpSessionSecurityContextRepository : Did not store empty
SecurityContext
2022-01-14 14:49:52.702 DEBUG 24600 --- [nio-8088-exec-2]
s.s.w.c.SecurityContextPersistenceFilter : Cleared
SecurityContextHolder
to complete request
2022-01-14 14:49:52.705 DEBUG 24600 --- [nio-8088-exec-2]
o.s.security.web.FilterChainProxy : Securing POST /error
2022-01-14 14:49:52.705 DEBUG 24600 --- [nio-8088-exec-2]
s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder
to
empty SecurityContext
2022-01-14 14:49:52.706 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder
to
anonymous SecurityContext
2022-01-14 14:49:52.706 DEBUG 24600 --- [nio-8088-exec-2]
o.s.security.web.FilterChainProxy : Secured POST /error
2022-01-14 14:49:52.721 DEBUG 24600 --- [nio-8088-exec-2]
a.DefaultWebInvocationPrivilegeEvaluator : filter invocation [/error]
denied for AnonymousAuthenticationToken [Principal=anonymousUser,
Credentials=[PROTECTED], Authenticated=true,
Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1,
SessionId=BAFE9322A4A2705325C4B6540915129E], Granted Authorities=
[ROLE_ANONYMOUS]]
org.springframework.security.access.AccessDeniedException: Access is
denied
at
org.springframework.security.access.vote.AffirmativeBased.
decide(AffirmativeBased.java:73)
~[spring-security-core-5.6.1.jar:5.6.1]
at org.springframework.security.web.access.
DefaultWebInvocationPrivilegeEvaluator.isAllowed
(DefaultWe
bInvocationPrivilegeEvaluator.java:100) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.access.
DefaultWebInvocationPrivilegeEvaluator.isAllowed
(DefaultWebInvocationPrivilegeEvaluator.java:67) ~[spring-security-
web-
5.6.1.jar:5.6.1]
at
org.springframework.boot.web.servlet.filter.ErrorPageSecurityFilter.
isAllowed
(ErrorPageSecurityFilter.java:84) ~[spring-boot-2.6.2.jar:2.6.2]
at
org.springframework.boot.web.servlet.filter.ErrorPageSecurityFilter.
doFilter
(ErrorPageSecurityFilter.java:72) ~[spring-boot-2.6.2.jar:2.6.2]
at
org.springframework.boot.web.servlet.filter.ErrorPageSecurityFilter.
doFilter
(ErrorPageSecurityFilter.java:66) ~[spring-boot-2.6.2.jar:2.6.2]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(
ApplicationFilterChain.
java:189) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:162) ~
[tomcat-embed-core-9.0.56.jar:9.0.56]
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.
doFilter
(FilterChainProxy.jav
a:327) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.access.intercept.
FilterSecurityInterceptor.invoke
(FilterSecurityInterceptor.java:106) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.access.intercept.
FilterSecurityInterceptor.doFilter
(FilterSecurityInterceptor.java:81) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.access.
ExceptionTranslationFilter.doFilter
(ExceptionTranslationFilter.java:122) ~[spring-security-web-
5.6.1.jar:5.6.1]
at
org.springframework.security.web.access.ExceptionTranslationFilter.
doFilter
(ExceptionTranslationFilter.java:116) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.session.SessionManagementFilter
.doFilter
(SessionManagementFilter.java:87) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.session.SessionManagementFilter.
doFilter
(SessionManagementFilter.java:81) ~[spring-security-web-
5.6.1.jar:5.6.1]
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain
.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.authentication.
AnonymousAuthenticationFilter.doFilter
(AnonymousAuthenticationFilter.java:109) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.servletapi.
SecurityContextHolderAwareRequestFilter.
doFilter(SecurityContextHolderAwareRequestFilter.java:149) ~[spring-
security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.savedrequest.
RequestCacheAwareFilter.doFilter
(RequestCacheAwareFilter.java:63) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.web.filter.OncePerRequestFilter.doFilter
(OncePerRequestFilter.java:102) ~[spring-web-5.3.14.jar:5.3.14]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.authentication.logout.
LogoutFilter.doFilter
(LogoutFilter.java:103) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.authentication.logout.
LogoutFilter.doFilter
(LogoutFilter.java:89) ~[spring-security-web-5.6.1.jar:5.6.1]
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.
doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(
OncePerRequestFilter.java:102)
~[spring-web-5.3.14.jar:5.3.14]
at org.springframework.security.web.FilterChainProxy$VirtualFilter
Chain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at
org.springframework.security.web.context.SecurityContextPersistence
Filter.doFilter
(SecurityContextPersistenceFilter.java:110) ~[spring-security-web-
5.6.1.jar:5.6.1]
at
org.springframework.security.web.context.SecurityContextPersistence
Filter.doFilter
(SecurityContextPersistenceFilter.java:80) ~[spring-security-web-
5.6.1.jar:5.6.1]
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.
doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.web.filter.OncePerRequestFilter.doFilter
(OncePerRequestFilter.java:102) ~[spring-web-5.3.14.jar:5.3.14]
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.
doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy.doFilterInternal
(FilterChainProxy.java:211) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy.doFilter
(FilterChainProxy.java:183) ~[spring-security-web-5.6.1.jar:5.6.1]
at
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate
(DelegatingFilterProxy.java:354) ~[spring-web-5.3.14.jar:5.3.14]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter
(DelegatingFilterProxy.java:267) ~
[spring-web-5.3.14.jar:5.3.14]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:189) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:162) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at
org.springframework.web.filter.RequestContextFilter.doFilterInternal
(RequestContextFilter.java:100) ~[spring-web-5.3.14.jar:5.3.14]
at org.springframework.web.filter.OncePerRequestFilter.doFilter
(OncePerRequestFilter.java:117) ~[spring-web-5.3.14.jar:5.3.14]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:189) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:162) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.springframework.web.filter.OncePerRequestFilter.doFilter
(OncePerRequestFilter.java:102) ~[spring-web-5.3.14.jar:5.3.14]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:189) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:162) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.springframework.web.filter.OncePerRequestFilter.doFilter
(OncePerRequestFilter.java:102) ~[spring-web-5.3.14.jar:5.3.14]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:189) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:162) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationDispatcher.invoke
(ApplicationDispatcher.java:711) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationDispatcher.processRequest
(ApplicationDispatcher.java:461) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationDispatcher.doForward
(ApplicationDispatcher.java:385) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationDispatcher.forward
(ApplicationDispatcher.java:313) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.StandardHostValve.custom
(StandardHostValve.java:403) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.StandardHostValve.status
(StandardHostValve.java:249) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
[tomcat-embed-core-9.0.56.jar:9.0.56]
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run
(TaskThread.java:61) ~
[tomcat-embed-core-9.0.56.jar:9.0.56]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
2022-01-14 00:49:13.289 DEBUG 21332 --- [nio-8088-exec-2]
w.c.HttpSessionSecurityContextRepository : Did not store anonymous
SecurityContext
2022-01-14 00:49:13.289 DEBUG 21332 --- [nio-8088-exec-2]
w.c.HttpSessionSecurityContextRepository : Did not store anonymous
SecurityContext
2022-01-14 00:49:13.289 DEBUG 21332 --- [nio-8088-exec-2]
s.s.w.c.SecurityContextPersistenceFilter : Cleared
SecurityContextHolder to complete request
Your logs say this:
2022-01-14 14:49:52.305 WARN 24600 --- [nio-8088-exec-2] c.k.b.s.serviceImpl.UserSecurityService :
Username { "username": "seeshee", "password": "12345" } not found
If we look in your code we can see the following line:
login(#RequestBody String username, String password )
This is your faulty code line, as it doesn't do what you think it does. You think it will take the json and extract the two parameters username and password and set these. But what it actually does is that the #RequestBody will take the entire body (the json) and set it to the parameter that is defined on, which is username.
So what spring is doing is that it will extract the entire json body and place it into the username string.
Then you try to use that to login, and then you get the error message posted above.
What you need to do is to create a holder class that spring can deserialize into.
public class RequestBody {
public RequestBody(String username, String password) {
this.username = username;
this.password = password;
}
// getters, setters
}
#PostMapping("/login")
public ResponseEntity<String> login(#RequestBody RequestBody requestBody ) throws Exception {
Authentication authentication = authenticationManager.authenticate(new
UsernamePasswordAuthenticationToken(
requestBody.getUsername(), requestBody.getPassword()
));
SecurityContextHolder.getContext().setAuthentication(authentication);
return new ResponseEntity<>("User signed -in succesfully", HttpStatus.OK);
}
You can read about how to use requestbody here:
Spring’s RequestBody and ResponseBody Annotation
I'm trying to write a service that will bind to another service through the eureka server and I want to use FeignClient + Hystrix, I can't implement the GET controller, I get this Exception:
java.base#11/jdk.internal.misc.Unsafe.park(Native Method)
java.base#11/java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:234)
java.base#11/java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:2123)
java.base#11/java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:1182)
java.base#11/java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:899)
java.base#11/java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1054)
java.base#11/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1114)
java.base#11/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
java.base#11/java.lang.Thread.run(Thread.java:834)
2021-10-29 14:15:14.413 INFO 5036 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-10-29 14:15:14.429 ERROR 5036 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'parserFileController': Unsatisfied dependency expressed through field 'parserServiceFeignClient'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'by.iba.hystrix.service.ParserServiceFeignClient': Unexpected exception during bean creation; nested exception is java.lang.IllegalStateException: Method has too many Body parameters: public abstract org.springframework.http.ResponseEntity by.iba.hystrix.service.ParserServiceFeignClient.getCars(by.iba.hystrix.filter.CarFilter,org.springframework.data.domain.Pageable)
Warnings:
-
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:660) ~[spring-beans-5.2.15.RELEASE.jar:5.2.15.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640) ~[spring-beans-5.2.15.RELEASE.jar:5.2.15.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119) ~[spring-beans-5.2.15.RELEASE.jar:5.2.15.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.2.15.RELEASE.jar:5.2.15.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1425) ~[spring-beans-5.2.15.RELEASE.jar:5.2.15.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593) ~[spring-beans-5.2.15.RELEASE.jar:5.2.15.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516) ~[spring-beans-5.2.15.RELEASE.jar:5.2.15.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324) ~[spring-beans-5.2.15.RELEASE.jar:5.2.15.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.2.15.RELEASE.jar:5.2.15.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) ~[spring-beans-5.2.15.RELEASE.jar:5.2.15.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.15.RELEASE.jar:5.2.15.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:897) ~[spring-beans-5.2.15.RELEASE.jar:5.2.15.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:879) ~[spring-context-5.2.15.RELEASE.jar:5.2.15.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:551) ~[spring-context-5.2.15.RELEASE.jar:5.2.15.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) ~[spring-boot-2.3.12.RELEASE.jar:2.3.12.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:755) ~[spring-boot-2.3.12.RELEASE.jar:2.3.12.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) ~[spring-boot-2.3.12.RELEASE.jar:2.3.12.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:402) ~[spring-boot-2.3.12.RELEASE.jar:2.3.12.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:312) ~[spring-boot-2.3.12.RELEASE.jar:2.3.12.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1247) ~[spring-boot-2.3.12.RELEASE.jar:2.3.12.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1236) ~[spring-boot-2.3.12.RELEASE.jar:2.3.12.RELEASE]
at by.iba.hystrix.HystrixApplication.main(HystrixApplication.java:18) ~[classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'by.iba.hystrix.service.ParserServiceFeignClient': Unexpected exception during bean creation; nested exception is java.lang.IllegalStateException: Method has too many Body parameters: public abstract org.springframework.http.ResponseEntity by.iba.hystrix.service.ParserServiceFeignClient.getCars(by.iba.hystrix.filter.CarFilter,org.springframework.data.domain.Pageable)
Warnings:
-
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:529) ~[spring-beans-5.2.15.RELEASE.jar:5.2.15.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324) ~[spring-beans-5.2.15.RELEASE.jar:5.2.15.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.2.15.RELEASE.jar:5.2.15.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) ~[spring-beans-5.2.15.RELEASE.jar:5.2.15.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.15.RELEASE.jar:5.2.15.RELEASE]
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) ~[spring-beans-5.2.15.RELEASE.jar:5.2.15.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1307) ~[spring-beans-5.2.15.RELEASE.jar:5.2.15.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1227) ~[spring-beans-5.2.15.RELEASE.jar:5.2.15.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:657) ~[spring-beans-5.2.15.RELEASE.jar:5.2.15.RELEASE]
... 21 common frames omitted
Caused by: java.lang.IllegalStateException: Method has too many Body parameters: public abstract org.springframework.http.ResponseEntity by.iba.hystrix.service.ParserServiceFeignClient.getCars(by.iba.hystrix.filter.CarFilter,org.springframework.data.domain.Pageable)
Warnings:
-
at feign.Util.checkState(Util.java:129) ~[feign-core-10.12.jar:na]
at feign.Contract$BaseContract.parseAndValidateMetadata(Contract.java:127) ~[feign-core-10.12.jar:na]
at org.springframework.cloud.openfeign.support.SpringMvcContract.parseAndValidateMetadata(SpringMvcContract.java:207) ~[spring-cloud-openfeign-core-2.2.9.RELEASE.jar:2.2.9.RELEASE]
at feign.Contract$BaseContract.parseAndValidateMetadata(Contract.java:62) ~[feign-core-10.12.jar:na]
at feign.hystrix.HystrixDelegatingContract.parseAndValidateMetadata(HystrixDelegatingContract.java:47) ~[feign-hystrix-10.12.jar:na]
at feign.ReflectiveFeign$ParseHandlersByName.apply(ReflectiveFeign.java:151) ~[feign-core-10.12.jar:na]
at feign.ReflectiveFeign.newInstance(ReflectiveFeign.java:49) ~[feign-core-10.12.jar:na]
at feign.hystrix.HystrixFeign$Builder.target(HystrixFeign.java:63) ~[feign-hystrix-10.12.jar:na]
at org.springframework.cloud.openfeign.HystrixTargeter.targetWithFallback(HystrixTargeter.java:74) ~[spring-cloud-openfeign-core-2.2.9.RELEASE.jar:2.2.9.RELEASE]
at org.springframework.cloud.openfeign.HystrixTargeter.target(HystrixTargeter.java:49) ~[spring-cloud-openfeign-core-2.2.9.RELEASE.jar:2.2.9.RELEASE]
at org.springframework.cloud.openfeign.FeignClientFactoryBean.getTarget(FeignClientFactoryBean.java:416) ~[spring-cloud-openfeign-core-2.2.9.RELEASE.jar:2.2.9.RELEASE]
at org.springframework.cloud.openfeign.FeignClientFactoryBean.getObject(FeignClientFactoryBean.java:361) ~[spring-cloud-openfeign-core-2.2.9.RELEASE.jar:2.2.9.RELEASE]
at org.springframework.cloud.openfeign.FeignClientsRegistrar.lambda$registerFeignClient$0(FeignClientsRegistrar.java:246) ~[spring-cloud-openfeign-core-2.2.9.RELEASE.jar:2.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.obtainFromSupplier(AbstractAutowireCapableBeanFactory.java:1235) ~[spring-beans-5.2.15.RELEASE.jar:5.2.15.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177) ~[spring-beans-5.2.15.RELEASE.jar:5.2.15.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:556) ~[spring-beans-5.2.15.RELEASE.jar:5.2.15.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516) ~[spring-beans-5.2.15.RELEASE.jar:5.2.15.RELEASE]
... 29 common frames omitted
Process finished with exit code 1
This is what my controller looks like in the main service:
#RestController
#RequestMapping("/cars")
public class CarController {
private final CarService carService;
#Autowired
public CarController(CarService carService) {
this.carService = carService;
}
#GetMapping
public ResponseEntity<Page<CarDto>> getCars(CarFilter carFilter, Pageable page) {
Page<CarDto> cars = carService.getCars(page, carFilter);
return new ResponseEntity<>(cars, HttpStatus.OK);
}
This is what my controller looks like in the service where I am trying to implement FeignClient:
#RestController
#RequestMapping("/cars")
public class ParserFileController {
#Autowired
private ParserServiceFeignClient parserServiceFeignClient;
#GetMapping
public ResponseEntity<Page<CarDto>> getCars(CarFilter carFilter, Pageable page) {
return parserServiceFeignClient.getCars(carFilter, page);
}
This is the interface where I made FeignClient
#FeignClient(
name = "PARSER-FILE-SERVICE",
url = "http://localhost:8080/cars",
fallback = ParserServiceFallback.class
)
public interface ParserServiceFeignClient {
#GetMapping()
ResponseEntity<Page<CarDto>> getCars(CarFilter carFilter, Pageable page);
And this is the Fallback class FeignClient:
#Component
public class ParserServiceFallback implements ParserServiceFeignClient {
#Override
public ResponseEntity<Page<CarDto>> getCars(CarFilter carFilter, Pageable page) {
System.out.println("In fallback method");
return new ResponseEntity<>(new RestPageImpl<>(), HttpStatus.OK);
}
CarFilter:
public class CarFilter {
private String mark;
private Integer year;
private String color;
private String country;
public CarFilter() {
}
// getters and setters
Please help, I have been tormented by this task for a long time. I tried to do it via POST, but this is not suitable for obtaining a resource with RESTapi
GET requests usually don't hava a body, so you have to pass params e.g. as query params.
Try using request param annotation:
#GetMapping
public ResponseEntity<Page<CarDto>> getCars(#RequestParam("car-filter") CarFilter carFilter, #RequestParam("page") Pageable page)
GET requests don't have a body, try using other mapping methods like the post. nad try to receive objects in a more specific way with some annotation like #RequestParam, or #RequestBody.
#PostMapping("")
public ResponseEntity<> getCars(#RequestBody CarFilter car, ....){}
I have something very similar to the code below (I had to do some obfiscation). I am getting an Application Failed to Start error. Code not shown are datasource bean and spring boot application class. When I put breakpoints in and all run in debug, all beans appear to be created except the Job and Step bean, which seem to be skipped over entirely. I am not sure how to diagnose further. Seems to be some Spring Magic issues. Any ideas are greatly appreciated.
Here is the exception:
2020-08-23 11:26:50.264 INFO 12195 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-08-23 11:26:50.265 INFO 12195 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.31]
2020-08-23 11:26:50.382 INFO 12195 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-08-23 11:26:50.383 INFO 12195 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2276 ms
2020-08-23 11:26:57.552 WARN 12195 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'databaseCursorStep' defined in class path resource [/com/configuration/BatchConfig.class]: Unsatisfied dependency expressed through method 'databaseCursorStep' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.batch.item.ItemReader<com.dto.StuffDto>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Qualifier(value=databaseCursorItemReader)}
2020-08-23 11:26:57.572 INFO 12195 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2020-08-23 11:26:57.603 INFO 12195 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-08-23 11:26:57.908 ERROR 12195 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
APPLICATION FAILED TO START
Description:
Parameter 0 of method databaseCursorStep in com.configuration.BatchConfig required a bean of type 'org.springframework.batch.item.ItemReader' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Qualifier(value=databaseCursorItemReader)
Action:
Consider defining a bean of type 'org.springframework.batch.item.ItemReader' in your configuration.
Disconnected from the target VM, address: '127.0.0.1:46088', transport: 'socket'
Process finished with exit code 1
Here is the code:
#Configuration
#EnableBatchProcessing
public class BatchConfig {
#Autowired
public JobBuilderFactory jobBuilderFactory;
#Autowired
public StepBuilderFactory stepBuilderFactory;
private static final String GET_DATA =
"SELECT " +
"stuffA, " +
"stuffB, " +
"FROM STUFF_TABLE " +
"ORDER BY stuffA ASC";
#Bean
public ItemReader<StuffDto> itemReader(DataSource dataSource) {
return new JdbcCursorItemReaderBuilder<StuffDto>()
.name("cursorItemReader")
.dataSource(dataSource)
.sql(GET_DATA)
.rowMapper(new BeanPropertyRowMapper<>(StuffDto.class))
.build();
}
#Bean
ItemProcessor<StuffDto, StuffDto> databaseXmlItemProcessor() {
return new QueryLoggingProcessor();
}
#Bean
public ItemWriter<StuffDto> databaseCursorItemWriter() {
return new LoggingItemWriter();
}
#Bean
public Step databaseCursorStep(#Qualifier("databaseCursorItemReader") ItemReader<StuffDto> reader,
#Qualifier("databaseCursorItemWriter") ItemWriter<StuffDto> writer,
StepBuilderFactory stepBuilderFactory) {
return stepBuilderFactory.get("databaseCursorStep")
.<StuffDto, StuffDto>chunk(1)
.reader(reader)
.writer(writer)
.build();
}
#Bean
public Job databaseCursorJob(#Qualifier("databaseCursorStep") Step exampleJobStep,
JobBuilderFactory jobBuilderFactory) {
return jobBuilderFactory.get("databaseCursorJob")
.incrementer(new RunIdIncrementer())
.flow(exampleJobStep)
.end()
.build();
}
}
Your Qualifier Bean name is itemReader not databaseCursorItemReader. Either change the method name or change to databaseCursorStep(#Qualifier("itemReader")
#Bean
public Step databaseCursorStep(#Qualifier("itemReader") ItemReader<StuffDto> reader,
#Qualifier("databaseCursorItemWriter") ItemWriter<StuffDto> writer,
StepBuilderFactory stepBuilderFactory) {
return stepBuilderFactory.get("databaseCursorStep")
.<StuffDto, StuffDto>chunk(1)
.reader(reader)
.writer(writer)
.build();
}
#Bean
public ItemReader<StuffDto> itemReader(DataSource dataSource) {
return new JdbcCursorItemReaderBuilder<StuffDto>()
.name("cursorItemReader")
.dataSource(dataSource)
.sql(GET_DATA)
.rowMapper(new BeanPropertyRowMapper<>(StuffDto.class))
.build();
}
I have a Webflux app that restarts automatically after a few minutes of usage, sometimes I can use it for a couple of hours then suddenly it restarts, when it restarts an error pops up saying duplicate EnhancerBySpringCGLIB. I know this question has been asked before and I tried the suggested solutions but none worked. below is my log
2020-07-26 10:18:00.515 INFO 23080 --- [ restartedMain] u.s.w.NcitoAfricaApplication : Started NcitoAfricaApplication in 5.37 seconds (JVM running for 6.719)
2020-07-26 10:18:00.523 DEBUG 23080 --- [ restartedMain] o.s.b.d.r.Restarter : Creating new Restarter for thread Thread[main,5,main]
2020-07-26 10:18:00.523 DEBUG 23080 --- [ restartedMain] o.s.b.d.r.Restarter : Immediately restarting application
2020-07-26 10:18:00.523 DEBUG 23080 --- [ restartedMain] o.s.b.d.r.Restarter : Created RestartClassLoader org.springframework.boot.devtools.restart.classloader.RestartClassLoader#1cbd5ea1
2020-07-26 10:18:00.523 DEBUG 23080 --- [ restartedMain] o.s.b.d.r.Restarter : Starting application ubuntu.software.web.NcitoAfricaApplication with URLs [file:/C:/Users/alungu5/IdeaProjects/Tubombeko/]
2020-07-26 10:30:15.181 DEBUG 23080 --- [ File Watcher] o.s.b.d.r.Restarter : Restarting application
2020-07-26 10:30:15.185 DEBUG 23080 --- [ Thread-385] o.s.b.d.r.Restarter : Stopping application
2020-07-26 10:30:15.187 DEBUG 23080 --- [ Thread-385] onfigReactiveWebServerApplicationContext : Closing org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext#6de721d1, started on Sun Jul 26 10:17:55 SAST 2020
2020-07-26 10:30:15.195 DEBUG 23080 --- [ Thread-385] o.s.c.s.DefaultLifecycleProcessor : Stopping beans in phase 2147483647
2020-07-26 10:30:15.201 DEBUG 23080 --- [ Thread-385] o.s.c.s.DefaultLifecycleProcessor : Bean 'webServerGracefulShutdown' completed its stop procedure
2020-07-26 10:30:15.201 DEBUG 23080 --- [ Thread-385] o.s.c.s.DefaultLifecycleProcessor : Stopping beans in phase 2147483646
2020-07-26 10:30:15.217 DEBUG 23080 --- [ Thread-385] o.s.c.s.DefaultLifecycleProcessor : Bean 'webServerStartStop' completed its stop procedure
2020-07-26 10:30:15.217 DEBUG 23080 --- [ Thread-385] o.s.c.s.DefaultLifecycleProcessor : Stopping beans in phase 0
2020-07-26 10:30:19.433 DEBUG 23080 --- [ Thread-385] o.s.b.d.r.Restarter : Created RestartClassLoader org.springframework.boot.devtools.restart.classloader.RestartClassLoader#45d8b2bd
2020-07-26 10:30:19.433 DEBUG 23080 --- [ Thread-385] o.s.b.d.r.Restarter : Starting application ubuntu.software.web.NcitoAfricaApplication with URLs [file:/C:/Users/alungu5/IdeaProjects/Tubombeko/]
2020-07-26 10:30:19.571 DEBUG 23080 --- [ restartedMain] .c.l.ClasspathLoggingApplicationListener : Application started with classpath: [file:/C:/Users/alungu5/IdeaProjects/Tubombeko/]
.
.
.
.
springframework.beans.factory.BeanCreationException: Error creating bean with name 'countryServiceImpl' defined in file [C:\Users\alungu5\IdeaProjects\Tubombeko\service\target\classes\ubuntu\software\service\country\CountryServiceImpl.class]: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class ubuntu.software.service.country.CountryServiceImpl: Common causes of this problem include using a final class or a non-visible class; nested exception is org.springframework.cglib.core.CodeGenerationException: java.lang.LinkageError-->loader 'app' attempted duplicate class definition for ubuntu.software.service.country.CountryServiceImpl$$EnhancerBySpringCGLIB$$906ca3da. (ubuntu.software.service.country.CountryServiceImpl$$EnhancerBySpringCGLIB$$906ca3da is in module ubuntu.software.service of loader 'app')
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:603) ~[spring-beans-5.2.7.RELEASE.jar:?]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.7.RELEASE.jar:?]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.7.RELEASE.jar:?]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226) ~[spring-beans-5.2.7.RELEASE.jar:?]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.7.RELEASE.jar:?]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.7.RELEASE.jar:?]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:893) ~[spring-beans-5.2.7.RELEASE.jar:?]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:879) ~[spring-context-5.2.7.RELEASE.jar:?]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:551) ~[spring-context-5.2.7.RELEASE.jar:?]
at org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.refresh(ReactiveWebServerApplicationContext.java:62) ~[spring-boot-2.3.1.RELEASE.jar:?]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) ~[spring-boot-2.3.1.RELEASE.jar:?]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) [spring-boot-2.3.1.RELEASE.jar:?]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.3.1.RELEASE.jar:?]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.3.1.RELEASE.jar:?]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) [spring-boot-2.3.1.RELEASE.jar:?]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.3.1.RELEASE.jar:?]
at ubuntu.software.web.NcitoAfricaApplication.main(NcitoAfricaApplication.java:21) [classes/:?]
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:?]
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:?]
at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:?]
at java.lang.reflect.Method.invoke(Method.java:564) ~[?:?]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.3.1.RELEASE.jar:?]
Caused by: org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class ubuntu.software.service.country.CountryServiceImpl: Common causes of this problem include using a final class or a non-visible class; nested exception is org.springframework.cglib.core.CodeGenerationException: java.lang.LinkageError-->loader 'app' attempted duplicate class definition for ubuntu.software.service.country.CountryServiceImpl$$EnhancerBySpringCGLIB$$906ca3da. (ubuntu.software.service.country.CountryServiceImpl$$EnhancerBySpringCGLIB$$906ca3da is in module ubuntu.software.service of loader 'app')
at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:208) ~[spring-aop-5.2.7.RELEASE.jar:?]
at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:110) ~[spring-aop-5.2.7.RELEASE.jar:?]
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(AbstractAutoProxyCreator.java:471) ~[spring-aop-5.2.7.RELEASE.jar:?]
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:350) ~[spring-aop-5.2.7.RELEASE.jar:?]
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:299) ~[spring-aop-5.2.7.RELEASE.jar:?]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:431) ~[spring-beans-5.2.7.RELEASE.jar:?]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans-5.2.7.RELEASE.jar:?]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595) ~[spring-beans-5.2.7.RELEASE.jar:?]
... 21 more
Caused by: org.springframework.cglib.core.CodeGenerationException: java.lang.LinkageError-->loader 'app' attempted duplicate class definition for ubuntu.software.service.country.CountryServiceImpl$$EnhancerBySpringCGLIB$$906ca3da. (ubuntu.software.service.country.CountryServiceImpl$$EnhancerBySpringCGLIB$$906ca3da is in module ubuntu.software.service of loader 'app')
at org.springframework.cglib.core.ReflectUtils.defineClass(ReflectUtils.java:558) ~[spring-core-5.2.7.RELEASE.jar:?]
at org.springframework.cglib.core.AbstractClassGenerator.generate(AbstractClassGenerator.java:363) ~[spring-core-5.2.7.RELEASE.jar:?]
at org.springframework.cglib.proxy.Enhancer.generate(Enhancer.java:585) ~[spring-core-5.2.7.RELEASE.jar:?]
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:110) ~[spring-core-5.2.7.RELEASE.jar:?]
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:108) ~[spring-core-5.2.7.RELEASE.jar:?]
at org.springframework.cglib.core.internal.LoadingCache$2.call(LoadingCache.java:54) ~[spring-core-5.2.7.RELEASE.jar:?]
at java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[?:?]
at org.springframework.cglib.core.internal.LoadingCache.createEntry(LoadingCache.java:61) ~[spring-core-5.2.7.RELEASE.jar:?]
at org.springframework.cglib.core.internal.LoadingCache.get(LoadingCache.java:34) ~[spring-core-5.2.7.RELEASE.jar:?]
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData.get(AbstractClassGenerator.java:134) ~[spring-core-5.2.7.RELEASE.jar:?]
at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:319) ~[spring-core-5.2.7.RELEASE.jar:?]
at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:572) ~[spring-core-5.2.7.RELEASE.jar:?]
at org.springframework.cglib.proxy.Enhancer.createClass(Enhancer.java:419) ~[spring-core-5.2.7.RELEASE.jar:?]
at org.springframework.aop.framework.ObjenesisCglibAopProxy.createProxyClassAndInstance(ObjenesisCglibAopProxy.java:57) ~[spring-aop-5.2.7.RELEASE.jar:?]
at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:205) ~[spring-aop-5.2.7.RELEASE.jar:?]
at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:110) ~[spring-aop-5.2.7.RELEASE.jar:?]
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(AbstractAutoProxyCreator.java:471) ~[spring-aop-5.2.7.RELEASE.jar:?]
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:350) ~[spring-aop-5.2.7.RELEASE.jar:?]
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:299) ~[spring-aop-5.2.7.RELEASE.jar:?]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:431) ~[spring-beans-5.2.7.RELEASE.jar:?]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans-5.2.7.RELEASE.jar:?]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595) ~[spring-beans-5.2.7.RELEASE.jar:?]
... 21 more
Caused by: java.lang.LinkageError: loader 'app' attempted duplicate class definition for ubuntu.software.service.country.CountryServiceImpl$$EnhancerBySpringCGLIB$$906ca3da. (ubuntu.software.service.country.CountryServiceImpl$$EnhancerBySpringCGLIB$$906ca3da is in module ubuntu.software.service of loader 'app')
at java.lang.ClassLoader.defineClass1(Native Method) ~[?:?]
at java.lang.System$2.defineClass(System.java:2196) ~[?:?]
at java.lang.invoke.MethodHandles$Lookup.defineClass(MethodHandles.java:1648) ~[?:?]
at jdk.internal.reflect.GeneratedMethodAccessor43.invoke(Unknown Source) ~[?:?]
at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:?]
at java.lang.reflect.Method.invoke(Method.java:564) ~[?:?]
at org.springframework.cglib.core.ReflectUtils.defineClass(ReflectUtils.java:555) ~[spring-core-5.2.7.RELEASE.jar:?]
at org.springframework.cglib.core.AbstractClassGenerator.generate(AbstractClassGenerator.java:363) ~[spring-core-5.2.7.RELEASE.jar:?]
at org.springframework.cglib.proxy.Enhancer.generate(Enhancer.java:585) ~[spring-core-5.2.7.RELEASE.jar:?]
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:110) ~[spring-core-5.2.7.RELEASE.jar:?]
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:108) ~[spring-core-5.2.7.RELEASE.jar:?]
at org.springframework.cglib.core.internal.LoadingCache$2.call(LoadingCache.java:54) ~[spring-core-5.2.7.RELEASE.jar:?]
at java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[?:?]
at org.springframework.cglib.core.internal.LoadingCache.createEntry(LoadingCache.java:61) ~[spring-core-5.2.7.RELEASE.jar:?]
at org.springframework.cglib.core.internal.LoadingCache.get(LoadingCache.java:34) ~[spring-core-5.2.7.RELEASE.jar:?]
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData.get(AbstractClassGenerator.java:134) ~[spring-core-5.2.7.RELEASE.jar:?]
at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:319) ~[spring-core-5.2.7.RELEASE.jar:?]
at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:572) ~[spring-core-5.2.7.RELEASE.jar:?]
at org.springframework.cglib.proxy.Enhancer.createClass(Enhancer.java:419) ~[spring-core-5.2.7.RELEASE.jar:?]
at org.springframework.aop.framework.ObjenesisCglibAopProxy.createProxyClassAndInstance(ObjenesisCglibAopProxy.java:57) ~[spring-aop-5.2.7.RELEASE.jar:?]
at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:205) ~[spring-aop-5.2.7.RELEASE.jar:?]
at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:110) ~[spring-aop-5.2.7.RELEASE.jar:?]
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(AbstractAutoProxyCreator.java:471) ~[spring-aop-5.2.7.RELEASE.jar:?]
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:350) ~[spring-aop-5.2.7.RELEASE.jar:?]
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:299) ~[spring-aop-5.2.7.RELEASE.jar:?]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:431) ~[spring-beans-5.2.7.RELEASE.jar:?]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans-5.2.7.RELEASE.jar:?]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595) ~[spring-beans-5.2.7.RELEASE.jar:?]
... 21 more
This is how my CountryServiceImpl looks like
#Service
#Qualifier("CountryServiceImpl")
public class CountryServiceImpl extends BaseService<Country, CountryDto, CountryRepository> implements ICountryService {
#Lazy
#Autowired
private CountryRepository countryRepository;
#Lazy
#Autowired
private IJWTUtil jwtUtil;
#Override
public CountryRepository getRepository() {
return countryRepository;
}
#Override
public Mono<Country> createModel(CountryDto countryDto, Map<String, Claim> claims) {
Country country = getModelMapper().map(countryDto, Country.class);
country.setStatus(BaseModel.Status.ENABLED);
return Mono.just(country);
}
#Override
public Mono<Country> createUpdateModel(CountryDto countryDto, Map<String, Claim> claims) {
return getRepository().findById(countryDto.getId())
.flatMap(country -> Mono.just(country.toBuilder()
.name(countryDto.getName())
.build()));
}
#Override
public IJWTUtil getJwtUtil() {
return jwtUtil;
}
}
My ICountryService interface
public interface ICountryService extends IBaseService<Country, CountryDto> {
}
My BaseService Impl
#Transactional
public abstract class BaseService<T extends BaseModel, V extends BaseDto, E extends BaseRepository<T>> implements IBaseService<T, V> {
#Getter
private final ModelMapper modelMapper;
abstract public E getRepository();
public abstract Mono<T> createModel(V v, Map<String, Claim> claims);
public abstract Mono<T> createUpdateModel(V v, Map<String, Claim> claims);
public abstract IJWTUtil getJwtUtil();
public Mono<T> validate(Mono<T> t) {
return t;
}
public Flux<T> validate(Flux<T> t) {
return t;
}
public BaseService() {
modelMapper = new ModelMapper();
}
#Override
public Mono<ResponseEntity<?>> create(V v, Optional<String> authorizationHeader) {
Map<String, Claim> claims = authorizationHeader.map(mAuthorizationHeader -> getJwtUtil().getAllClaims(mAuthorizationHeader)).orElse(new HashMap<>());
Mono<T> model = this.createModel(v, claims);
return create(model, claims)
.flatMap(__ -> Mono.<ResponseEntity<?>>just(ResponseEntity
.status(HttpStatus.CREATED)
.body(Response.builder()
.payLoad(HttpStatus.CREATED)
.build())))
.switchIfEmpty(Mono.defer(() ->
Mono.just(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Response.builder()
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.message("Unknown error occurred, try again")
.build()))));
}
#Override
public Mono<T> create(Mono<T> t, Map<String, Claim> claims) {
return validate(t)
.flatMap(k -> getRepository().save(k));
}
#Override
public Flux<T> createAll(List<T> t, Map<String, Claim> claims) {
return validate(Flux.fromIterable(t))
.thenMany(getRepository().saveAll(t));
}
}
And finally My IBaseService Interface
public interface IBaseService<T extends BaseModel, V extends BaseDto> {
Mono<ResponseEntity<?>> create(V v, Optional<String> authorizationHeader);
Mono<T> create(Mono<T> t, Map<String, Claim> claims);
Flux<T> createAll(List<T> t, Map<String, Claim> claims);
}
After doing some reading I found out that CGLIB issues are usually caused by the #Transactional annotation as it generates proxies, a way around is to put it #Transactional on the parent of which I have but the error still pops up after the app restarts.
Ok, so I found the culprit, turns out it was the Java 9 module-info.java, I encountered an issue making RabbitMq work, all files were imported correctly but it was pointing to say the error was coming from my module-info.java so I removed it, after removing it I have not had this problem (and RabbitMq worked too), from my understanding, their are internal classes that were not put on the allow list that need to access my classes and because of that the app kept failing, the app has been working since then without any problems.
Trying to write api for authorization jwt+csrf, but I get an error.How to fix it?
thanks in advance
Error:
Error creating bean with name 'restHandlerMapping' defined in class
path resource
[org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.class]:
Bean instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate
[org.springframework.data.rest.webmvc.support.DelegatingHandlerMapping]:
Factory method 'restHandlerMapping' threw exception; nested exception
is java.lang.IllegalStateException: Missing path mapping. Handler
method
'org.springframework.data.rest.webmvc.RepositoryController#optionsForRepositories()'
in bean 'repositoryController' must be mapped to a non-empty path. If
you wish to map to all paths, please map explicitly to /** or **.
Full terminal output:
2019-04-06 00:37:35.103 WARN 24654 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'restHandlerMapping' defined in class path resource [org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.rest.webmvc.support.DelegatingHandlerMapping]: Factory method 'restHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: Missing path mapping. Handler method 'org.springframework.data.rest.webmvc.RepositoryController#optionsForRepositories()' in bean 'repositoryController' must be mapped to a non-empty path. If you wish to map to all paths, please map explicitly to "/**" or "**".
2019-04-06 00:37:35.124 INFO 24654 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
2019-04-06 00:37:35.126 INFO 24654 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2019-04-06 00:37:35.129 INFO 24654 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2019-04-06 00:37:35.138 INFO 24654 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
2019-04-06 00:37:35.141 INFO 24654 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2019-04-06 00:37:35.160 INFO 24654 --- [ restartedMain] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-04-06 00:37:35.165 ERROR 24654 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'restHandlerMapping' defined in class path resource [org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.rest.webmvc.support.DelegatingHandlerMapping]: Factory method 'restHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: Missing path mapping. Handler method 'org.springframework.data.rest.webmvc.RepositoryController#optionsForRepositories()' in bean 'repositoryController' must be mapped to a non-empty path. If you wish to map to all paths, please map explicitly to "/**" or "**".
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:638) ~[spring-beans-5.2.0.BUILD-SNAPSHOT.jar:5.2.0.BUILD-SNAPSHOT]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:468) ~[spring-beans-5.2.0.BUILD-SNAPSHOT.jar:5.2.0.BUILD-SNAPSHOT]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1325) ~[spring-beans-5.2.0.BUILD-SNAPSHOT.jar:5.2.0.BUILD-SNAPSHOT]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1164) ~[spring-beans-5.2.0.BUILD-SNAPSHOT.jar:5.2.0.BUILD-SNAPSHOT]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-5.2.0.BUILD-SNAPSHOT.jar:5.2.0.BUILD-SNAPSHOT]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.2.0.BUILD-SNAPSHOT.jar:5.2.0.BUILD-SNAPSHOT]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.2.0.BUILD-SNAPSHOT.jar:5.2.0.BUILD-SNAPSHOT]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.0.BUILD-SNAPSHOT.jar:5.2.0.BUILD-SNAPSHOT]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.2.0.BUILD-SNAPSHOT.jar:5.2.0.BUILD-SNAPSHOT]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.2.0.BUILD-SNAPSHOT.jar:5.2.0.BUILD-SNAPSHOT]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:866) ~[spring-beans-5.2.0.BUILD-SNAPSHOT.jar:5.2.0.BUILD-SNAPSHOT]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877) ~[spring-context-5.2.0.BUILD-SNAPSHOT.jar:5.2.0.BUILD-SNAPSHOT]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.2.0.BUILD-SNAPSHOT.jar:5.2.0.BUILD-SNAPSHOT]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.2.0.BUILD-SNAPSHOT.jar:2.2.0.BUILD-SNAPSHOT]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:785) ~[spring-boot-2.2.0.BUILD-SNAPSHOT.jar:2.2.0.BUILD-SNAPSHOT]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:407) ~[spring-boot-2.2.0.BUILD-SNAPSHOT.jar:2.2.0.BUILD-SNAPSHOT]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:322) ~[spring-boot-2.2.0.BUILD-SNAPSHOT.jar:2.2.0.BUILD-SNAPSHOT]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1278) ~[spring-boot-2.2.0.BUILD-SNAPSHOT.jar:2.2.0.BUILD-SNAPSHOT]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1266) ~[spring-boot-2.2.0.BUILD-SNAPSHOT.jar:2.2.0.BUILD-SNAPSHOT]
at com.sandr1x.quizspringvue.QuizSpringVueApplication.main(QuizSpringVueApplication.java:9) ~[main/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.2.0.BUILD-SNAPSHOT.jar:2.2.0.BUILD-SNAPSHOT]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.rest.webmvc.support.DelegatingHandlerMapping]: Factory method 'restHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: Missing path mapping. Handler method 'org.springframework.data.rest.webmvc.RepositoryController#optionsForRepositories()' in bean 'repositoryController' must be mapped to a non-empty path. If you wish to map to all paths, please map explicitly to "/**" or "**".
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.2.0.BUILD-SNAPSHOT.jar:5.2.0.BUILD-SNAPSHOT]
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:633) ~[spring-beans-5.2.0.BUILD-SNAPSHOT.jar:5.2.0.BUILD-SNAPSHOT]
... 24 common frames omitted
Caused by: java.lang.IllegalStateException: Missing path mapping. Handler method 'org.springframework.data.rest.webmvc.RepositoryController#optionsForRepositories()' in bean 'repositoryController' must be mapped to a non-empty path. If you wish to map to all paths, please map explicitly to "/**" or "**".
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry.validateMethodMapping(AbstractHandlerMethodMapping.java:622) ~[spring-webmvc-5.2.0.BUILD-SNAPSHOT.jar:5.2.0.BUILD-SNAPSHOT]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry.register(AbstractHandlerMethodMapping.java:592) ~[spring-webmvc-5.2.0.BUILD-SNAPSHOT.jar:5.2.0.BUILD-SNAPSHOT]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.registerHandlerMethod(AbstractHandlerMethodMapping.java:314) ~[spring-webmvc-5.2.0.BUILD-SNAPSHOT.jar:5.2.0.BUILD-SNAPSHOT]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.lambda$detectHandlerMethods$1(AbstractHandlerMethodMapping.java:284) ~[spring-webmvc-5.2.0.BUILD-SNAPSHOT.jar:5.2.0.BUILD-SNAPSHOT]
at java.base/java.util.LinkedHashMap.forEach(LinkedHashMap.java:684) ~[na:na]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.detectHandlerMethods(AbstractHandlerMethodMapping.java:282) ~[spring-webmvc-5.2.0.BUILD-SNAPSHOT.jar:5.2.0.BUILD-SNAPSHOT]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.processCandidateBean(AbstractHandlerMethodMapping.java:254) ~[spring-webmvc-5.2.0.BUILD-SNAPSHOT.jar:5.2.0.BUILD-SNAPSHOT]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.initHandlerMethods(AbstractHandlerMethodMapping.java:213) ~[spring-webmvc-5.2.0.BUILD-SNAPSHOT.jar:5.2.0.BUILD-SNAPSHOT]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.afterPropertiesSet(AbstractHandlerMethodMapping.java:201) ~[spring-webmvc-5.2.0.BUILD-SNAPSHOT.jar:5.2.0.BUILD-SNAPSHOT]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.afterPropertiesSet(RequestMappingHandlerMapping.java:164) ~[spring-webmvc-5.2.0.BUILD-SNAPSHOT.jar:5.2.0.BUILD-SNAPSHOT]
at org.springframework.data.rest.webmvc.BasePathAwareHandlerMapping.afterPropertiesSet(BasePathAwareHandlerMapping.java:194) ~[spring-data-rest-webmvc-3.2.0.M2.jar:3.2.0.M2]
at org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration.restHandlerMapping(RepositoryRestMvcConfiguration.java:588) ~[spring-data-rest-webmvc-3.2.0.M2.jar:3.2.0.M2]
at org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration$$EnhancerBySpringCGLIB$$1be339be.CGLIB$restHandlerMapping$28(<generated>) ~[spring-data-rest-webmvc-3.2.0.M2.jar:3.2.0.M2]
at org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration$$EnhancerBySpringCGLIB$$1be339be$$FastClassBySpringCGLIB$$84f2d0e6.invoke(<generated>) ~[spring-data-rest-webmvc-3.2.0.M2.jar:3.2.0.M2]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.2.0.BUILD-SNAPSHOT.jar:5.2.0.BUILD-SNAPSHOT]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363) ~[spring-context-5.2.0.BUILD-SNAPSHOT.jar:5.2.0.BUILD-SNAPSHOT]
at org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration$$EnhancerBySpringCGLIB$$1be339be.restHandlerMapping(<generated>) ~[spring-data-rest-webmvc-3.2.0.M2.jar:3.2.0.M2]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.2.0.BUILD-SNAPSHOT.jar:5.2.0.BUILD-SNAPSHOT]
... 25 common frames omitted
WebSecurityConfig.java
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
UserDetailsServiceImpl userDetailsService;
#Autowired
private JwtAuthEntryPoint unauthorizedHandler;
#Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.setAllowedOrigins(Arrays.asList("http://localhost:8080"));
config.addAllowedHeader("*");
config.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/api/auth/**", config);
return source;
}
#Bean
public JwtAuthTokenFilter authenticationJwtTokenFilter() {
return new JwtAuthTokenFilter();
}
#Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf()
.ignoringAntMatchers("/api/auth/signin")
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
.authorizeRequests()
.antMatchers("/api/auth/**").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
API
package com.sandr1x.quizspringvue.controller;
import com.sandr1x.quizspringvue.message.request.LoginForm;
import com.sandr1x.quizspringvue.message.request.SignUpForm;
import com.sandr1x.quizspringvue.message.response.JwtResponse;
import com.sandr1x.quizspringvue.model.Role;
import com.sandr1x.quizspringvue.model.RoleName;
import com.sandr1x.quizspringvue.model.User;
import com.sandr1x.quizspringvue.repository.RoleRepository;
import com.sandr1x.quizspringvue.repository.UserRepository;
import com.sandr1x.quizspringvue.security.jwt.JwtProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.util.HashSet;
import java.util.Set;
#CrossOrigin(origins = "*", maxAge = 3600)
#RestController
#RequestMapping("/api/auth")
public class AuthRestAPIs {
#Autowired
AuthenticationManager authenticationManager;
#Autowired
UserRepository userRepository;
#Autowired
RoleRepository roleRepository;
#Autowired
PasswordEncoder encoder;
#Autowired
JwtProvider jwtProvider;
#PostMapping("/signin")
public ResponseEntity<?> authenticateUser(#Valid #RequestBody LoginForm loginRequest) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
loginRequest.getUsername(),
loginRequest.getPassword()
)
);
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtProvider.generateJwtToken(authentication);
return ResponseEntity.ok(new JwtResponse(jwt));
}
#PostMapping("/signup")
public ResponseEntity<String> registerUser(#Valid #RequestBody SignUpForm signUpRequest) {
if(userRepository.existsByUsername(signUpRequest.getUsername())) {
return new ResponseEntity<String>("Fail -> Username is already taken!",
HttpStatus.BAD_REQUEST);
}
if(userRepository.existsByEmail(signUpRequest.getEmail())) {
return new ResponseEntity<String>("Fail -> Email is already in use!",
HttpStatus.BAD_REQUEST);
}
User user = new User(signUpRequest.getUsername(),
signUpRequest.getEmail(), encoder.encode(signUpRequest.getPassword()));
Set<String> strRoles = signUpRequest.getRole();
Set<Role> roles = new HashSet<>();
strRoles.forEach(role -> {
switch(role) {
case "admin":
Role adminRole = roleRepository.findByName(RoleName.ROLE_ADMIN)
.orElseThrow(() -> new RuntimeException("Fail! -> Cause: User Role not find."));
roles.add(adminRole);
break;
case "otherRole":
//
break;
default:
Role userRole = roleRepository.findByName(RoleName.ROLE_USER)
.orElseThrow(() -> new RuntimeException("Fail! -> Cause: User Role not find."));
roles.add(userRole);
}
});
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok().body("User registered successfully!");
}
}
This happened to me when I accidentally defined two controller methods for the same request method and endpoint.
I confirm the problem is the version of spring boot I have.
Just change the version to 2.2.0.M1 and it will work.