Unauthorized 401 error for permitAll() URLs - spring

I am getting unauthorized error even for permit all URLs.
This is my security config file:
#Configuration
#EnableWebSecurity
public class SecurityConfig {
#Value("${auth0.audience}")
private String audience;
#Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}")
private String issuer;
#Bean
JwtDecoder jwtDecoder() {
NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder) JwtDecoders.fromOidcIssuerLocation(issuer);
OAuth2TokenValidator<Jwt> audienceValidator = new AudienceValidator(audience);
OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer(issuer);
OAuth2TokenValidator<Jwt> withAudience = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator);
jwtDecoder.setJwtValidator(withAudience);
return jwtDecoder;
}
#Bean
public DefaultSecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth-> auth
.requestMatchers("/api/public/**","/login","/register").permitAll().anyRequest().authenticated())
.oauth2ResourceServer()
.jwt();
return http.build();
}
}
This is my validator file:
class AudienceValidator implements OAuth2TokenValidator<Jwt> {
private final String audience;
AudienceValidator(String audience) {
this.audience = audience;
}
public OAuth2TokenValidatorResult validate(Jwt jwt) {
OAuth2Error error = new OAuth2Error("invalid_token", "The required audience is missing", null);
if (jwt.getAudience().contains(audience)) {
return OAuth2TokenValidatorResult.success();
}
return OAuth2TokenValidatorResult.failure(error);
}
}
And these are the Log files
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
[32m :: Spring Boot :: [39m [2m (v3.0.1)[0;39m
[2m2023-02-19T22:23:00.142+05:30[0;39m [32m INFO[0;39m [35m16708[0;39m [2m---[0;39m [2m[ restartedMain][0;39m [36mc.r.apigateway.ApiGatewayApplication [0;39m [2m:[0;39m Starting ApiGatewayApplication using Java 17.0.6 with PID 16708 (C:\PM\api-gateway - Copy\target\classes started by KrishnaGopikaUrlagan in C:\PM\api-gateway - Copy)
[2m2023-02-19T22:23:00.142+05:30[0;39m [32m INFO[0;39m [35m16708[0;39m [2m---[0;39m [2m[ restartedMain][0;39m [36mc.r.apigateway.ApiGatewayApplication [0;39m [2m:[0;39m No active profile set, falling back to 1 default profile: "default"
[2m2023-02-19T22:23:00.669+05:30[0;39m [32m INFO[0;39m [35m16708[0;39m [2m---[0;39m [2m[ restartedMain][0;39m [36mo.s.cloud.context.scope.GenericScope [0;39m [2m:[0;39m BeanFactory id=54aac986-e0d5-38c2-b07e-9736a12b46b1
[2m2023-02-19T22:23:01.470+05:30[0;39m [32m INFO[0;39m [35m16708[0;39m [2m---[0;39m [2m[ restartedMain][0;39m [36mtrationDelegate$BeanPostProcessorChecker[0;39m [2m:[0;39m Bean 'org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerBeanPostProcessorAutoConfiguration' of type [org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerBeanPostProcessorAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
[2m2023-02-19T22:23:01.471+05:30[0;39m [32m INFO[0;39m [35m16708[0;39m [2m---[0;39m [2m[ restartedMain][0;39m [36mtrationDelegate$BeanPostProcessorChecker[0;39m [2m:[0;39m Bean 'org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerBeanPostProcessorAutoConfiguration$ReactorDeferringLoadBalancerFilterConfig' of type [org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerBeanPostProcessorAutoConfiguration$ReactorDeferringLoadBalancerFilterConfig] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
[2m2023-02-19T22:23:01.471+05:30[0;39m [32m INFO[0;39m [35m16708[0;39m [2m---[0;39m [2m[ restartedMain][0;39m [36mtrationDelegate$BeanPostProcessorChecker[0;39m [2m:[0;39m Bean 'reactorDeferringLoadBalancerExchangeFilterFunction' of type [org.springframework.cloud.client.loadbalancer.reactive.DeferringLoadBalancerExchangeFilterFunction] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
[2m2023-02-19T22:23:01.538+05:30[0;39m [32mDEBUG[0;39m [35m16708[0;39m [2m---[0;39m [2m[ restartedMain][0;39m [36mswordEncoderAuthenticationManagerBuilder[0;39m [2m:[0;39m No authenticationProviders and no parentAuthenticationManager defined. Returning null.
[2m2023-02-19T22:23:02.904+05:30[0;39m [32m INFO[0;39m [35m16708[0;39m [2m---[0;39m [2m[ restartedMain][0;39m [36mo.s.s.web.DefaultSecurityFilterChain [0;39m [2m:[0;39m Will secure any request with [org.springframework.security.web.session.DisableEncodeUrlFilter#5c9f1e10, org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#9658b45, org.springframework.security.web.context.SecurityContextHolderFilter#291e1f26, org.springframework.security.web.header.HeaderWriterFilter#1d58f1b7, org.springframework.security.web.authentication.logout.LogoutFilter#2de04a13, org.springframework.security.oauth2.server.resource.web.authentication.BearerTokenAuthenticationFilter#738072a1, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#240b8e76, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#2ed115b5, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#2c68f8e0, org.springframework.security.web.access.ExceptionTranslationFilter#4f68b71d, org.springframework.security.web.access.intercept.AuthorizationFilter#733ad243]
[2m2023-02-19T22:23:26.660+05:30[0;39m [32mDEBUG[0;39m [35m16708[0;39m [2m---[0;39m [2m[ parallel-1][0;39m [36mo.s.s.w.s.u.m.OrServerWebExchangeMatcher[0;39m [2m:[0;39m Trying to match using PathMatcherServerWebExchangeMatcher{pattern='/logout', method=POST}
[2m2023-02-19T22:23:26.660+05:30[0;39m [32mDEBUG[0;39m [35m16708[0;39m [2m---[0;39m [2m[ parallel-1][0;39m [36mathPatternParserServerWebExchangeMatcher[0;39m [2m:[0;39m Request 'GET /api/public/allergy' doesn't match 'POST /logout'
[2m2023-02-19T22:23:26.660+05:30[0;39m [32mDEBUG[0;39m [35m16708[0;39m [2m---[0;39m [2m[ parallel-1][0;39m [36mo.s.s.w.s.u.m.OrServerWebExchangeMatcher[0;39m [2m:[0;39m No matches found
[2m2023-02-19T22:23:26.661+05:30[0;39m [32mDEBUG[0;39m [35m16708[0;39m [2m---[0;39m [2m[ parallel-1][0;39m [36ma.DelegatingReactiveAuthorizationManager[0;39m [2m:[0;39m Checking authorization on '/api/public/allergy' using org.springframework.security.authorization.AuthenticatedReactiveAuthorizationManager#69b0d355
[2m2023-02-19T22:23:26.661+05:30[0;39m [32mDEBUG[0;39m [35m16708[0;39m [2m---[0;39m [2m[ parallel-1][0;39m [36mebSessionServerSecurityContextRepository[0;39m [2m:[0;39m No SecurityContext found in WebSession: 'org.springframework.web.server.session.InMemoryWebSessionStore$InMemoryWebSession#2da15e91'
[2m2023-02-19T22:23:26.661+05:30[0;39m [32mDEBUG[0;39m [35m16708[0;39m [2m---[0;39m [2m[ parallel-1][0;39m [36mo.s.s.w.s.a.AuthorizationWebFilter [0;39m [2m:[0;39m Authorization failed: Access Denied
This the pom.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.demo</groupId>
<artifactId>api-gateway-auth0</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>api-gateway</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
<spring-cloud.version>2022.0.1</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>netflix-candidates</id>
<name>Netflix Candidates</name>
<url>https://artifactory-oss.prod.netflix.net/artifactory/maven-oss-candidates</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</project>
I tried to permit all public URLs and authenticate all the private URLs. but even though I permitted the public URLs I am getting a 401 error. I took out the webflux dependency, added the #Configuration annotation and made some more changes based on the suggestions I got from the comments. But still, the same problem.
Please help me solve this error.

Spring Security 6 is deny-by-default, so if you don't explicitly reference a URL, or provide a wildcard, it'll deny access. Try this:
.requestMatchers("api/public/**").permitAll())

The reference you are providing is a specific one. You need to provide a general one for spring security to either accept or reject apis that belong to that path. Try the below:
instead of "api/public" or api/private use "api/public/*" and "api/private/*"

If you are using Spring Security 6.x, you may be missing an #Configuration on your SecurityConfig. I added a comment explaining the discrepancy between your logs and your config, so if the missing annotation is your problem, you may face further configuration issues afterwards.
See the 5.8 migration guide (which should be used when upgrading to 6.0) for more info.
Edit:
Upon discussing further in comments and reviewing your updated question, it appears that you are building an application using spring-boot-starter-gateway (Spring Cloud Gateway), which builds on Spring WebFlux and requires a corresponding security configuration using #EnableWebFluxSecurity. Explicit WebFlux Security Configuration in the reference contains an example configuration to get you started with Spring WebFlux.

Related

Spring Boot:Error starting ApplicationContext. APPLICATION FAILED TO START

I am getting below error in console when i am trying to run spring boot app.I am new to spring boot and learning everything newly but i am stuck.I did go through various stackoverflow answers but none resolved the issue
Error log
[2m2023-01-20T22:56:15.534+05:30[0;39m [32m INFO[0;39m [35m16620[0;39m [2m---[0;39m [2m[ main][0;39m [36ms.EnfamilrestapiSpringrestapiApplication[0;39m [2m:[0;39m No active profile set, falling back to 1 default profile: "default"
[2m2023-01-20T22:56:17.467+05:30[0;39m [32m INFO[0;39m [35m16620[0;39m [2m---[0;39m [2m[ main][0;39m [36mo.s.b.w.embedded.tomcat.TomcatWebServer [0;39m [2m:[0;39m Tomcat initialized with port(s): 8080 (http)
[2m2023-01-20T22:56:17.504+05:30[0;39m [32m INFO[0;39m [35m16620[0;39m [2m---[0;39m [2m[ main][0;39m [36mo.apache.catalina.core.StandardService [0;39m [2m:[0;39m Starting service [Tomcat]
[2m2023-01-20T22:56:17.505+05:30[0;39m [32m INFO[0;39m [35m16620[0;39m [2m---[0;39m [2m[ main][0;39m [36mo.apache.catalina.core.StandardEngine [0;39m [2m:[0;39m Starting Servlet engine: [Apache Tomcat/10.1.4]
[2m2023-01-20T22:56:17.744+05:30[0;39m [32m INFO[0;39m [35m16620[0;39m [2m---[0;39m [2m[ main][0;39m [36mo.a.c.c.C.[Tomcat].[localhost].[/] [0;39m [2m:[0;39m Initializing Spring embedded WebApplicationContext
[2m2023-01-20T22:56:17.746+05:30[0;39m [32m INFO[0;39m [35m16620[0;39m [2m---[0;39m [2m[ main][0;39m [36mw.s.c.ServletWebServerApplicationContext[0;39m [2m:[0;39m Root WebApplicationContext: initialization completed in 2106 ms
[2m2023-01-20T22:56:17.878+05:30[0;39m [33m WARN[0;39m [35m16620[0;39m [2m---[0;39m [2m[ main][0;39m [36mConfigServletWebServerApplicationContext[0;39m [2m:[0;39m Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'enfamilController': Unsatisfied dependency expressed through field 'repo': No qualifying bean of type 'com.nischitha.springweb.repository.EnfamilRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
[2m2023-01-20T22:56:17.884+05:30[0;39m [32m INFO[0;39m [35m16620[0;39m [2m---[0;39m [2m[ main][0;39m [36mo.apache.catalina.core.StandardService [0;39m [2m:[0;39m Stopping service [Tomcat]
[2m2023-01-20T22:56:18.150+05:30[0;39m [32m INFO[0;39m [35m16620[0;39m [2m---[0;39m [2m[ main][0;39m [36m.s.b.a.l.ConditionEvaluationReportLogger[0;39m [2m:[0;39m
Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
[2m2023-01-20T22:56:18.203+05:30[0;39m [31mERROR[0;39m [35m16620[0;39m [2m---[0;39m [2m[ main][0;39m [36mo.s.b.d.LoggingFailureAnalysisReporter [0;39m [2m:[0;39m
***************************
APPLICATION FAILED TO START
***************************
Description:
Field repo in com.nischitha.springweb.controller.EnfamilController required a bean of type 'com.nischitha.springweb.repository.EnfamilRepository' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.nischitha.springweb.repository.EnfamilRepository' in your configuration.
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.nischitha.springweb</groupId>
<artifactId>enfamilrestapi_springrestapi</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>enfamilrestapi_springrestapi</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Enfamil(entity)
package com.nischitha.springweb.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
#Entity
public class Enfamil {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
public Enfamil() {
}
#Override
public String toString() {
return "Enfamil [id=" + id + ", name=" + name + ", price=" + price + ", description=" + description + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
private String name;
private String price;
private String description;
}
**EnfamilRepository **
package com.nischitha.springweb.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.RepositoryDefinition;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import com.nischitha.springweb.entity.Enfamil;
#Repository
public interface EnfamilRepository extends JpaRepository<Enfamil, Integer> {
}
Enfamil Controller
package com.nischitha.springweb.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.nischitha.springweb.entity.Enfamil;
import com.nischitha.springweb.repository.EnfamilRepository;
#RestController
public class EnfamilController {
#Autowired
EnfamilRepository repo;
#RequestMapping(value = "/enfamil/", method = RequestMethod.GET)
public List<Enfamil> findProducts() {
return repo.findAll();
}
#RequestMapping(value = "/enfamil/{id}", method = RequestMethod.GET)
public Enfamil getProduct(#PathVariable("id") int id) {
return repo.findById(id).get();
}
#RequestMapping(value = "/enfamil/", method = RequestMethod.POST)
public Enfamil createProduct(#RequestBody Enfamil enfamil) {
return repo.save(enfamil);
}
#RequestMapping(value = "/enfamil/", method = RequestMethod.PUT)
public Enfamil updateProduct(Enfamil enfamil) {
return repo.save(enfamil);
}
#RequestMapping(value = "/enfamil/{id}", method = RequestMethod.DELETE)
public void deleteProduct(#PathVariable("id") int id) {
repo.deleteById(id);
}
}
**
EnfamilrestapiSpringrestapiApplication.java**
package com.nischitha.springweb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication(exclude = {DataSourceAutoConfiguration.class })
public class EnfamilrestapiSpringrestapiApplication {
public static void main(String[] args) {
SpringApplication.run(EnfamilrestapiSpringrestapiApplication.class, args);
}
}
application.properties
spring.datasource.url=jdbc:mysql//localhost:3306/mydb
spring.datasource.username=
spring.datsource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
Folder Structure screenshot
Below are the things i tried-
putting all files in one folder
2.marking repository bean as #NoRepositoryBean
3.#EnableJpaRepositories(basePackages = "com.nischitha.springweb.repository") - added this to EnfamilrestapiSpringrestapiApplication.java file

SpringBoot + Spring Security OAuth2 2.0 Resource Server JWT at Startup Expectation is not calling Authorisation Server

Summary :
Testing out Spring Security OAuth2 Resource Server JWT with SpringBoot 2.7.7 which uses Spring Security 5.7.6 to query Authorisation Server at startup.
According to :
https://docs.spring.io/spring-security/reference/5.7/servlet/oauth2/resource-server/jwt.html#_startup_expectations
Startup Expectations
When this property and these dependencies are used, Resource Server
will automatically configure itself to validate JWT-encoded Bearer
Tokens.
It achieves this through a deterministic startup process:
Query the Provider Configuration or Authorization Server Metadata endpoint for the jwks_url property
Query the jwks_url endpoint for supported algorithms
Configure the validation strategy to query jwks_url for valid public keys of the algorithms found
Configure the validation strategy to validate each JWTs iss claim against idp.example.com.
A consequence of this process is that the authorization server must be
up and receiving requests in order for Resource Server to successfully
start up.
If the authorization server is down when Resource Server queries it
(given appropriate timeouts), then startup will fail.
I have the property defined in application.properties AND the dependencies in pom.xml as above.
However, my very small example to try this out does not work ( e.g. The Resource Server does not appear to be querying the Authorisation Server at all at startup, and therefore the Resource Server starts-up successfully.
I was expecting my very small app to fail at startup as per documentation, but it did not ! Went as far as shutting down the Authorisation Server, and the SpringBoot Resources Server app still starts up.
Here's what I did :
1) pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.example</groupId>
<artifactId>oauth2-resource-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>oauth2-resource-server</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
<spring-cloud.version>2021.0.5</spring-cloud.version>
<bootstrap.version>5.2.3</bootstrap.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-jose</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency-->
<!--dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency-->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>${bootstrap.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
2. application.properties
server.port=8081
spring.thymeleaf.cache=false
spring.security.oauth2.resourceserver.jwt.issuer-uri=http://openam.localtest.me:8080/openam/oauth2/realms/subrealm/
spring.security.oauth2.resourceserver.jwt.jwk-set-uri=http://openam.localtest.me:8080/openam/oauth2/realms/subrealm/connect/jwk_uri
3. Configuration class:
package org.example.oauth2resourceserver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.web.SecurityFilterChain;
#Configuration
#EnableWebSecurity
public class OAuth2ResourceServerSecurityConfiguration {
#Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}")
String jwkSetUri;
#Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((authorize) -> authorize
.antMatchers(HttpMethod.GET, "/**").hasAuthority("SCOPE_message:read")
.antMatchers(HttpMethod.POST, "/**").hasAuthority("SCOPE_message:write")
.anyRequest().authenticated()
)
.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
return http.build();
}
#Bean
JwtDecoder jwtDecoder() {
return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri).build();
}
}
4. Controller
package org.example.oauth2resourceserver;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class ExampleMVCController {
#GetMapping("/")
public String main(Model model) {
return "welcome";
}
#GetMapping("/welcome")
public String welcome(Model model) {
return "welcome";
}
}
5. Application
package org.example.oauth2resourceserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Oauth2ResourceServerApplication {
public static void main(String[] args) {
SpringApplication.run(Oauth2ResourceServerApplication.class, args);
}
}
With the Authorisation Server down, output on the console when I run the Resource Server is:
2022-12-28 03:32:38.148 INFO 1377958 --- [ main] o.e.o.Oauth2ResourceServerApplication : Starting Oauth2ResourceServerApplication using Java 11.0.15 on xxxxx-Inspiron-15-7510 with PID 1377958 (/home/xxxxx/projects/oauth2-resource-server/target/classes started by jsalvo in /home/xxxxx/projects/oauth2-resource-server)
2022-12-28 03:32:38.150 INFO 1377958 --- [ main] o.e.o.Oauth2ResourceServerApplication : No active profile set, falling back to 1 default profile: "default"
2022-12-28 03:32:38.561 INFO 1377958 --- [ main] o.s.cloud.context.scope.GenericScope : BeanFactory id=12f14043-de4d-3b01-a8aa-ef038a41274e
2022-12-28 03:32:38.733 INFO 1377958 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8081 (http)
2022-12-28 03:32:38.739 INFO 1377958 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-12-28 03:32:38.739 INFO 1377958 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.70]
2022-12-28 03:32:38.819 INFO 1377958 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-12-28 03:32:38.820 INFO 1377958 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 634 ms
2022-12-28 03:32:38.931 INFO 1377958 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Will secure any request with [org.springframework.security.web.session.DisableEncodeUrlFilter#748ac6f3, org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#68f6e55d, org.springframework.security.web.context.SecurityContextPersistenceFilter#2bfaba70, org.springframework.security.web.header.HeaderWriterFilter#5584d9c6, org.springframework.security.web.csrf.CsrfFilter#3bf54172, org.springframework.security.web.authentication.logout.LogoutFilter#58af5076, org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationFilter#650c405c, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#9301672, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#2577a95d, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#6fff46bf, org.springframework.security.web.session.SessionManagementFilter#17e9bc9e, org.springframework.security.web.access.ExceptionTranslationFilter#4da39ca9, org.springframework.security.web.access.intercept.AuthorizationFilter#2954f6ab]
2022-12-28 03:32:39.140 INFO 1377958 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8081 (http) with context path ''
2022-12-28 03:32:39.152 INFO 1377958 --- [ main] o.e.o.Oauth2ResourceServerApplication : Started Oauth2ResourceServerApplication in 1.27 seconds (JVM running for 1.512)
What am I missing ?
What code in Spring Security OAuth2 Resource Server does the call to the Authorisation Server at startup ?
UPDATE 2022-12-28
As suggested by the comments, I have completely removed my OAuth2ResourceServerSecurityConfiguration above. Still no luck.
On looking at the source code for OAuth2ResourceServerJwtConfiguration.JwtDecoderConfiguration :
It appears that you must only specify one of the following properties, but not both:
spring.security.oauth2.resourceserver.jwt.issuer-uri
spring.security.oauth2.resourceserver.jwt.jwk-set-uri
The method at :
JwtDecoderConfiguration.jwtDecoderByIssuerUri() method has an #IssuerUriCondition annotation that dictates a condition where you must only have the spring.security.oauth2.resourceserver.jwt.issuer-uri property defined.
So I commented out the other property ( commented out spring.security.oauth2.resourceserver.jwt.jwk-set-uri from application.properties), but when I debug into that method via IntelliJ, it steps at line 139 below but it does not step / stop at line 141 within the lambda, which is where the code that actually calls the authorisation server, even if I try to Step-In ( F7 ) from line 139:
In short, I am still at a loss. Anyone have any ideas ?

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'some.other.property' in value "${some.other.property}"

I am new to Spring technology and this issue has been bugging me for hours. My spring cloud config client isn't able to read properties from the config server because I am getting an IllegalArgumentException. The config server displays all the properties, but I think there is an issue with the name attribute in the propertySources list and my wild guess is that it is the reason why I am getting this issue. I am attaching the source code, error and the output here. Please help me out!!
Error:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.4.1)
2021-01-03 22:52:41.286 INFO 6124 --- [ restartedMain] c.e.c.ConfigClientAppApplication : Starting ConfigClientAppApplication using Java 14.0.2 on RahulNair with PID 6124 (C:\Users\nairr\Documents\DB Learnings\Spring Apps\Spring Cloud\config-client-app\target\classes started by nairr in C:\Users\nairr\Documents\DB Learnings\Spring Apps\Spring Cloud\Spring_Cloud_And_Microservices)
2021-01-03 22:52:41.286 INFO 6124 --- [ restartedMain] c.e.c.ConfigClientAppApplication : No active profile set, falling back to default profiles: default
2021-01-03 22:52:41.467 INFO 6124 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2021-01-03 22:52:41.467 INFO 6124 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2021-01-03 22:52:43.907 INFO 6124 --- [ restartedMain] o.s.cloud.context.scope.GenericScope : BeanFactory id=ccf80bff-8490-3f1d-990f-4b6383bd7788
2021-01-03 22:52:44.391 INFO 6124 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 6451 (http)
2021-01-03 22:52:44.407 INFO 6124 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-01-03 22:52:44.407 INFO 6124 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.41]
2021-01-03 22:52:44.548 INFO 6124 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-01-03 22:52:44.548 INFO 6124 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 3081 ms
2021-01-03 22:52:45.038 INFO 6124 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2021-01-03 22:52:45.471 INFO 6124 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2021-01-03 22:52:45.647 INFO 6124 --- [ restartedMain] o.s.b.a.e.web.EndpointLinksResolver : Exposing 15 endpoint(s) beneath base path '/actuator'
2021-01-03 22:52:45.723 INFO 6124 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 6451 (http) with context path ''
2021-01-03 22:52:45.833 WARN 6124 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.configClientController': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'some.other.property' in value "${some.other.property}"
2021-01-03 22:52:45.836 INFO 6124 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
2021-01-03 22:52:45.853 INFO 6124 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2021-01-03 22:52:45.877 INFO 6124 --- [ restartedMain] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-01-03 22:52:45.908 ERROR 6124 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.configClientController': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'some.other.property' in value "${some.other.property}"
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:405) ~[spring-beans-5.3.2.jar:5.3.2]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1415) ~[spring-beans-5.3.2.jar:5.3.2]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:608) ~[spring-beans-5.3.2.jar:5.3.2]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:531) ~[spring-beans-5.3.2.jar:5.3.2]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$1(AbstractBeanFactory.java:374) ~[spring-beans-5.3.2.jar:5.3.2]
at org.springframework.cloud.context.scope.GenericScope$BeanLifecycleWrapper.getBean(GenericScope.java:381) ~[spring-cloud-context-3.0.0.jar:3.0.0]
at org.springframework.cloud.context.scope.GenericScope.get(GenericScope.java:184) ~[spring-cloud-context-3.0.0.jar:3.0.0]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:371) ~[spring-beans-5.3.2.jar:5.3.2]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.2.jar:5.3.2]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1159) ~[spring-context-5.3.2.jar:5.3.2]
at org.springframework.cloud.context.scope.refresh.RefreshScope.eagerlyInitialize(RefreshScope.java:124) ~[spring-cloud-context-3.0.0.jar:3.0.0]
at org.springframework.cloud.context.scope.refresh.RefreshScope.start(RefreshScope.java:116) ~[spring-cloud-context-3.0.0.jar:3.0.0]
at org.springframework.cloud.context.scope.refresh.RefreshScope.onApplicationEvent(RefreshScope.java:111) ~[spring-cloud-context-3.0.0.jar:3.0.0]
at org.springframework.cloud.context.scope.refresh.RefreshScope.onApplicationEvent(RefreshScope.java:66) ~[spring-cloud-context-3.0.0.jar:3.0.0]
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172) ~[spring-context-5.3.2.jar:5.3.2]
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165) ~[spring-context-5.3.2.jar:5.3.2]
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139) ~[spring-context-5.3.2.jar:5.3.2]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:426) ~[spring-context-5.3.2.jar:5.3.2]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:383) ~[spring-context-5.3.2.jar:5.3.2]
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:943) ~[spring-context-5.3.2.jar:5.3.2]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:591) ~[spring-context-5.3.2.jar:5.3.2]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:144) ~[spring-boot-2.4.1.jar:2.4.1]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:767) ~[spring-boot-2.4.1.jar:2.4.1]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) ~[spring-boot-2.4.1.jar:2.4.1]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:426) ~[spring-boot-2.4.1.jar:2.4.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:326) ~[spring-boot-2.4.1.jar:2.4.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1309) ~[spring-boot-2.4.1.jar:2.4.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1298) ~[spring-boot-2.4.1.jar:2.4.1]
at com.example.configclientapp.ConfigClientAppApplication.main(ConfigClientAppApplication.java:12) ~[classes/: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:564) ~[na:na]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.4.1.jar:2.4.1]
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'some.other.property' in value "${some.other.property}"
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:178) ~[spring-core-5.3.2.jar:5.3.2]
at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:124) ~[spring-core-5.3.2.jar:5.3.2]
at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:239) ~[spring-core-5.3.2.jar:5.3.2]
at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:210) ~[spring-core-5.3.2.jar:5.3.2]
at org.springframework.context.support.PropertySourcesPlaceholderConfigurer.lambda$processProperties$0(PropertySourcesPlaceholderConfigurer.java:175) ~[spring-context-5.3.2.jar:5.3.2]
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:931) ~[spring-beans-5.3.2.jar:5.3.2]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1308) ~[spring-beans-5.3.2.jar:5.3.2]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1287) ~[spring-beans-5.3.2.jar:5.3.2]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640) ~[spring-beans-5.3.2.jar:5.3.2]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119) ~[spring-beans-5.3.2.jar:5.3.2]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.3.2.jar:5.3.2]
... 33 common frames omitted
Process finished with exit code 0
I am getting the following output when I hit the ./{config-client-name}/{client-profile} endpoint of the spring cloud config server. The part where I think there is a problem is highlighted in yellow.
Spring Cloud Config Server Output Image
Following is my config-server code
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>config-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>config-server</name>
<description>Demo project for Spring cloud</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>2020.0.0</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/*.properties</include>
</includes>
</resource>
</resources>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
</project>
application.properties
spring.application.name=config-server
server.port=8888
spring.cloud.config.server.git.uri=https://github.com/rahul976451/config-server-props.git
JAVA code
package com.example.configserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.config.server.EnableConfigServer;
#SpringBootApplication
#EnableConfigServer
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
Following is my config-client code
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>config-client-app</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>config-client-app</name>
<description>Demo project for Spring cloud</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>2020.0.0</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/*.properties</include>
</includes>
</resource>
</resources>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
</project>
application.properties file
server.port=6451
management.endpoints.web.exposure.include=*
bootstrap.properties file
spring.application.name=config-client-app
spring.cloud.config.uri=http://localhost:8888
eureka.client.server-url.defaultZone=http://localhost:8761/eureka/
JAVA CODE
main.java
package com.example.configclientapp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
#SpringBootApplication
#EnableDiscoveryClient
public class ConfigClientAppApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigClientAppApplication.class, args);
}
}
ConfigClientAppConfiguration.java
package com.example.configclientapp;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
#Component
#ConfigurationProperties(prefix ="some") //Going to represent our property that is named some.property
public class ConfigClientAppConfiguration {
private String property;
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
}
ConfigClientController.java
package com.example.configclientapp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RefreshScope
public class ConfigClientController {
#Autowired
private ConfigClientAppConfiguration properties;
#Value("${some.other.property}") //from the configuration server's application.properties file
private String someOtherProperty;
#RequestMapping("/")
public String printConfig(){
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(properties.getProperty());
stringBuilder.append(" || ");
stringBuilder.append(someOtherProperty);
return stringBuilder.toString();
}
}
Sorry if there is any silly mistake from my end, and please do point it out if there. Thank you!
I finally found the fix myself. Seems that the client bootstrapping doesn't occur automatically in new Spring Cloud release, instead we need to add following dependency and explicitly mention the bootstrapping in bootstrap.xml in the config-client.
Add the dependency
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
And then I just added the following line in bootstrap.xml of my config-client and it worked magically.
spring.cloud.bootstrap.enabled=true
I got this from this link:
Spring Cloud Config: client doesn't attempt to connect to the config server:
Thank you so much guys for your help and contribution! Thanks #Bragolgirith for the fix. Hope this helps people and save their time.
“${some.other.property}” is trying searching for that property in the application.properties file and trying to inject its value in the someOtherProperty variable as expected in this portion of the code:
#Value("${some.other.property}") //from the configuration server's application.properties file
private String someOtherProperty;
Looking at your application.properties file, it is clear that no such entry named some.other.property is defined. There lies the problem, Spring is trying to inject a value not present in such file.
add "some.other.property=foo" in application.properties file and also add the following in the pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Today is 21st January, 2022 (spring boot version 2.6.3) and config client configuration is done through three settings:
Only add spring-cloud-starter-config dependency in your pom.xml
Set the url for config server in application.properties: spring.config.import=configserver:http://localhost:8888
Set the name of the client in order for it to fetch configuration assigned only to it: spring.application.name=movie-catalog-service
spring-cloud-starter-bootstrap dependency and bootstrap.properties are not required.
NOTE: spring-cloud.version=2021.0.0

Spring Boot JAX-RS/CXF dependency injection works in JAR but not WAR

I'm wrapping an existing vanilla JAX-RS application JAR with a Spring Boot application using cxf.jaxrs.classes-scan and cxf.jaxrs.classes-scan-packages. When I run as a JAR or with maven spring-boot:run, dependency injection works fine. When I run as a WAR (on WebSphere Liberty 17.0.0.2), the #Inject-able fields are null during REST requests.
Here's the SpringBootApplication:
#SpringBootApplication(scanBasePackages = { "com.test" })
public class CustomerServiceApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(CustomerServiceApplication.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(CustomerServiceApplication.class);
}
}
Here's src/main/resources/application.properties:
cxf.path=/
cxf.jaxrs.classes-scan=true
cxf.jaxrs.classes-scan-packages=com.test,com.fasterxml.jackson.jaxrs.json
Here's the Maven pom.xml (the vanilla JAX-RS application JAR is customerservice-java which is in the local repository):
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>customerservice-springboot</groupId>
<artifactId>customerservice-springboot</artifactId>
<packaging>war</packaging>
<version>2.0.0-SNAPSHOT</version>
<name>Customer Service :: Spring Boot</name>
<!-- We need to use cxf-spring-boot-starter-jaxrs 3.2.0 because of https://issues.apache.org/jira/browse/CXF-7237
At the time of writing this code, the latest available version in Maven central
is 3.1.7 so we need to use the Apache snapshot repository. -->
<repositories>
<repository>
<id>apache.snapshots</id>
<name>Apache Development Snapshot Repository</name>
<url>https://repository.apache.org/content/repositories/snapshots/</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-spring-boot-starter-jaxrs</artifactId>
<version>3.2.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.json</groupId>
<artifactId>javax.json-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<dependency>
<groupId>customerservice-java</groupId>
<artifactId>customerservice-java</artifactId>
<version>2.0.0-SNAPSHOT</version>
<classifier>jar</classifier>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.0.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Here's the web service in the JAR project:
package com.test;
import javax.inject.Inject;
import javax.ws.rs.CookieParam;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
#Path("/")
public class CustomerServiceRest {
#Inject
CustomerService customerService;
#GET
#Path("/byid/{custid}")
#Produces("text/plain")
public Response getCustomer(#PathParam("custid") String customerid, #CookieParam("token") String jwtToken) {
return Response.ok(customerService.getCustomerId(customerid)).build();
}
}
Here's the bean:
package com.test;
import javax.inject.Named;
#Named
public class CustomerService {
public String getCustomerById(String username) {
// ... implementation ..
return customerDoc.toJson();
}
}
Here's the WAR logging output:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.4.RELEASE)
INFO c.a.s.CustomerServiceApplication - Starting CustomerServiceApplication on 23fb5f5646c3 with PID 20 (/opt/ibm/wlp/usr/servers/defaultServer/apps/expanded/customerservice-springboot-2.0.0-SNAPSHOT.war/WEB-INF/classes started by root in /opt/ibm/wlp/output/defaultServer)
INFO c.a.s.CustomerServiceApplication - No active profile set, falling back to default profiles: default
INFO o.s.b.c.e.AnnotationConfigEmbeddedWebApplicationContext - Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#67e7ebcd: startup date [Wed Jul 19 19:36:12 UTC 2017]; root of context hierarchy
INFO o.s.b.f.x.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [META-INF/cxf/cxf.xml]
INFO o.s.b.f.a.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
INFO c.i.w.w.webapp - SRVE0292I: Servlet Message - [customerservice-springboot-2.0.0-SNAPSHOT]:.Initializing Spring embedded WebApplicationContext
INFO o.s.w.c.ContextLoader - Root WebApplicationContext: initialization completed in 3654 ms
INFO o.s.b.w.s.ServletRegistrationBean - Mapping servlet: 'dispatcherServlet' to [/]
INFO o.s.b.w.s.ServletRegistrationBean - Mapping servlet: 'CXFServlet' to [/*]
INFO o.s.b.w.s.FilterRegistrationBean - Mapping filter: 'errorPageFilter' to: [/*]
INFO o.s.b.w.s.FilterRegistrationBean - Mapping filter: 'characterEncodingFilter' to: [/*]
INFO o.s.b.w.s.FilterRegistrationBean - Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
INFO o.s.b.w.s.FilterRegistrationBean - Mapping filter: 'httpPutFormContentFilter' to: [/*]
INFO o.s.b.w.s.FilterRegistrationBean - Mapping filter: 'requestContextFilter' to: [/*]
INFO o.s.w.s.m.m.a.RequestMappingHandlerAdapter - Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#67e7ebcd: startup date [Wed Jul 19 19:36:12 UTC 2017]; root of context hierarchy
INFO o.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)
INFO o.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)
INFO o.s.w.s.h.SimpleUrlHandlerMapping - Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
INFO o.s.w.s.h.SimpleUrlHandlerMapping - Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
INFO o.s.w.s.h.SimpleUrlHandlerMapping - Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
INFO o.a.c.e.ServerImpl - Setting the server's publish address to be /
INFO o.s.j.e.a.AnnotationMBeanExporter - Registering beans for JMX exposure on startup
INFO c.a.s.CustomerServiceApplication - Started CustomerServiceApplication in 14.955 seconds (JVM running for 271.749)
INFO o.a.c.e.S.e.o.i.l.E.i.w.j.2.0.c.0.17.cl170220170523-1818(id=171)] - Setting the server's publish address to be /
If I enable logging.level.org.springframework.beans.factory.support=TRACE in application.properties, I see the dependency injection working during application startup:
DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'customerService'
DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating instance of bean 'customerService'
DEBUG o.s.b.f.s.DefaultListableBeanFactory - Eagerly caching bean 'customerService' to allow for resolving potential circular references
DEBUG o.s.b.f.s.DefaultListableBeanFactory - Finished creating instance of bean 'customerService' [...]
DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating instance of bean 'com.test.CustomerServiceRest'
DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'customerService'
DEBUG o.s.b.f.s.DefaultListableBeanFactory - Finished creating instance of bean 'com.test.CustomerServiceRest'
However, when I make REST requests, I can see that a new instance of CustomerServiceRest is created on each request (System.out.println in the constructor) and the #Inject-able dependencies are null (resuting in a NullPointerException). So I thought maybe adding #Singleton to CustomerServiceRest would work, but a new object is still created on each request.
Does anyone know how to either use a single web service bean or to ensure that Spring injects all the dependencies? The vanilla JAX-RS application JAR can't itself take on any Spring dependencies.
This kind of issue occurred in one of the spring project
However we have used the #Qualifier("name") on the Class declaration and the same qualifier has been used while auto wiring with the #Inject
I was able to solve this by not using Liberty's CXF (e.g. using servlet & jsp features instead of the webProfile feature [which brings in Liberty's jaxrs feature]), and adding exclude = { DispatcherServletAutoConfiguration.class } to the #SpringBootApplication annotation. This is only needed for my type of use case (e.g. microservices) where the DispatcherServlet is mounted as the default servlet on / and the CXFServlet is mounted with cxf.path=/ (thus creating a /* URL mapping). For other cases where Spring MVC is mixed with CXF but the CXF services are at a non-root URL mapping, the exclude is not necessary. I'm still investigating how to get this to work with Liberty's CXF and I'll update this answer if I find out.
I deployed your code on Tomcat 8.5.x with JDK 1.8 and CustomerService was injected successfully.
Do you have any chance to test your war under Tomcat. At least to understand if it is an issue about the code or app server. Sometimes embedded libraries inside WebSphere/Weblogic are overriding jars coming from your war packages and similar problems occur.

GWT spring-boot application: servlet initialization

I have a GWT application (gwt 2.8) on wich I want to add Spring-Boot dependency (1.5.3.RELEASE). I want a standalone executable war application
Here is my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee">
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.mycompany.fonems.webapp.server.FonemsWebappApplication</param-value>
</init-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Servlets -->
<servlet>
<servlet-name>messageServlet</servlet-name>
<servlet-class>com.mycompany.fonems.webapp.server.FONEMSWebMessageServiceImpl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>messageServlet</servlet-name>
<url-pattern>/fonemswebapp/FONEMSWebMessageService.rpc</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>securityServlet</servlet-name>
<servlet-class>com.mycompany.fonems.webapp.server.FONEMSWebSecurityServiceImpl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>securityServlet</servlet-name>
<url-pattern>/fonemswebapp/FONEMSWebSecurityService.rpc</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>loginServlet</servlet-name>
<servlet-class>com.mycompany.fonems.webapp.server.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<filter>
<filter-name>gwtCacheControlFilter</filter-name>
<filter-class>com.mycompany.fonems.webapp.server.GWTCacheControlFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>gwtCacheControlFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Default page to serve -->
<welcome-file-list>
<welcome-file>Fonemswebapp.html</welcome-file>
</welcome-file-list>
</web-app>
where FonemsWebappApplication is my spring-boot entry point class.
package com.mycompany.fonems.webapp.server;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.inject.Inject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
#Slf4j
#Configuration
#ComponentScan(basePackages = { "com.mycompany.fonems" })
#EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class,
ValidationAutoConfiguration.class })
public class FonemsWebappApplication {
#Inject
private Environment env;
public static void main(String[] args) throws UnknownHostException {
log.info("-------------------------------\tApplication is starting ...");
SpringApplicationBuilder app = new SpringApplicationBuilder(FonemsWebappApplication.class);
Environment env = app.run(args).getEnvironment();
String portNumber = env.getProperty("server.port");
log.info("\n----------------------------------------------------------\n\t"
+ "Application '{}' is running! Access URLs:\n\t" + "Local: \t\thttp://127.0.0.1:{}\n\t"
+ "External: \thttp://{}:{}\n----------------------------------------------------------",
env.getProperty("spring.application.name"), portNumber, InetAddress.getLocalHost().getHostAddress(), portNumber);
log.info("-------------------------------\tApplication is running");
}
}
I launch my application. It seems to start with no error. Nevertheless, in my web broser I have this error:
Problem accessing /fonemswebapp/FONEMSWebMessageService.rpc
The path is not found
Here the logs:
[ main] o.s.w.s.resource.ResourceUrlProvider : Looking for resource handler mappings
[ main] o.s.w.s.resource.ResourceUrlProvider : Found resource handler mapping: URL pattern="/**/favicon.ico", locations=[ServletContext resource [/
], class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/], class path resource []], resolvers=[org.springframework.we
b.servlet.resource.PathResourceResolver#7de5871d]
[ main] o.s.w.s.resource.ResourceUrlProvider : Found resource handler mapping: URL pattern="/webjars/**", locations=[class path resource [META-INF/
resources/webjars/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver#49d42faf]
[ main] o.s.w.s.resource.ResourceUrlProvider : Found resource handler mapping: URL pattern="/**", locations=[ServletContext resource [/], class pat
h resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResol
ver#4948daec]
[ main] o.s.web.servlet.DispatcherServlet : Initializing servlet 'dispatcherServlet'
[ main] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
[ main] o.s.web.servlet.DispatcherServlet : Using MultipartResolver [org.springframework.web.multipart.support.StandardServletMultipartResolver#
709d86a2]
[ main] o.s.web.servlet.DispatcherServlet : Unable to locate LocaleResolver with name 'localeResolver': using default [org.springframework.web.s
ervlet.i18n.AcceptHeaderLocaleResolver#2e1add6f]
[ main] o.s.web.servlet.DispatcherServlet : Unable to locate ThemeResolver with name 'themeResolver': using default [org.springframework.web.ser
vlet.theme.FixedThemeResolver#46702c26]
[ main] o.s.web.servlet.DispatcherServlet : Unable to locate RequestToViewNameTranslator with name 'viewNameTranslator': using default [org.spri
ngframework.web.servlet.view.DefaultRequestToViewNameTranslator#2e3cd732]
[ main] o.s.web.servlet.DispatcherServlet : Unable to locate FlashMapManager with name 'flashMapManager': using default [org.springframework.web
.servlet.support.SessionFlashMapManager#7f6b57f2]
[ main] o.s.web.servlet.DispatcherServlet : Published WebApplicationContext of servlet 'dispatcherServlet' as ServletContext attribute with name
[org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcherServlet]
[ main] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 31 ms
[ main] o.s.web.servlet.DispatcherServlet : Servlet 'dispatcherServlet' configured successfully
[ main] .s.b.c.e.j.JettyEmbeddedServletContainer : Jetty started on port(s) 8088 (http/1.1)
[ main] o.s.w.c.s.StandardServletEnvironment : Adding [server.ports] PropertySource with highest search precedence
[ main] c.n.f.w.server.FonemsWebappApplication : Started FonemsWebappApplication in 7.634 seconds (JVM running for 8.248)
[ main] c.n.f.w.server.FonemsWebappApplication :
----------------------------------------------------------
Application 'fonems-webapp-refonte' is running! Access URLs:
Local: http://127.0.0.1:8088
External: http://10.20.146.96:8088
----------------------------------------------------------
[ main] c.n.f.w.server.FonemsWebappApplication : ------------------------------- Application is running
<< Then I launch this URL: http://127.0.0.1:8088/Fonemswebapp.html in my web broser>>
o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/fonemswebapp/fonemsweba
pp.nocache.js]
s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /fonemswebapp/fonemswebapp.nocache.js
s.w.s.m.m.a.RequestMappingHandlerMapping : Did not find handler method for [/fonemswebapp/fonemswebapp.nocache.js]
o.s.w.s.handler.SimpleUrlHandlerMapping : Matching patterns for request [/fonemswebapp/fonemswebapp.nocache.js] are [/**]
o.s.w.s.handler.SimpleUrlHandlerMapping : URI Template variables for request [/fonemswebapp/fonemswebapp.nocache.js] are {}
o.s.w.s.handler.SimpleUrlHandlerMapping : Mapping [/fonemswebapp/fonemswebapp.nocache.js] to HandlerExecutionChain with handler [ResourceHttpR
equestHandler [locations=[ServletContext resource [/], class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/]], resol
vers=[org.springframework.web.servlet.resource.PathResourceResolver#4948daec]]] and 1 interceptor
o.s.web.servlet.DispatcherServlet : Last-Modified value for [/fonemswebapp/fonemswebapp.nocache.js] is: -1
o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/error]
s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /error
s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public org.springframework.http.ResponseEntity<java.util.Map<java.lang.Str
ing, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)]
o.s.web.servlet.DispatcherServlet : Last-Modified value for [/error] is: -1
o.s.w.s.m.m.a.HttpEntityMethodProcessor : Written [{timestamp=Fri Jun 16 11:02:10 CEST 2017, status=404, error=Not Found, message=Not Found, p
ath=/fonemswebapp/fonemswebapp.nocache.js}] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter#6b09ce57]
o.s.web.servlet.DispatcherServlet : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapt
er completed request handling
o.s.web.servlet.DispatcherServlet : Successfully completed request
o.s.web.servlet.DispatcherServlet : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapt
er completed request handling
o.s.web.servlet.DispatcherServlet : Successfully completed request
o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/fonemswebapp/fonemsweba
pp.nocache.js]
s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /fonemswebapp/fonemswebapp.nocache.js
s.w.s.m.m.a.RequestMappingHandlerMapping : Did not find handler method for [/fonemswebapp/fonemswebapp.nocache.js]
o.s.w.s.handler.SimpleUrlHandlerMapping : Matching patterns for request [/fonemswebapp/fonemswebapp.nocache.js] are [/**]
o.s.w.s.handler.SimpleUrlHandlerMapping : URI Template variables for request [/fonemswebapp/fonemswebapp.nocache.js] are {}
o.s.w.s.handler.SimpleUrlHandlerMapping : Mapping [/fonemswebapp/fonemswebapp.nocache.js] to HandlerExecutionChain with handler [ResourceHttpR
equestHandler [locations=[ServletContext resource [/], class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/]], resol
vers=[org.springframework.web.servlet.resource.PathResourceResolver#4948daec]]] and 1 interceptor
o.s.web.servlet.DispatcherServlet : Last-Modified value for [/fonemswebapp/fonemswebapp.nocache.js] is: -1
o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/error]
s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /error
s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public org.springframework.http.ResponseEntity<java.util.Map<java.lang.Str
ing, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)]
o.s.web.servlet.DispatcherServlet : Last-Modified value for [/error] is: -1
o.s.w.s.m.m.a.HttpEntityMethodProcessor : Written [{timestamp=Fri Jun 16 11:02:10 CEST 2017, status=404, error=Not Found, message=Not Found, p
ath=/fonemswebapp/fonemswebapp.nocache.js}] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter#6b09ce57]
o.s.web.servlet.DispatcherServlet : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapt
er completed request handling
o.s.web.servlet.DispatcherServlet : Successfully completed request
o.s.web.servlet.DispatcherServlet : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapt
er completed request handling
o.s.web.servlet.DispatcherServlet : Successfully completed request
When I launch the url in firefox, my form is displayed. When I click on search button, I have this error in the broser:
HTTP ERROR 404 Problem accessing /fonemswebapp/FONEMSWebMessageService.rpc. Reason: Not Found
Here is my pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.mycompany.fonems</groupId>
<artifactId>fonems-parent</artifactId>
<version>0.0.140-SNAPSHOT</version>
<relativePath>../fonems-parent/pom.xml</relativePath>
</parent>
<artifactId>fonems-webapp-refonte</artifactId>
<packaging>war</packaging>
<name>FONEMS WebApp</name>
<properties>
<!-- Setting maven.compiler.source to something different to 1.8
needs that you configure the sourceLevel in gwt-maven-plugin since
GWT compiler 2.8 requires 1.8 (see gwt-maven-plugin block below) -->
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<!-- Don't let your Mac use a crazy non-standard encoding -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencyManagement>
<dependencies>
<!-- ensure all GWT deps use the same version (unless overridden) -->
<dependency>
<groupId>com.google.gwt</groupId>
<artifactId>gwt</artifactId>
<version>${gwt.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.mycompany.fonems</groupId>
<artifactId>fonems-fwk-server-common</artifactId>
<version>${project.version}</version>
<exclusions>
<exclusion>
<artifactId>xercesImpl</artifactId>
<groupId>xerces</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.mycompany.fonems</groupId>
<artifactId>fonems-refonte-dao</artifactId>
<version>${project.version}</version>
<exclusions>
<exclusion>
<artifactId>javax.el-api</artifactId>
<groupId>javax.el</groupId>
</exclusion>
<exclusion>
<artifactId>xercesImpl</artifactId>
<groupId>xerces</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.gwt</groupId>
<artifactId>gwt-servlet</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.gwt</groupId>
<artifactId>gwt-user</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.gwt</groupId>
<artifactId>gwt-dev</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.smartgwt</groupId>
<artifactId>smartgwt</artifactId>
<version>${smartgwt.version}</version>
</dependency>
<dependency>
<groupId>com.smartgwt</groupId>
<artifactId>smartgwt-skins</artifactId>
<version>${smartgwt.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mycompany.drh</groupId>
<artifactId>newncauth</artifactId>
<version>${mycompany.drh.version}</version>
</dependency>
<dependency>
<groupId>mycompany.drh</groupId>
<artifactId>mycompany.droits-habilitations.rmi</artifactId>
<version>${mycompany.drh.rmi.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<!-- Output classes directly into the webapp, so that IDEs and "mvn process-classes" update them in DevMode -->
<!-- <outputDirectory>${project.build.directory}/src/main/webapp/WEB-INF/classes</outputDirectory> -->
<plugins>
<!-- GWT Maven Plugin-->
<plugin>
<groupId>net.ltgt.gwt.maven</groupId>
<artifactId>gwt-maven-plugin</artifactId>
<version>${gwt.maven.plugin.version}</version>
<executions>
<execution>
<goals>
<goal>import-sources</goal>
<goal>compile</goal>
<goal>import-test-sources</goal>
<goal>test</goal>
</goals>
</execution>
</executions>
<configuration>
<moduleName>com.mycompany.fonems.webapp.Fonemswebapp</moduleName>
<moduleShortName>Fonemswebapp</moduleShortName>
<failOnError>true</failOnError>
<!-- GWT compiler 2.8 requires 1.8, hence define sourceLevel here if you use
a different source language for java compilation -->
<sourceLevel>1.8</sourceLevel>
<!-- Compiler configuration -->
<compilerArgs>
<!-- Ask GWT to create the Story of Your Compile (SOYC) (gwt:compile) -->
<arg>-compileReport</arg>
<arg>-XcompilerMetrics</arg>
</compilerArgs>
<!-- DevMode configuration -->
<warDir>${project.build.directory}/${project.build.finalName}</warDir>
<classpathScope>compile+runtime</classpathScope>
<!-- URL(s) that should be opened by DevMode (gwt:devmode). -->
<startupUrls>
<startupUrl>Fonemswebapp.html</startupUrl>
</startupUrls>
<webappDirectory>${outputFolder}</webappDirectory>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<warSourceDirectory>target/www/</warSourceDirectory>
<packagingExcludes>WEB-INF/lib/tomcat-*.jar</packagingExcludes>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<executable>false</executable>
<!-- Enable the line below to have remote debugging of your application on port 5005 <jvmArguments>-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005</jvmArguments> -->
</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptors>
<descriptor>assembly.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Why, in the logs, we see ServletDispatcher occurences? In my application should I define a ServletDispatcher? If it is the case, how to define my 5 web.xml servlets and filter to be taken into account?
What is curious, is that application runs and responds normally when I launch it from the GWT Development Mode (eclipse plugin).
Thank you

Resources