Spring Boot Oauth2 oauth/token not mapped on initialization - spring-boot

I am applying OAuth2 security to my Spring Boot Application.
My issue is that when I run the application /oauth/token path is not mapped at the time of application initialization.
AuthorizationServerConfig.java
package com.example.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
#Configuration
#EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
#Autowired
private AuthenticationManager authenticationManager;
#Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenthicated()");
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("clientid")
.secret("secret")
.authorizedGrantTypes("authorization_code")
.scopes("user_info")
.autoApprove(true);
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
}
ResourceServerConfig.java
package com.example.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
#EnableResourceServer
#Configuration
public class ResourceServerConfig extends WebSecurityConfigurerAdapter {
#Autowired
private AuthenticationManager authenticationManager;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.requestMatchers().antMatchers("/").and().authorizeRequests().anyRequest().authenticated();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.parentAuthenticationManager(authenticationManager)
.inMemoryAuthentication().withUser("admin")
.password("admin")
.roles("ADMIN");
}
}
ProductRestController.java
#RestController
#RequestMapping("/product")
public class ProductRestController {
#RequestMapping(value = "/{id}", method = RequestMethod.GET)
#ResponseBody
public String getProductById(#PathVariable("id") int id) {
System.out.println("In Controller");
return "Hello";
}
Application Console Log:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.7.RELEASE)
2017-09-22 11:40:51.155 INFO 10744 --- [ restartedMain] c.o.inventory.launch.Application : Starting Application on Twinkle-PC with PID 10744 (D:\OrderhiveSpring\orderhive-inventory\bin started by Twinkle in D:\OrderhiveSpring\orderhive-inventory)
2017-09-22 11:40:51.155 INFO 10744 --- [ restartedMain] c.o.inventory.launch.Application : No active profile set, falling back to default profiles: default
2017-09-22 11:40:51.155 INFO 10744 --- [ restartedMain] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#9cbf79e: startup date [Fri Sep 22 11:40:51 UTC 2017]; root of context hierarchy
2017-09-22 11:40:52.050 INFO 10744 --- [ restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8888 (http)
2017-09-22 11:40:52.050 INFO 10744 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2017-09-22 11:40:52.051 INFO 10744 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.20
2017-09-22 11:40:52.063 INFO 10744 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2017-09-22 11:40:52.064 INFO 10744 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 909 ms
2017-09-22 11:40:52.124 INFO 10744 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-09-22 11:40:52.124 INFO 10744 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-09-22 11:40:52.124 INFO 10744 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-09-22 11:40:52.124 INFO 10744 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2017-09-22 11:40:52.124 INFO 10744 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2017-09-22 11:40:52.124 INFO 10744 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2017-09-22 11:40:58.354 INFO 10744 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2017-09-22 11:40:58.355 INFO 10744 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2017-09-22 11:40:58.362 INFO 10744 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2017-09-22 11:40:58.592 INFO 10744 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2017-09-22 11:40:58.856 INFO 10744 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#9cbf79e: startup date [Fri Sep 22 11:40:51 UTC 2017]; root of context hierarchy
2017-09-22 11:40:58.871 INFO 10744 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/product/{id}],methods=[GET]}" onto public java.lang.String com.orderhive.inventory.controller.ProductRestController.getProductById(int)
2017-09-22 11:40:58.871 INFO 10744 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-09-22 11:40:58.871 INFO 10744 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-09-22 11:40:58.887 INFO 10744 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-22 11:40:58.887 INFO 10744 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-22 11:40:58.902 INFO 10744 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-22 11:40:58.949 INFO 10744 --- [ restartedMain] b.a.s.AuthenticationManagerConfiguration :
Using default security password: a1f8d8ad-e937-4dd6-8be2-2648a9ed9a80
2017-09-22 11:40:58.964 INFO 10744 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/css/**'], Ant [pattern='/js/**'], Ant [pattern='/images/**'], Ant [pattern='/webjars/**'], Ant [pattern='/**/favicon.ico'], Ant [pattern='/error']]], []
2017-09-22 11:40:58.964 INFO 10744 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/**']]], [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#6a1033a9, org.springframework.security.web.context.SecurityContextPersistenceFilter#35d7fa68, org.springframework.security.web.header.HeaderWriterFilter#7d6e8d02, org.springframework.security.web.authentication.logout.LogoutFilter#e859232, org.springframework.security.web.authentication.www.BasicAuthenticationFilter#40b3d30, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#57b0571b, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#5e3fd672, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#48992772, org.springframework.security.web.session.SessionManagementFilter#69c735a2, org.springframework.security.web.access.ExceptionTranslationFilter#723216e7, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#e7327d0]
2017-09-22 11:40:59.002 INFO 10744 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2017-09-22 11:40:59.042 INFO 10744 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-09-22 11:40:59.054 INFO 10744 --- [ restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8888 (http)
2017-09-22 11:40:59.056 INFO 10744 --- [ restartedMain] c.o.inventory.launch.Application : Started Application in 7.936 seconds (JVM running for 1520.559)
In this log, GET /product/id is mapped but POST /oauth/token or any of the OAuth paths are not mapped and hence it gives a 404 not found error.
I have uploaded the configurations,let me know if any config is missing for OAuth2 security.

I think you are missing WebMvcConfigurerAdapter implementation, I have implemented the same Ouath2 applications using same technologies like spring boot. You can verify your config files, GitHub links are here-
https://github.com/manishsingh27/TokenBasedAuth/blob/main/authz/src/main/java/com/adms/authz/config/WebConfiguration.java
https://github.com/manishsingh27/TokenBasedAuth/blob/main/authz/src/main/java/com/adms/authz/config/AuthorizationConfiguration.java

Related

How to inject List of String arrays in spring from properties file?

how to create a nested arrays in list in application properties, and insert it as a value?
#Value("${LIST_OF_NESTED_ARRAYS}")
List<String[]> list;
Yes, By using Spring Expression Language it can be achieved.
Code:
package com.test.listofarray;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import lombok.extern.slf4j.Slf4j;
#SpringBootApplication
#Slf4j
public class TestApplication implements CommandLineRunner {
#Value("#{'${LIST_OF_NESTED_ARRAYS}'.split(';')}")
private List<String[]> list;
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
list.forEach(array -> log.info("array ----> {}", Arrays.toString(array)));
}
}
application.properties
LIST_OF_NESTED_ARRAYS=India,USA,Brazil;Asia,Africa
use semi-column(;) to separate the values of each array in the above property and give the same semi-column(;) in the split function inside #value annotation.
Verify the output of the injected list in the below output log.
Output:
2021-11-01 17:48:39.105 INFO 11352 --- [ main] com.resilience.retry.RetryApplication : No active profile set, falling back to default profiles: default
2021-11-01 17:48:42.184 INFO 11352 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-11-01 17:48:42.206 INFO 11352 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-11-01 17:48:42.207 INFO 11352 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.54]
2021-11-01 17:48:42.411 INFO 11352 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-11-01 17:48:42.411 INFO 11352 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 3235 ms
2021-11-01 17:48:45.139 INFO 11352 --- [ main] o.s.b.a.e.web.EndpointLinksResolver : Exposing 1 endpoint(s) beneath base path '/actuator'
2021-11-01 17:48:45.256 INFO 11352 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2021-11-01 17:48:45.285 INFO 11352 --- [ main] com.resilience.retry.RetryApplication : Started RetryApplication in 6.946 seconds (JVM running for 7.648)
2021-11-01 17:48:45.397 INFO 11352 --- [ main] com.resilience.retry.RetryApplication : array ----> [India, USA, Brazil]
2021-11-01 17:48:45.400 INFO 11352 --- [ main] com.resilience.retry.RetryApplication : array ----> [Asia, Africa]
2021-11-01 17:49:03.860 INFO 11352 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-11-01 17:49:03.861 INFO 11352 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2021-11-01 17:49:03.862 INFO 11352 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
If you are using application.yml you can do it as follows:
yourProperty:
- - "Array1 - String1"
- "Array1 - String2"
- - "Array2 - String1"
- "Array2 - String2"

Illegal state exception: Error during attachment using: co.elastic.apm.attach.bytebuddy.agent.ByteBuddyAgent

I just created one application with springboot , used the Elastic APM attacher of APM tool. When i run the apm attacher, it generates error exception as shown below. Code used to generate the error:
package com.howtodoinjava.demo;
import org.springframework.boot.SpringApplication;
import co.elastic.apm.attach.*;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringBootDemoApplication {
public static void main(String[] args) {
ElasticApmAttacher.attach();
SpringApplication.run(SpringBootDemoApplication.class, args);
}
}
---------------------------------------------------------------------
IDE: Eclipse
Spring boot
Error exception :
Exception in thread "main" java.lang.IllegalStateException: Error during attachment using: co.elastic.apm.attach.bytebuddy.agent.ByteBuddyAgent$AttachmentProvider$Compound#6debcae2
at co.elastic.apm.attach.bytebuddy.agent.ByteBuddyAgent.install(ByteBuddyAgent.java:608)
at co.elastic.apm.attach.bytebuddy.agent.ByteBuddyAgent.attach(ByteBuddyAgent.java:268)
at co.elastic.apm.attach.ElasticApmAttacher.attach(ElasticApmAttacher.java:166)
at co.elastic.apm.attach.ElasticApmAttacher.attach(ElasticApmAttacher.java:120)
at co.elastic.apm.attach.ElasticApmAttacher.attach(ElasticApmAttacher.java:77)
at com.howtodoinjava.demo.SpringBootDemoApplication.main(SpringBootDemoApplication.java:11)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at co.elastic.apm.attach.bytebuddy.agent.Attacher.install(Attacher.java:106)
at co.elastic.apm.attach.bytebuddy.agent.ByteBuddyAgent.install(ByteBuddyAgent.java:603)
... 5 more
Caused by: java.lang.NoSuchMethodError: com.sun.jna.Native.load(Ljava/lang/String;Ljava/lang/Class;Ljava/util/Map;)Lcom/sun/jna/Library;
at com.sun.jna.platform.win32.Kernel32.<clinit>(Kernel32.java:43)
at co.elastic.apm.attach.bytebuddy.agent.VirtualMachine$ForHotSpot$Connection$ForJnaWindowsNamedPipe$Factory.connect(VirtualMachine.java:1235)
at co.elastic.apm.attach.bytebuddy.agent.VirtualMachine$ForHotSpot.attach(VirtualMachine.java:256)
at co.elastic.apm.attach.bytebuddy.agent.VirtualMachine$ForHotSpot.attach(VirtualMachine.java:239)
... 11 more
---------------------------
But if I try to run the application commenting the line i.e //ElasticApmAttacher.attach(); from same code, it runs successfully
package com.howtodoinjava.demo;
import org.springframework.boot.SpringApplication;
import co.elastic.apm.attach.*;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringBootDemoApplication {
public static void main(String[] args) {
//ElasticApmAttacher.attach();
SpringApplication.run(SpringBootDemoApplication.class, args);
}
}
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.4.0.RELEASE)
2019-12-07 22:58:30.086 INFO 16984 --- [ main] c.h.demo.SpringBootDemoApplication : Starting SpringBootDemoApplication on LP-ArvindK with PID 16984 (C:\Users\arvind.kumar\Downloads\springbootdemo-hello-world-rest\springbootdemo\target\classes started by Arvind.Kumar in C:\Users\arvind.kumar\Downloads\springbootdemo-hello-world-rest\springbootdemo)
2019-12-07 22:58:30.090 INFO 16984 --- [ main] c.h.demo.SpringBootDemoApplication : No active profile set, falling back to default profiles: default
2019-12-07 22:58:30.130 INFO 16984 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#647fd8ce: startup date [Sat Dec 07 22:58:30 IST 2019]; root of context hierarchy
2019-12-07 22:58:31.046 INFO 16984 --- [ main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2019-12-07 22:58:31.107 INFO 16984 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [class org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$64c40b86] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-12-07 22:58:31.431 INFO 16984 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8081 (http)
2019-12-07 22:58:31.439 INFO 16984 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2019-12-07 22:58:31.439 INFO 16984 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.4
2019-12-07 22:58:31.610 INFO 16984 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-12-07 22:58:31.610 INFO 16984 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1484 ms
2019-12-07 22:58:31.734 INFO 16984 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2019-12-07 22:58:31.734 INFO 16984 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2019-12-07 22:58:31.734 INFO 16984 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2019-12-07 22:58:31.734 INFO 16984 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2019-12-07 22:58:31.734 INFO 16984 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2019-12-07 22:58:32.038 INFO 16984 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2019-12-07 22:58:32.050 INFO 16984 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2019-12-07 22:58:32.138 INFO 16984 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.0.9.Final}
2019-12-07 22:58:32.142 INFO 16984 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2019-12-07 22:58:32.142 INFO 16984 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2019-12-07 22:58:32.230 INFO 16984 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2019-12-07 22:58:32.350 INFO 16984 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.HSQLDialect
2019-12-07 22:58:32.489 INFO 16984 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
2019-12-07 22:58:32.489 INFO 16984 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete
2019-12-07 22:58:32.501 INFO 16984 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-12-07 22:58:32.830 INFO 16984 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#647fd8ce: startup date [Sat Dec 07 22:58:30 IST 2019]; root of context hierarchy
2019-12-07 22:58:32.878 INFO 16984 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto public java.util.List<com.howtodoinjava.demo.model.Employee> com.howtodoinjava.demo.controller.EmployeeController.getEmployees()
2019-12-07 22:58:32.878 INFO 16984 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2019-12-07 22:58:32.878 INFO 16984 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2019-12-07 22:58:32.910 INFO 16984 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-12-07 22:58:32.910 INFO 16984 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-12-07 22:58:32.938 INFO 16984 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-12-07 22:58:33.167 INFO 16984 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2019-12-07 22:58:33.205 INFO 16984 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8081 (http)
2019-12-07 22:58:33.209 INFO 16984 --- [ main] c.h.demo.SpringBootDemoApplication : Started SpringBootDemoApplication in 3.365 seconds (JVM running for 4.327)
i am searching for solution but so far clueless. Can someone please suggest how to resolve it
The exception comes from the constructur of the Kernel32 class which is a class of the Maven coordinate net.java.dev.jna:jna-platform which itself depends on net.java.dev.jna:jna. It seems to me like you have to incompatible versions of those dependencies on the class path.
I assume that you use version 4 of JNA core and version 5 of JNA platform. Upgrade the first or downgrade the latter and the error should disappear.

Cannot enable APR Protocol on Embedded Tomcat

I am trying to use the APR protocol in my Spring Boot project.
Till now i have downloaded the tomcat-native library and did what it instructed me to do, which are ./configure , make and make install. After that i copied all libtcnative files with different extensions to /usr/lib. Now Embedded Tomcat has found all tomcat-native files but it is not running tomcat using the APR protocol.
I have configured my project to run in https with a letsencrypt certificate in http/2 and I am using Ubuntu 16.04, Java 1.8.191, Spring Boot 2.0.7. Below is my logtrace when my server starts:
/usr/lib/jvm/java-1.8.0-openjdk-amd64/bin/java -XX:TieredStopAtLevel=1 -noverify -Dspring.output.ansi.enabled=always -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=44947 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Djava.rmi.server.hostname=localhost -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true -javaagent:/home/samim/IntalledSoftware/idea-IU-173.4301.25/lib/idea_rt.jar=37149:/home/samim/IntalledSoftware/idea-IU-173.4301.25/bin -Dfile.encoding=UTF-8 -classpath /usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/charsets.jar:/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/ext/cldrdata.jar:/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/ext/dnsns.jar:/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/ext/icedtea-sound.jar:/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/ext/jaccess.jar:/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/ext/localedata.jar:/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/ext/nashorn.jar:/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/ext/sunec.jar:/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/ext/sunjce_provider.jar:/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/ext/sunpkcs11.jar:/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/ext/zipfs.jar:/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/jce.jar:/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/jsse.jar:/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/management-agent.jar:/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/resources.jar:/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/rt.jar:/root/IdeaProjects/templateprocessor/target/classes:/root/.m2/repository/org/springframework/boot/spring-boot-starter-actuator/2.0.7.RELEASE/spring-boot-starter-actuator-2.0.7.RELEASE.jar:/root/.m2/repository/org/springframework/boot/spring-boot-starter/2.0.7.RELEASE/spring-boot-starter-2.0.7.RELEASE.jar:/root/.m2/repository/org/springframework/boot/spring-boot-starter-logging/2.0.7.RELEASE/spring-boot-starter-logging-2.0.7.RELEASE.jar:/root/.m2/repository/ch/qos/logback/logback-classic/1.2.3/logback-classic-1.2.3.jar:/root/.m2/repository/ch/qos/logback/logback-core/1.2.3/logback-core-1.2.3.jar:/root/.m2/repository/org/apache/logging/log4j/log4j-to-slf4j/2.10.0/log4j-to-slf4j-2.10.0.jar:/root/.m2/repository/org/apache/logging/log4j/log4j-api/2.10.0/log4j-api-2.10.0.jar:/root/.m2/repository/org/slf4j/jul-to-slf4j/1.7.25/jul-to-slf4j-1.7.25.jar:/root/.m2/repository/javax/annotation/javax.annotation-api/1.3.2/javax.annotation-api-1.3.2.jar:/root/.m2/repository/org/yaml/snakeyaml/1.19/snakeyaml-1.19.jar:/root/.m2/repository/org/springframework/boot/spring-boot-actuator-autoconfigure/2.0.7.RELEASE/spring-boot-actuator-autoconfigure-2.0.7.RELEASE.jar:/root/.m2/repository/org/springframework/boot/spring-boot-actuator/2.0.7.RELEASE/spring-boot-actuator-2.0.7.RELEASE.jar:/root/.m2/repository/com/fasterxml/jackson/core/jackson-databind/2.9.7/jackson-databind-2.9.7.jar:/root/.m2/repository/com/fasterxml/jackson/core/jackson-annotations/2.9.0/jackson-annotations-2.9.0.jar:/root/.m2/repository/com/fasterxml/jackson/core/jackson-core/2.9.7/jackson-core-2.9.7.jar:/root/.m2/repository/org/springframework/spring-context/5.0.11.RELEASE/spring-context-5.0.11.RELEASE.jar:/root/.m2/repository/com/fasterxml/jackson/datatype/jackson-datatype-jsr310/2.9.7/jackson-datatype-jsr310-2.9.7.jar:/root/.m2/repository/io/micrometer/micrometer-core/1.0.8/micrometer-core-1.0.8.jar:/root/.m2/repository/org/hdrhistogram/HdrHistogram/2.1.10/HdrHistogram-2.1.10.jar:/root/.m2/repository/org/latencyutils/LatencyUtils/2.0.3/LatencyUtils-2.0.3.jar:/root/.m2/repository/org/springframework/boot/spring-boot-starter-security/2.0.7.RELEASE/spring-boot-starter-security-2.0.7.RELEASE.jar:/root/.m2/repository/org/springframework/spring-aop/5.0.11.RELEASE/spring-aop-5.0.11.RELEASE.jar:/root/.m2/repository/org/springframework/spring-beans/5.0.11.RELEASE/spring-beans-5.0.11.RELEASE.jar:/root/.m2/repository/org/springframework/security/spring-security-config/5.0.10.RELEASE/spring-security-config-5.0.10.RELEASE.jar:/root/.m2/repository/org/springframework/security/spring-security-web/5.0.10.RELEASE/spring-security-web-5.0.10.RELEASE.jar:/root/.m2/repository/org/springframework/spring-expression/5.0.11.RELEASE/spring-expression-5.0.11.RELEASE.jar:/root/.m2/repository/org/thymeleaf/extras/thymeleaf-extras-springsecurity4/3.0.4.RELEASE/thymeleaf-extras-springsecurity4-3.0.4.RELEASE.jar:/root/.m2/repository/org/slf4j/slf4j-api/1.7.25/slf4j-api-1.7.25.jar:/root/.m2/repository/org/springframework/boot/spring-boot-starter-thymeleaf/2.0.7.RELEASE/spring-boot-starter-thymeleaf-2.0.7.RELEASE.jar:/root/.m2/repository/org/thymeleaf/thymeleaf-spring5/3.0.11.RELEASE/thymeleaf-spring5-3.0.11.RELEASE.jar:/root/.m2/repository/org/thymeleaf/thymeleaf/3.0.11.RELEASE/thymeleaf-3.0.11.RELEASE.jar:/root/.m2/repository/org/attoparser/attoparser/2.0.5.RELEASE/attoparser-2.0.5.RELEASE.jar:/root/.m2/repository/org/unbescape/unbescape/1.1.6.RELEASE/unbescape-1.1.6.RELEASE.jar:/root/.m2/repository/org/thymeleaf/extras/thymeleaf-extras-java8time/3.0.2.RELEASE/thymeleaf-extras-java8time-3.0.2.RELEASE.jar:/root/.m2/repository/org/springframework/boot/spring-boot-starter-web/2.0.7.RELEASE/spring-boot-starter-web-2.0.7.RELEASE.jar:/root/.m2/repository/org/springframework/boot/spring-boot-starter-json/2.0.7.RELEASE/spring-boot-starter-json-2.0.7.RELEASE.jar:/root/.m2/repository/com/fasterxml/jackson/datatype/jackson-datatype-jdk8/2.9.7/jackson-datatype-jdk8-2.9.7.jar:/root/.m2/repository/com/fasterxml/jackson/module/jackson-module-parameter-names/2.9.7/jackson-module-parameter-names-2.9.7.jar:/root/.m2/repository/org/springframework/boot/spring-boot-starter-tomcat/2.0.7.RELEASE/spring-boot-starter-tomcat-2.0.7.RELEASE.jar:/root/.m2/repository/org/apache/tomcat/embed/tomcat-embed-core/8.5.35/tomcat-embed-core-8.5.35.jar:/root/.m2/repository/org/apache/tomcat/embed/tomcat-embed-el/8.5.35/tomcat-embed-el-8.5.35.jar:/root/.m2/repository/org/apache/tomcat/embed/tomcat-embed-websocket/8.5.35/tomcat-embed-websocket-8.5.35.jar:/root/.m2/repository/org/hibernate/validator/hibernate-validator/6.0.13.Final/hibernate-validator-6.0.13.Final.jar:/root/.m2/repository/javax/validation/validation-api/2.0.1.Final/validation-api-2.0.1.Final.jar:/root/.m2/repository/org/jboss/logging/jboss-logging/3.3.2.Final/jboss-logging-3.3.2.Final.jar:/root/.m2/repository/com/fasterxml/classmate/1.3.4/classmate-1.3.4.jar:/root/.m2/repository/org/springframework/spring-web/5.0.11.RELEASE/spring-web-5.0.11.RELEASE.jar:/root/.m2/repository/org/springframework/spring-webmvc/5.0.11.RELEASE/spring-webmvc-5.0.11.RELEASE.jar:/root/.m2/repository/org/springframework/boot/spring-boot-devtools/2.0.7.RELEASE/spring-boot-devtools-2.0.7.RELEASE.jar:/root/.m2/repository/org/springframework/boot/spring-boot/2.0.7.RELEASE/spring-boot-2.0.7.RELEASE.jar:/root/.m2/repository/org/springframework/boot/spring-boot-autoconfigure/2.0.7.RELEASE/spring-boot-autoconfigure-2.0.7.RELEASE.jar:/root/.m2/repository/org/springframework/spring-core/5.0.11.RELEASE/spring-core-5.0.11.RELEASE.jar:/root/.m2/repository/org/springframework/spring-jcl/5.0.11.RELEASE/spring-jcl-5.0.11.RELEASE.jar:/root/.m2/repository/org/springframework/security/spring-security-core/5.0.10.RELEASE/spring-security-core-5.0.10.RELEASE.jar com.siqes.TemplateprocessorApplication
19:23:01.616 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : []
19:23:01.620 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Excluded patterns for restart : [/spring-boot-actuator/target/classes/, /spring-boot-devtools/target/classes/, /spring-boot/target/classes/, /spring-boot-starter-[\w-]+/, /spring-boot-autoconfigure/target/classes/, /spring-boot-starter/target/classes/]
19:23:01.620 [main] DEBUG org.springframework.boot.devtools.restart.ChangeableUrls - Matching URLs for reloading : [file:/root/IdeaProjects/templateprocessor/target/classes/]
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.7.RELEASE)
2018-12-26 19:23:02.067 INFO 10929 --- [ restartedMain] com.siqes.TemplateprocessorApplication : Starting TemplateprocessorApplication on dev-76 with PID 10929 (/root/IdeaProjects/templateprocessor/target/classes started by root in /root/IdeaProjects/templateprocessor)
2018-12-26 19:23:02.069 INFO 10929 --- [ restartedMain] com.siqes.TemplateprocessorApplication : No active profile set, falling back to default profiles: default
2018-12-26 19:23:02.158 INFO 10929 --- [ restartedMain] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#2690e06e: startup date [Wed Dec 26 19:23:02 IST 2018]; root of context hierarchy
2018-12-26 19:23:04.260 INFO 10929 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 443 (https) 80 (http)
2018-12-26 19:23:04.283 INFO 10929 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-12-26 19:23:04.284 INFO 10929 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.35
2018-12-26 19:23:04.288 INFO 10929 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : Loaded APR based Apache Tomcat Native library [1.2.19] using APR version [1.5.2].
2018-12-26 19:23:04.289 INFO 10929 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
2018-12-26 19:23:04.289 INFO 10929 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true]
2018-12-26 19:23:04.292 INFO 10929 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : OpenSSL successfully initialized [OpenSSL 1.1.1a 20 Nov 2018]
2018-12-26 19:23:04.356 INFO 10929 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-12-26 19:23:04.356 INFO 10929 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2204 ms
2018-12-26 19:23:04.975 INFO 10929 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-12-26 19:23:04.975 INFO 10929 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'webMvcMetricsFilter' to: [/*]
2018-12-26 19:23:04.976 INFO 10929 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-12-26 19:23:04.976 INFO 10929 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-12-26 19:23:04.976 INFO 10929 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-12-26 19:23:04.976 INFO 10929 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2018-12-26 19:23:04.977 INFO 10929 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpTraceFilter' to: [/*]
2018-12-26 19:23:04.977 INFO 10929 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2018-12-26 19:23:05.150 INFO 10929 --- [ restartedMain] .s.s.UserDetailsServiceAutoConfiguration :
Using generated security password: 7c0a25e1-aa1f-4b57-884f-94fbd8afc570
2018-12-26 19:23:05.267 INFO 10929 --- [ restartedMain] o.s.s.w.a.c.ChannelProcessingFilter : Validated configuration attributes
2018-12-26 19:23:05.290 INFO 10929 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher#1, [org.springframework.security.web.access.channel.ChannelProcessingFilter#c0cdb3d, org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#2b320338, org.springframework.security.web.context.SecurityContextPersistenceFilter#325f68d3, org.springframework.security.web.header.HeaderWriterFilter#48e85931, org.springframework.security.web.authentication.logout.LogoutFilter#240e5c77, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#60808cc4, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#145d0cc7, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#68485018, org.springframework.security.web.session.SessionManagementFilter#d3c6627, org.springframework.security.web.access.ExceptionTranslationFilter#71d8532b, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#787589ce]
2018-12-26 19:23:05.380 INFO 10929 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-12-26 19:23:05.659 INFO 10929 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#2690e06e: startup date [Wed Dec 26 19:23:02 IST 2018]; root of context hierarchy
2018-12-26 19:23:05.710 INFO 10929 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/],methods=[GET]}" onto public java.lang.String com.siqes.templateprocessor.controller.MainController.home()
2018-12-26 19:23:05.711 INFO 10929 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/template-processor],methods=[GET]}" onto public java.lang.String com.siqes.templateprocessor.controller.MainController.templateProcessor()
2018-12-26 19:23:05.716 INFO 10929 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-12-26 19:23:05.716 INFO 10929 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-12-26 19:23:05.741 INFO 10929 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-12-26 19:23:05.741 INFO 10929 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-12-26 19:23:06.038 INFO 10929 --- [ restartedMain] o.s.b.a.e.web.EndpointLinksResolver : Exposing 2 endpoint(s) beneath base path '/actuator'
2018-12-26 19:23:06.048 INFO 10929 --- [ restartedMain] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "{[/actuator/health],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
2018-12-26 19:23:06.049 INFO 10929 --- [ restartedMain] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "{[/actuator/info],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
2018-12-26 19:23:06.051 INFO 10929 --- [ restartedMain] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "{[/actuator],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto protected java.util.Map<java.lang.String, java.util.Map<java.lang.String, org.springframework.boot.actuate.endpoint.web.Link>> org.springframework.boot.actuate.endpoint.web.servlet.WebMvcEndpointHandlerMapping.links(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-12-26 19:23:06.071 WARN 10929 --- [ restartedMain] on$ThymeleafSecurityDialectConfiguration : Auto-configuration for thymeleaf-extras-springsecurity4 is deprecated in favour of thymeleaf-extras-springsecurity5
2018-12-26 19:23:06.126 INFO 10929 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2018-12-26 19:23:06.168 INFO 10929 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-12-26 19:23:06.611 INFO 10929 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 443 (https) 80 (http) with context path ''
2018-12-26 19:23:06.616 INFO 10929 --- [ restartedMain] com.siqes.TemplateprocessorApplication : Started TemplateprocessorApplication in 4.983 seconds (JVM running for 5.92)
2018-12-26 19:23:07.282 INFO 10929 --- [on(4)-127.0.0.1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-12-26 19:23:07.282 INFO 10929 --- [on(4)-127.0.0.1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2018-12-26 19:23:07.298 INFO 10929 --- [on(4)-127.0.0.1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 16 ms
My beans are as follows:
#Configuration
public class ConnectorConfig {
#Bean
public ServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
#Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
};
tomcat.addAdditionalTomcatConnectors(redirectConnector());
return tomcat;
}
private Connector redirectConnector() {
Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
connector.setScheme("http");
connector.setPort(80);
connector.setSecure(false);
connector.setRedirectPort(443);
return connector;
}
}
I even tried using the AprLifecycleListener like below:
#Bean
public ServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
#Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
};
tomcat.addAdditionalTomcatConnectors(redirectConnector());
LifecycleListener aprLifecycleListener = new AprLifecycleListener();
tomcat.setProtocol("org.apache.coyote.http11.Http11AprProtocol");
tomcat.addContextLifecycleListeners(aprLifecycleListener);
return tomcat;
}
But i get error while starting tomcat with the APR:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.7.RELEASE)
2018-12-26 20:05:29.201 INFO 11939 --- [ restartedMain] com.siqes.TemplateprocessorApplication : Starting TemplateprocessorApplication on dev-76 with PID 11939 (/root/IdeaProjects/templateprocessor/target/classes started by root in /root/IdeaProjects/templateprocessor)
2018-12-26 20:05:29.203 INFO 11939 --- [ restartedMain] com.siqes.TemplateprocessorApplication : No active profile set, falling back to default profiles: default
2018-12-26 20:05:29.266 INFO 11939 --- [ restartedMain] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#57b72439: startup date [Wed Dec 26 20:05:29 IST 2018]; root of context hierarchy
2018-12-26 20:05:31.222 WARN 11939 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is java.lang.IllegalStateException: To use SSL, the connector's protocol handler must be an AbstractHttp11JsseProtocol subclass
2018-12-26 20:05:31.235 INFO 11939 --- [ restartedMain] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-12-26 20:05:31.244 ERROR 11939 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is java.lang.IllegalStateException: To use SSL, the connector's protocol handler must be an AbstractHttp11JsseProtocol subclass
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:157) ~[spring-boot-2.0.7.RELEASE.jar:2.0.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-5.0.11.RELEASE.jar:5.0.11.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.0.7.RELEASE.jar:2.0.7.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754) [spring-boot-2.0.7.RELEASE.jar:2.0.7.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:386) [spring-boot-2.0.7.RELEASE.jar:2.0.7.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) [spring-boot-2.0.7.RELEASE.jar:2.0.7.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1242) [spring-boot-2.0.7.RELEASE.jar:2.0.7.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1230) [spring-boot-2.0.7.RELEASE.jar:2.0.7.RELEASE]
at com.siqes.TemplateprocessorApplication.main(TemplateprocessorApplication.java:10) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.0.7.RELEASE.jar:2.0.7.RELEASE]
Caused by: java.lang.IllegalStateException: To use SSL, the connector's protocol handler must be an AbstractHttp11JsseProtocol subclass
at org.springframework.util.Assert.state(Assert.java:73) ~[spring-core-5.0.11.RELEASE.jar:5.0.11.RELEASE]
at org.springframework.boot.web.embedded.tomcat.SslConnectorCustomizer.customize(SslConnectorCustomizer.java:55) ~[spring-boot-2.0.7.RELEASE.jar:2.0.7.RELEASE]
at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.customizeSsl(TomcatServletWebServerFactory.java:317) ~[spring-boot-2.0.7.RELEASE.jar:2.0.7.RELEASE]
at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.customizeConnector(TomcatServletWebServerFactory.java:300) ~[spring-boot-2.0.7.RELEASE.jar:2.0.7.RELEASE]
at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getWebServer(TomcatServletWebServerFactory.java:166) ~[spring-boot-2.0.7.RELEASE.jar:2.0.7.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:181) ~[spring-boot-2.0.7.RELEASE.jar:2.0.7.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:154) ~[spring-boot-2.0.7.RELEASE.jar:2.0.7.RELEASE]
... 13 common frames omitted
Process finished with exit code 0
I had to remove some lines as stackoverflow has a limit of 30000 character. I am posting it in a comment. Please Help.

Spring Boot Reactive Mongo Hangs on startup

I have a Spring Boot application that uses reactive Mongo DB drivers that hangs on startup.
Logs:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.1.RELEASE)
2018-05-20 13:45:47.923 DEBUG 26675 --- [ main] s.b.w.r.c.StandardReactiveWebEnvironment : Adding PropertySource 'systemProperties' with lowest search precedence
2018-05-20 13:45:47.924 DEBUG 26675 --- [ main] s.b.w.r.c.StandardReactiveWebEnvironment : Adding PropertySource 'systemEnvironment' with lowest search precedence
2018-05-20 13:45:47.924 DEBUG 26675 --- [ main] s.b.w.r.c.StandardReactiveWebEnvironment : Initialized StandardReactiveWebEnvironment with PropertySources [MapPropertySource {name='systemProperties'}, SystemEnvironmentPropertySource {name='systemEnvironment'}]
2018-05-20 13:45:48.018 INFO 26675 --- [ main] c.a.m.mobsters.MobstersApplication : Starting MobstersApplication on Adrians-iMac.local with PID 26675 (/Users/adrian/IdeaProjects/MobstersREST/backend/target/classes started by adrian in /Users/adrian/IdeaProjects/MobstersREST)
2018-05-20 13:45:48.018 INFO 26675 --- [ main] c.a.m.mobsters.MobstersApplication : The following profiles are active: prod
2018-05-20 13:45:48.018 DEBUG 26675 --- [ main] o.s.boot.SpringApplication : Loading source class com.adrian.mobstersrest.mobsters.MobstersApplication
2018-05-20 13:45:48.092 DEBUG 26675 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Activated profiles prod
2018-05-20 13:45:48.093 DEBUG 26675 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Loaded config file 'file:/Users/adrian/IdeaProjects/MobstersREST/backend/target/classes/application.yml' (classpath:/application.yml) for profile prod
2018-05-20 13:45:48.093 DEBUG 26675 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Loaded config file 'file:/Users/adrian/IdeaProjects/MobstersREST/backend/target/classes/application.yml' (classpath:/application.yml)
2018-05-20 13:45:48.097 INFO 26675 --- [ main] onfigReactiveWebServerApplicationContext : Refreshing org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext#2f9f7dcf: startup date [Sun May 20 13:45:48 EDT 2018]; root of context hierarchy
2018-05-20 13:45:48.098 DEBUG 26675 --- [ main] onfigReactiveWebServerApplicationContext : Bean factory for org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext#2f9f7dcf: org.springframework.beans.factory.support.DefaultListableBeanFactory#2525ff7e: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,mobstersApplication]; root of factory hierarchy
2018-05-20 13:45:49.075 DEBUG 26675 --- [ main] o.s.b.a.AutoConfigurationPackages : #EnableAutoConfiguration was declared on a class in the package 'com.adrian.mobstersrest.mobsters'. Automatic #Repository and #Entity scanning is enabled.
2018-05-20 13:45:49.662 DEBUG 26675 --- [ main] onfigReactiveWebServerApplicationContext : Unable to locate MessageSource with name 'messageSource': using default [org.springframework.context.support.DelegatingMessageSource#619bd14c]
2018-05-20 13:45:49.662 DEBUG 26675 --- [ main] onfigReactiveWebServerApplicationContext : Unable to locate ApplicationEventMulticaster with name 'applicationEventMulticaster': using default [org.springframework.context.event.SimpleApplicationEventMulticaster#323e8306]
2018-05-20 13:45:49.969 INFO 26675 --- [ main] s.w.r.r.m.a.RequestMappingHandlerMapping : Mapped "{[/],methods=[GET]}" onto public java.lang.String com.adrian.mobstersrest.mobsters.api.v1.controller.IndexController.index()
2018-05-20 13:45:49.982 INFO 26675 --- [ main] s.w.r.r.m.a.RequestMappingHandlerMapping : Mapped "{[/api/v1/mobsters/{username}/queue],methods=[POST]}" onto public org.reactivestreams.Publisher<java.lang.Void> com.adrian.mobstersrest.mobsters.api.v1.controller.MobsterController.queue(java.lang.String)
2018-05-20 13:45:49.983 INFO 26675 --- [ main] s.w.r.r.m.a.RequestMappingHandlerMapping : Mapped "{[/api/v1/mobsters],methods=[GET]}" onto public reactor.core.publisher.Flux<com.adrian.mobstersrest.mobsters.domain.Mobster> com.adrian.mobstersrest.mobsters.api.v1.controller.MobsterController.getMobsters()
2018-05-20 13:45:49.983 INFO 26675 --- [ main] s.w.r.r.m.a.RequestMappingHandlerMapping : Mapped "{[/api/v1/mobsters],methods=[POST]}" onto public org.reactivestreams.Publisher<java.lang.Void> com.adrian.mobstersrest.mobsters.api.v1.controller.MobsterController.addMobster(org.reactivestreams.Publisher<com.adrian.mobstersrest.mobsters.domain.Mobster>)
2018-05-20 13:45:50.054 INFO 26675 --- [ main] o.s.w.r.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.reactive.resource.ResourceWebHandler]
2018-05-20 13:45:50.055 INFO 26675 --- [ main] o.s.w.r.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.reactive.resource.ResourceWebHandler]
2018-05-20 13:45:50.503 INFO 26675 --- [ main] org.mongodb.driver.cluster : Cluster created with settings {hosts=[ds157599.mlab.com:57599], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2018-05-20 13:45:50.830 INFO 26675 --- [ main] org.mongodb.driver.cluster : Cluster created with settings {hosts=[ds157599.mlab.com:57599], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2018-05-20 13:45:51.129 INFO 26675 --- [.mlab.com:57599] org.mongodb.driver.connection : Opened connection [connectionId{localValue:1, serverValue:133602}] to ds157599.mlab.com:57599
2018-05-20 13:45:51.161 INFO 26675 --- [.mlab.com:57599] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=ds157599.mlab.com:57599, type=REPLICA_SET_PRIMARY, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 4, 14]}, minWireVersion=0, maxWireVersion=5, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=null, roundTripTimeNanos=30750252, setName='rs-ds157599', canonicalAddress=ds157599-a.mlab.com:57599, hosts=[ds157599-a.mlab.com:57599], passives=[], arbiters=[], primary='ds157599-a.mlab.com:57599', tagSet=TagSet{[]}, electionId=7fffffff0000000000000001, setVersion=1, lastWriteDate=Sun May 20 13:45:45 EDT 2018, lastUpdateTimeNanos=67395842952667}
2018-05-20 13:45:51.198 INFO 26675 --- [.mlab.com:57599] org.mongodb.driver.connection : Opened connection [connectionId{localValue:2, serverValue:133603}] to ds157599.mlab.com:57599
2018-05-20 13:45:51.239 INFO 26675 --- [.mlab.com:57599] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=ds157599.mlab.com:57599, type=REPLICA_SET_PRIMARY, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 4, 14]}, minWireVersion=0, maxWireVersion=5, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=null, roundTripTimeNanos=41193458, setName='rs-ds157599', canonicalAddress=ds157599-a.mlab.com:57599, hosts=[ds157599-a.mlab.com:57599], passives=[], arbiters=[], primary='ds157599-a.mlab.com:57599', tagSet=TagSet{[]}, electionId=7fffffff0000000000000001, setVersion=1, lastWriteDate=Sun May 20 13:45:45 EDT 2018, lastUpdateTimeNanos=67395921620843}
2018-05-20 13:45:51.456 INFO 26675 --- [ main] o.s.b.a.e.web.EndpointLinksResolver : Exposing 2 endpoint(s) beneath base path '/actuator'
2018-05-20 13:45:51.467 INFO 26675 --- [ main] .b.a.e.w.r.WebFluxEndpointHandlerMapping : Mapped "{[/actuator/health],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public org.reactivestreams.Publisher<org.springframework.http.ResponseEntity<java.lang.Object>> org.springframework.boot.actuate.endpoint.web.reactive.AbstractWebFluxEndpointHandlerMapping$ReadOperationHandler.handle(org.springframework.web.server.ServerWebExchange)
2018-05-20 13:45:51.468 INFO 26675 --- [ main] .b.a.e.w.r.WebFluxEndpointHandlerMapping : Mapped "{[/actuator/info],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public org.reactivestreams.Publisher<org.springframework.http.ResponseEntity<java.lang.Object>> org.springframework.boot.actuate.endpoint.web.reactive.AbstractWebFluxEndpointHandlerMapping$ReadOperationHandler.handle(org.springframework.web.server.ServerWebExchange)
2018-05-20 13:45:51.469 INFO 26675 --- [ main] .b.a.e.w.r.WebFluxEndpointHandlerMapping : Mapped "{[/actuator],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto protected java.util.Map<java.lang.String, java.util.Map<java.lang.String, org.springframework.boot.actuate.endpoint.web.Link>> org.springframework.boot.actuate.endpoint.web.reactive.WebFluxEndpointHandlerMapping.links(org.springframework.web.server.ServerWebExchange)
2018-05-20 13:45:51.562 INFO 26675 --- [ main] o.s.w.r.r.m.a.ControllerMethodResolver : Looking for #ControllerAdvice: org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext#2f9f7dcf: startup date [Sun May 20 13:45:48 EDT 2018]; root of context hierarchy
2018-05-20 13:45:52.538 INFO 26675 --- [ntLoopGroup-2-2] org.mongodb.driver.connection : Opened connection [connectionId{localValue:3, serverValue:133604}] to ds157599.mlab.com:57599
My reactive Mongo configuration:
package com.adrian.mobstersrest.mobsters.config;
import com.mongodb.ConnectionString;
import com.mongodb.reactivestreams.client.MongoClient;
import com.mongodb.reactivestreams.client.MongoClients;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.DependsOn;
import org.springframework.data.mongodb.config.AbstractReactiveMongoConfiguration;
import org.springframework.data.mongodb.core.mapping.event.LoggingEventListener;
import org.springframework.data.mongodb.repository.config.EnableReactiveMongoRepositories;
#SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
#EnableReactiveMongoRepositories
#AutoConfigureAfter(EmbeddedMongoAutoConfiguration.class)
public class MongoConfig extends AbstractReactiveMongoConfiguration {
#Value("${spring.data.mongodb.uri}")
private String uri;
#Override
#Bean
#DependsOn("embeddedMongoServer")
public MongoClient reactiveMongoClient() {
return MongoClients.create(new ConnectionString(uri));
}
#Override
protected String getDatabaseName() {
return "mobsters";
}
#Bean
public LoggingEventListener mongoEventListener() {
return new LoggingEventListener();
}
}
It looks like mongo is hanging according to the logs, it just sits at Opened connection, but never says that my application has been initialized.
This also happens when connecting to a local instance of Mongo ran in a Docker container.
It seems like you should not be using #SpringBootApplication in this class.
You should have a "main" class with a main method that already has #SpringBootApplication and you can add the exclusions there, you shouldn't have more than one #SpringBootApplication in your project. After doing that just delete that annotation from
the MongoConfig class.
#EnableReactiveMongoRepositories
#AutoConfigureAfter(EmbeddedMongoAutoConfiguration.class)
public class MongoConfig extends AbstractReactiveMongoConfiguration {
Edit: i just now noticed that this was posted more than 2 years ago..............

Creating an unsecure endpoint for login on a secured Spring Boot RESTful API - WebConfig seemingly ignored

Thanks for checking out my question!
What I'm trying to do:
I want my RESTful API to have an unsecured endpoint /auth/login that would allow a client to get a JWT token to be used for secure access.
What I've done:
I have a RESTful API I created by essentially really quickly initializing using Spring Initializr with the Spring Security module enabled. After many hours of searching tutorials and guides (Spring Security is very difficult to grok) I've stumbled upon this guide that has a severe lack of code, but in the end I've found a GitLab repo that has a complete implementation of that guide, so I've completely downloaded the security folder. The only problem is that the given implementation is configured to have all URLs authenticated (as can be seen here on line 60), while I want to have /auth/login unsecured. As such, I have altered the configuration override to permit all requests for my desired unsecured endpoint:
WebSecurityConfig.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import java.util.Arrays;
#Configuration
#SuppressWarnings("SpringJavaAutowiringInspection")
#EnableWebSecurity
#EnableAutoConfiguration
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
#Autowired
private JwtAuthenticationProvider authenticationProvider;
#Bean
#Override
public AuthenticationManager authenticationManager() throws Exception {
return new ProviderManager(Arrays.asList(authenticationProvider));
}
#Bean
public JwtAuthenticationTokenFilter authenticationTokenFilterBean() throws Exception {
JwtAuthenticationTokenFilter authenticationTokenFilter = new JwtAuthenticationTokenFilter();
authenticationTokenFilter.setAuthenticationManager(authenticationManager());
authenticationTokenFilter.setAuthenticationSuccessHandler(new JwtAuthenticationSuccessHandler());
return authenticationTokenFilter;
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/auth/login/");
}
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
// we don't need CSRF because our token is invulnerable
.csrf().disable()
.authorizeRequests()
// allow anonymous resource requests
.antMatchers("/auth/login").permitAll()
// All urls must be authenticated (filter for token always fires (/**)
.anyRequest().authenticated()
.and()
// Call our errorHandler if authentication/authorisation fails
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
.and()
// don't create session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); //.and()
// Custom JWT based security filter
httpSecurity
.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
// disable page caching
httpSecurity.headers().cacheControl();
}
}
What's the problem?
For some reason, whenever I try to make a tokenless request to /auth/login, my server's response remains to be:
{"timestamp":1472057590171,"status":401,"error":"Unauthorized","message":"Authentication Failed: No JWT token found in request headers","path":"/auth/login"}
If I make a request with a token, as I would for a secured endpoint, the response is a 200 OK with all the proper response body.
It's almost as if the server is ignoring my configuration. In JwtAuthenticationTokenFilter.java the constructer's super contains a string that indicated the path the filter is applied to. In my case it is applied to /**, or all paths. According to this guide, the configuration is supposed to override that.
Extra data for debugging:
JwtAuthenticationTokenFilter.java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Filter that orchestrates authentication by using supplied JWT token
*
* #author pascal alma
*/
public class JwtAuthenticationTokenFilter extends AbstractAuthenticationProcessingFilter {
#Value("${jwt.header}")
private String tokenHeader;
public JwtAuthenticationTokenFilter() {
super("/**");
}
/**
* Attempt to authenticate request - basically just pass over to another method to authenticate request headers
*/
#Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {
String header = request.getHeader(this.tokenHeader);
if (header == null || !header.startsWith("Bearer ")) {
throw new JwtTokenMissingException("No JWT token found in request headers");
}
String authToken = header.substring(7);
JwtAuthenticationToken authRequest = new JwtAuthenticationToken(authToken);
return getAuthenticationManager().authenticate(authRequest);
}
/**
* Make sure the rest of the filterchain is satisfied
*
* #param request
* #param response
* #param chain
* #param authResult
* #throws IOException
* #throws ServletException
*/
#Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult)
throws IOException, ServletException {
super.successfulAuthentication(request, response, chain, authResult);
// As this authentication is in HTTP header, after success we need to continue the request normally
// and return the response as if the resource was not secured at all
chain.doFilter(request, response);
}
}
AuthController.java
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/auth")
public class AuthController {
#RequestMapping(path="/login", method = RequestMethod.GET)
public String response() {
return "Hey!";
}
}
Spring Boot log (includes one unauthorized request to the supposedly unsecure /auth/login)
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.4.0.RELEASE)
2016-08-25 01:02:46.367 INFO 21486 --- [ main] com.BackendApplication : No active profile set, falling back to default profiles: default
2016-08-25 01:02:46.423 INFO 21486 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#384ad17b: startup date [Thu Aug 25 01:02:46 HKT 2016]; root of context hierarchy
2016-08-25 01:02:47.390 INFO 21486 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [class org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$afc52b37] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2016-08-25 01:02:47.424 INFO 21486 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.security.config.annotation.configuration.ObjectPostProcessorConfiguration' of type [class org.springframework.security.config.annotation.configuration.ObjectPostProcessorConfiguration$$EnhancerBySpringCGLIB$$4872f371] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2016-08-25 01:02:47.432 INFO 21486 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'objectPostProcessor' of type [class org.springframework.security.config.annotation.configuration.AutowireBeanFactoryObjectPostProcessor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2016-08-25 01:02:47.433 INFO 21486 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler#57a48985' of type [class org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2016-08-25 01:02:47.440 INFO 21486 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration' of type [class org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration$$EnhancerBySpringCGLIB$$6d479623] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2016-08-25 01:02:47.448 INFO 21486 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'methodSecurityMetadataSource' of type [class org.springframework.security.access.method.DelegatingMethodSecurityMetadataSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2016-08-25 01:02:47.686 INFO 21486 --- [ main] org.xnio : XNIO version 3.3.6.Final
2016-08-25 01:02:47.696 INFO 21486 --- [ main] org.xnio.nio : XNIO NIO Implementation Version 3.3.6.Final
2016-08-25 01:02:47.743 WARN 21486 --- [ main] io.undertow.websockets.jsr : UT026009: XNIO worker was not set on WebSocketDeploymentInfo, the default worker will be used
2016-08-25 01:02:47.744 WARN 21486 --- [ main] io.undertow.websockets.jsr : UT026010: Buffer pool was not set on WebSocketDeploymentInfo, the default pool will be used
2016-08-25 01:02:47.753 INFO 21486 --- [ main] io.undertow.servlet : Initializing Spring embedded WebApplicationContext
2016-08-25 01:02:47.753 INFO 21486 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1332 ms
2016-08-25 01:02:48.125 INFO 21486 --- [ main] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-08-25 01:02:48.126 INFO 21486 --- [ main] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2016-08-25 01:02:48.126 INFO 21486 --- [ main] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2016-08-25 01:02:48.126 INFO 21486 --- [ main] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2016-08-25 01:02:48.127 INFO 21486 --- [ main] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2016-08-25 01:02:48.128 INFO 21486 --- [ main] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'authenticationTokenFilterBean' to: [/*]
2016-08-25 01:02:48.128 INFO 21486 --- [ main] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2016-08-25 01:02:48.283 INFO 21486 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2016-08-25 01:02:48.297 INFO 21486 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2016-08-25 01:02:48.339 INFO 21486 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.0.9.Final}
2016-08-25 01:02:48.340 INFO 21486 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2016-08-25 01:02:48.341 INFO 21486 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2016-08-25 01:02:48.366 INFO 21486 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2016-08-25 01:02:48.619 INFO 21486 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2016-08-25 01:02:48.789 INFO 21486 --- [ main] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000228: Running hbm2ddl schema update
2016-08-25 01:02:48.809 INFO 21486 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2016-08-25 01:02:48.886 INFO 21486 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: Ant [pattern='/auth/login/'], []
2016-08-25 01:02:48.914 DEBUG 21486 --- [ main] edFilterInvocationSecurityMetadataSource : Adding web access control expression 'permitAll', for Ant [pattern='/auth/login']
2016-08-25 01:02:48.915 DEBUG 21486 --- [ main] edFilterInvocationSecurityMetadataSource : Adding web access control expression 'authenticated', for org.springframework.security.web.util.matcher.AnyRequestMatcher#1
2016-08-25 01:02:48.919 DEBUG 21486 --- [ main] o.s.s.w.a.i.FilterSecurityInterceptor : Validated configuration attributes
2016-08-25 01:02:48.920 DEBUG 21486 --- [ main] o.s.s.w.a.i.FilterSecurityInterceptor : Validated configuration attributes
2016-08-25 01:02:48.922 INFO 21486 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher#1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#310d57b1, org.springframework.security.web.context.SecurityContextPersistenceFilter#22cb3d59, org.springframework.security.web.header.HeaderWriterFilter#2407a36c, org.springframework.security.web.authentication.logout.LogoutFilter#29bbc391, com..security.JwtAuthenticationTokenFilter#4c7e978c, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#5cff729b, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#5a7b309b, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#143fefaf, org.springframework.security.web.session.SessionManagementFilter#28b8f98a, org.springframework.security.web.access.ExceptionTranslationFilter#6889f56f, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#6b867ee7]
2016-08-25 01:02:48.933 DEBUG 21486 --- [ main] o.s.s.a.i.a.MethodSecurityInterceptor : Validated configuration attributes
2016-08-25 01:02:48.996 INFO 21486 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#384ad17b: startup date [Thu Aug 25 01:02:46 HKT 2016]; root of context hierarchy
2016-08-25 01:02:49.052 INFO 21486 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/auth/login],methods=[GET]}" onto public java.lang.String com..web.AuthController.response()
2016-08-25 01:02:49.053 INFO 21486 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/secure/],methods=[POST]}" onto public com..model.Greeting com..web.MainController.homePage(java.lang.String)
2016-08-25 01:02:49.053 INFO 21486 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/secure/hello],methods=[GET]}" onto public com..model.Greeting com..web.MainController.greeting(java.lang.String)
2016-08-25 01:02:49.053 INFO 21486 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/secure/user || /secure/me],methods=[POST]}" onto public org.springframework.http.ResponseEntity<?> com..web.MainController.user(java.security.Principal)
2016-08-25 01:02:49.055 INFO 21486 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2016-08-25 01:02:49.056 INFO 21486 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2016-08-25 01:02:49.092 INFO 21486 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-08-25 01:02:49.092 INFO 21486 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-08-25 01:02:49.122 INFO 21486 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-08-25 01:02:49.310 DEBUG 21486 --- [ main] eGlobalAuthenticationAutowiredConfigurer : Eagerly initializing {webSecurityConfig=com..security.config.WebSecurityConfig$$EnhancerBySpringCGLIB$$12aaac67#47c40b56}
2016-08-25 01:02:49.312 INFO 21486 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2016-08-25 01:02:49.344 INFO 21486 --- [ main] b.c.e.u.UndertowEmbeddedServletContainer : Undertow started on port(s) 8080 (http)
2016-08-25 01:02:49.347 INFO 21486 --- [ main] com.BackendApplication : Started BackendApplication in 3.256 seconds (JVM running for 3.461)
2016-08-25 01:02:57.681 DEBUG 21486 --- [ XNIO-3 task-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/auth/login'; against '/auth/login/'
2016-08-25 01:02:57.682 DEBUG 21486 --- [ XNIO-3 task-1] o.s.security.web.FilterChainProxy : /auth/login at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2016-08-25 01:02:57.682 DEBUG 21486 --- [ XNIO-3 task-1] o.s.security.web.FilterChainProxy : /auth/login at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2016-08-25 01:02:57.683 DEBUG 21486 --- [ XNIO-3 task-1] o.s.security.web.FilterChainProxy : /auth/login at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2016-08-25 01:02:57.684 DEBUG 21486 --- [ XNIO-3 task-1] o.s.security.web.FilterChainProxy : /auth/login at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
2016-08-25 01:02:57.684 DEBUG 21486 --- [ XNIO-3 task-1] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', GET]
2016-08-25 01:02:57.684 DEBUG 21486 --- [ XNIO-3 task-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/auth/login'; against '/logout'
2016-08-25 01:02:57.684 DEBUG 21486 --- [ XNIO-3 task-1] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', POST]
2016-08-25 01:02:57.684 DEBUG 21486 --- [ XNIO-3 task-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /auth/login' doesn't match 'POST /logout
2016-08-25 01:02:57.684 DEBUG 21486 --- [ XNIO-3 task-1] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', PUT]
2016-08-25 01:02:57.684 DEBUG 21486 --- [ XNIO-3 task-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /auth/login' doesn't match 'PUT /logout
2016-08-25 01:02:57.684 DEBUG 21486 --- [ XNIO-3 task-1] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', DELETE]
2016-08-25 01:02:57.684 DEBUG 21486 --- [ XNIO-3 task-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /auth/login' doesn't match 'DELETE /logout
2016-08-25 01:02:57.684 DEBUG 21486 --- [ XNIO-3 task-1] o.s.s.web.util.matcher.OrRequestMatcher : No matches found
2016-08-25 01:02:57.684 DEBUG 21486 --- [ XNIO-3 task-1] o.s.security.web.FilterChainProxy : /auth/login at position 5 of 11 in additional filter chain; firing Filter: 'JwtAuthenticationTokenFilter'
2016-08-25 01:02:57.684 DEBUG 21486 --- [ XNIO-3 task-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Request '/auth/login' matched by universal pattern '/**'
2016-08-25 01:02:57.684 DEBUG 21486 --- [ XNIO-3 task-1] .a.SimpleUrlAuthenticationFailureHandler : No failure URL set, sending 401 Unauthorized error
2016-08-25 01:02:57.684 DEBUG 21486 --- [ XNIO-3 task-1] o.s.s.w.header.writers.HstsHeaderWriter : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher#3225c3b4
2016-08-25 01:02:57.685 DEBUG 21486 --- [ XNIO-3 task-1] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
2016-08-25 01:02:57.686 INFO 21486 --- [ XNIO-3 task-1] io.undertow.servlet : Initializing Spring FrameworkServlet 'dispatcherServlet'
2016-08-25 01:02:57.686 INFO 21486 --- [ XNIO-3 task-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2016-08-25 01:02:57.697 INFO 21486 --- [ XNIO-3 task-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 11 ms
This example is slightly older (2015) and does not use Spring Security, but it is a JWT solution for securing a Spring Boot application. The author has also included their code on Github for reference, as you said the post you have been using is lacking in code examples.

Resources