Kotlin testing authentication to /actuator api - spring-boot

I have a ActuatorSecurity class which I use for authentication for /actuator actions.
package com.netapp.qronicle.config
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest
import org.springframework.context.annotation.Bean
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.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.crypto.factory.PasswordEncoderFactories
#Configuration
#EnableWebSecurity
class ActuatorSecurity : WebSecurityConfigurerAdapter() {
#Value("\${security.user.actuator-username}")
private val actuatorUsername: String? = null
#Value("\${security.user.actuator-password}")
private val actuatorPassword: String? = null
#Throws(Exception::class)
override fun configure(http: HttpSecurity) {
http.csrf().disable().requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests()
.anyRequest().hasRole("USER")
.and()
.httpBasic()
}
#Throws(Exception::class)
override fun configure(auth: AuthenticationManagerBuilder) {
val passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder()
val encodedPassword = passwordEncoder.encode(actuatorPassword)
auth.inMemoryAuthentication()
.withUser(actuatorUsername).password(encodedPassword).roles("USER")
}
#Bean
#Throws(Exception::class)
override fun authenticationManagerBean(): AuthenticationManager {
// ALTHOUGH THIS SEEMS LIKE USELESS CODE,
// IT'S REQUIRED TO PREVENT SPRING BOOT AUTO-CONFIGURATION
return super.authenticationManagerBean()
}
}
I have everything configured in my application.properties file
# spring boot actuator access control
management.endpoints.web.exposure.include=*
security.user.actuator-username=admin
security.user.actuator-password=admin123
I would like to just to do basic authentication api tests for /actuator/** but have not been able to do so, here is my test class
package com.netapp.qronicle.web
import com.netapp.qronicle.config.ActuatorSecurity
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.junit.jupiter.SpringExtension
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders
import org.springframework.test.web.servlet.result.MockMvcResultMatchers
import javax.inject.Inject
#ExtendWith(SpringExtension::class)
#WebMvcTest(ActuatorSecurity::class)
#ContextConfiguration(classes = [ActuatorSecurity::class])
class ActuatorTest {
#Inject
lateinit var mockMvc: MockMvc
#Test
fun `Basic authentication actuator test`() {
val result = mockMvc.perform(
MockMvcRequestBuilders.get("/actuator"))
.andExpect(MockMvcResultMatchers.status().isOk)
Assertions.assertNotNull(result)
}
}
The error thrown is:
2019-02-26 17:07:26.062 INFO 34766 --- [ main] com.netapp.qronicle.web.ActuatorTest : Starting ActuatorTest on jmasson-mac-0 with PID 34766 (started by jonma in /Users/jonma/Development/java/report-generator)
2019-02-26 17:07:26.099 INFO 34766 --- [ main] com.netapp.qronicle.web.ActuatorTest : No active profile set, falling back to default profiles: default
2019-02-26 17:07:29.324 INFO 34766 --- [ main] com.netapp.qronicle.web.ActuatorTest : Started ActuatorTest in 4.468 seconds (JVM running for 6.427)
MockHttpServletRequest:
HTTP Method = GET
Request URI = /actuator
Parameters = {}
Headers = {}
Body = <no character encoding set>
Session Attrs = {}
Handler:
Type = org.springframework.web.servlet.resource.ResourceHttpRequestHandler
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 404
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []

Related

Call Authenticator Microservice From ApiGateway ServerSecurityContextRepository

Introduction
I have a microservice responsible for authenticating each API call to my server. so when any request comes API gateway is supposed to call the authenticator for the validation with token and after this is a success the actual API call process to the intended destination.
API Gateway is a spring-cloud-starter-gateway project using spring-boot-starter-webflux. And the other microservice can be connected using FeignClient.
Problem
I am trying to call the feignclient method from the ReactiveAuthenticationManager authenticate(). and I need some kind of possibility to intercept it and validate this to either throw error or return a success mono.
But as of now the flatmap is not being called.
Code
import com.atlpay.pgapigateway.JwtAuthenticationToken
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.core.Authentication
import org.springframework.security.core.context.SecurityContext
import org.springframework.security.core.context.SecurityContextImpl
import org.springframework.security.web.server.context.ServerSecurityContextRepository
import org.springframework.stereotype.Component
import org.springframework.web.server.ServerWebExchange
import reactor.core.publisher.Mono
#Component
class SecurityContextRepository : ServerSecurityContextRepository {
#Autowired
private lateinit var authenticationManager: AuthenticationManager
override fun save(swe: ServerWebExchange, sc: SecurityContext): Mono<Void> {
return Mono.empty()
}
override fun load(serverWebExchange: ServerWebExchange): Mono<SecurityContext> {
val path = serverWebExchange.request.path
//send request to authentication manager
val auth: Authentication = JwtAuthenticationToken(
"",
serverWebExchange.request.method!!.name,
path.toString(),
serverWebExchange.request.headers
)
return this.authenticationManager.authenticate(auth)
.map { authentication ->
SecurityContextImpl(authentication)
}
}
}
The above SecurityContextRepository calls the AuthenticationManager mentioned below.
import com.atlpay.pgapigateway.JwtAuthenticationToken
import com.atlpay.pgjavacontracts.feign.TestFeign
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.authentication.ReactiveAuthenticationManager
import org.springframework.security.core.Authentication
import org.springframework.stereotype.Component
import reactor.core.publisher.Mono
#Component
class AuthenticationManager : ReactiveAuthenticationManager {
#Autowired
private lateinit var testFeign: TestFeign
override fun authenticate(authentication: Authentication): Mono<Authentication> {
val authToken = (authentication as JwtAuthenticationToken).token
val toReturnUserNamePasswordAuthenticationToken = JwtAuthenticationToken(
authentication.token,
authentication.httpMethod,
authentication.path,
authentication.httpHeaders
)
return testFeign.getUsers()
.flatMap { response ->
//if error throw error
>>>>>> println("This is just a test >> ${response.status()}")
Mono.just(toReturnUserNamePasswordAuthenticationToken as Authentication)
}
.then(Mono.just(toReturnUserNamePasswordAuthenticationToken as Authentication))
}
}
From the above class I am expecting to intercept the call the validate the response code of the feignclient. at this line -
println("This is just a test >> ${response.status()}")
But this is never called!!
FeignClient is just a mock api for testing -
import feign.Response
import org.springframework.web.bind.annotation.PostMapping
import reactivefeign.spring.config.ReactiveFeignClient
import reactor.core.publisher.Mono
#ReactiveFeignClient(url = "https://630369f20de3cd918b34e39e.mockapi.io", name = "testFeign")
interface TestFeign {
#PostMapping("/users")
fun getUsers(): Mono<Response>
}
Attempts
Tried to make a call using Restclient blocking api. and got the result.
but I want it to be load balanced so changed to a LoadBalanced rest client and used the URL 'http://myMicroServiceName/validate' this gives me a block()/blockfirst()/blocklast() are blocking error.
So this is out of scope for now.
I think I am missing some basic structure in the Reactive part or its an issue with the Apigateway ReactiveAuthenticationManager.
Update
Found an solution with webfilter. will update with an answer soon.
Any suggestion is appreciated.

#BeforeAdvise is not working for same method names in Spring BOOT

I am learning Spring AOP and tried to call the #BeforeAdvise for two Different methods in different classes. But the log added in the first call is getting printed only. Please check the code below and let me know what is not correct here.
MainClass
package com.example.aspects;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.example.aspects.AopClasses.DemoConfig;
#SpringBootApplication
public class AspectsApplication {
public static void main(String[] args) {
SpringApplication.run(AspectsApplication.class, args);
}
}
AspectClass
package com.example.aspects.Acpects;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
#Aspect
#Component
public class MyLoggingDemo {
private static final Logger logger = LogManager.getLogger(MyLoggingDemo.class);
#Before("execution(public String test())")
public void beforeCheck() {
logger.info("Before Check !!!!!!!!!!!! "+System.currentTimeMillis() );
}
}
ConfigClass
package com.example.aspects.AopClasses;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
#Configuration
#EnableAspectJAutoProxy
#ComponentScan("com.example.aspects")
public class DemoConfig {
}
TestClass- Where the first call is made to the function
package com.example.aspects.AopClasses;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/")
public class tesTClass {
private static final Logger logger = LogManager.getLogger(tesTClass.class);
MemberShipDAO dao = new MemberShipDAO();
#RequestMapping(value = "/")
public String test() {
logger.info("Hey I am here");
return "HEy There I am Working !!";
}
#RequestMapping(value ="/test")
public String testing() {
logger.info("MemberShipDAO Call");
return dao.test(); // method with same name called here again
}
}
MemberShipDAO - Declared the test method again here
package com.example.aspects.AopClasses;
import org.springframework.stereotype.Component;
#Component
public class MemberShipDAO {
public String test() {
return "HEy!!";
}
}
Console
2022-01-18 11:37:52.794 INFO 8032 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-01-18 11:37:52.796 INFO 8032 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-01-18 11:37:52.802 INFO 8032 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 5 ms
2022-01-18 11:37:52.811 INFO 8032 --- [nio-8080-exec-1] c.example.aspects.Acpects.MyLoggingDemo : Before Check !!!!!!!!!!!! 1642486072811
2022-01-18 11:37:52.854 INFO 8032 --- [nio-8080-exec-1] c.example.aspects.AopClasses.tesTClass : Hey I am here
2022-01-18 11:37:57.383 INFO 8032 --- [nio-8080-exec-3] c.example.aspects.AopClasses.tesTClass : MemberShipDAO Call
Change this
MemberShipDAO dao = new MemberShipDAO();
to this
#Autowired MemberShipDAO dao;
Spring's magic for the AOP happens only when you use the instance created by Spring. Behind the scene, Spring instantiated your dao and wrapped it with a proxy that makes a call to your aspect.

Why is AOP Logging not working in my project

I'm wasting a lot of time right now with AOP logging setup.
I don't know why AOP isn't working in my project.
I think I've done all the settings I can.
Please let me know if you guys have a solutions.
Thank you.
application.java
#EnableAspectJAutoProxy
#SpringBootApplication
#ComponentScan(basePackages = "com.demo.apiservice")
#MapperScan("com.demo.apiservice.mapper")
public class ApiServiceApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(ApiServiceApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(ApiServiceApplication.class, args);
}
#Bean
public ModelMapper modelMapper() {
return new CustmizedModelMapper();
}
#Bean
public AopLoggingConfig loggingAspect(){
return new AopLoggingConfig();
}
}
build.gradle
configurations {
all {
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
}
}
dependencies {
//implementation 'org.springframework.boot:spring-boot-starter-security:2.5.5'
implementation 'org.springframework.boot:spring-boot-starter-web:2.5.5'
implementation 'org.springframework.boot:spring-boot-starter-log4j2:2.5.5'
implementation 'org.springframework.boot:spring-boot-starter-mail:2.5.5'
implementation 'org.springframework.boot:spring-boot-starter-aop:2.5.5'
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.3'
testImplementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter-test:2.1.3'
implementation 'org.springframework.boot:spring-boot-starter-data-rest:2.5.5'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.projectlombok:lombok:1.18.8'
implementation 'org.modelmapper:modelmapper:2.3.8'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa:2.5.5'
implementation 'org.springframework.boot:spring-boot-starter-jdbc:2.5.5'
implementation 'com.h2database:h2:1.4.200'
implementation 'org.springframework.boot:spring-boot-configuration-processor:2.5.5'
implementation 'org.springframework.security:spring-security-core:5.4.2'
implementation 'com.fasterxml.jackson.core:jackson-core:2.12.3'
implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.12.3'
implementation 'com.fasterxml.jackson.core:jackson-databind:2.12.3'
implementation 'org.apache.httpcomponents:httpclient:4.5.13'
implementation 'com.nimbusds:nimbus-jose-jwt:9.7'
implementation 'io.springfox:springfox-swagger2:3.0.0'
implementation 'io.springfox:springfox-swagger-ui:2.9.2'
implementation 'joda-time:joda-time:2.10.10'
implementation 'io.jsonwebtoken:jjwt-api:0.11.1'
implementation 'javax.inject:javax.inject:1'
implementation 'com.googlecode.json-simple:json-simple:1.1'
implementation 'de.mkammerer:argon2-jvm:2.7'
implementation 'org.bouncycastle:bcprov-jdk15on:1.68'
implementation 'org.apache.maven.plugins:maven-surefire-plugin:2.22.0'
implementation 'javax.validation:validation-api:2.0.1.Final'
implementation 'org.postgresql:postgresql:42.1.4'
implementation 'org.hibernate:hibernate-gradle-plugin:5.6.1.Final'
implementation 'com.jayway.jsonpath:json-path:2.6.0'
compileOnly 'org.projectlombok:lombok:1.18.8'
testCompileOnly 'org.projectlombok:lombok:1.18.8'
runtimeOnly 'org.springframework.boot:spring-boot-devtools:2.5.5'
annotationProcessor 'org.projectlombok:lombok:1.18.8'
testAnnotationProcessor 'org.projectlombok:lombok:1.18.8'
testImplementation 'org.springframework.boot:spring-boot-starter-test:2.5.5'
testImplementation 'org.springframework.security:spring-security-test:5.5.2'
}
AopLoggingComponent.java
package com.demo.apiservice.config;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
#Component
#Aspect
public class AopLoggingConfig {
Logger logger = LoggerFactory.getLogger(AopLoggingConfig.class);
static String name = "";
static String type = "";
/**
* AspectJ is applied only to a specific class/method in package.
*/
#Around("execution(* com.demo.apiservice.customer.*Controller.*(..))")
public Object logPrint(ProceedingJoinPoint joinPoint) throws Throwable {
type = joinPoint.getSignature().getDeclaringTypeName();
if (type.indexOf("Controller") -1) {
name = "Controller \t: ";
}
else if (type.indexOf("Service") -1) {
name = "ServiceImpl \t: ";
}
else if (type.indexOf("DAO") -1) {
name = "DAO \t\t: ";
}
logger.debug(name + type + ".######################### " + joinPoint.getSignature().getName() + "()");
return joinPoint.proceed();
}
}
controller.java
package com.demo.apiservice.customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.demo.apiservice.constant.Constants;
import com.demo.apiservice.customer.service.CustomerService;
import com.demo.apiservice.customer.service.impl.CustomerServiceImpl;
import com.demo.apiservice.request.CustomerRequest;
import com.demo.apiservice.request.LoginRequest;
import com.demo.apiservice.response.GetCustomerResponse;
import com.demo.apiservice.response.SuccessResponse;
import com.demo.apiservice.utils.ResponseHandler;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
import javax.validation.Valid;
#Slf4j
#RestController
#Api(tags = "Customers APIs")
#RequestMapping("/apiservice/v1/customers")
public class CustomerController {
#Autowired
private CustomerService customerService;
#GetMapping
#ApiOperation(value = "List of Customers API")
#ApiResponses(value = {
#ApiResponse(code = 400, message = Constants.BAD_REQUEST),
#ApiResponse(code = 403, message = Constants.ACCESS_DENIED)})
public ResponseEntity<Object retrieveAll() {
log.info("Start of CustomerController::retrieveAll method");
return customerService.retrieveAll();
}
}
application.yml
logging:
level:
org:
springframework.web: DEBUG
hibernat: DEBUG
com:
atoz_develop:
mybatissample:
repository: TRACE
mybatis:
mapper-locations: classpath:/mappers/*.xml
type-aliases-package: com.demo.apiservice.entity
configuration:
map-underscore-to-camel-case: 'true'
debug: 'true'
spring:
datasource:
driver-class-name: org.postgresql.Driver
username: postgres
url: jdbc:postgresql://localhost:5432/postgres
platform: postgres
password: postgres
jpa:
generate-ddl: 'false'
properties:
hibernate:
dialect: org.hibernate.dialect.PostgreSQL10Dialect
format_sql: 'true'
hibernate:
ddl-auto: update
show-sql: 'true'
stack trace log
2021-11-17 16:05:19.992 DEBUG 23300 --- [nio-8080-exec-8] o.s.w.s.DispatcherServlet : GET /apiservice/v1/customers, parameters={} 2021-11-17 16:05:19.992 DEBUG 23300 --- [nio-8080-exec-8] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.demo.apiservice.customer.CustomerController#retrieveAll()
2021-11-17 16:05:19.993 INFO 23300 --- [nio-8080-exec-8] c.l.a.c.CustomerController : Start of CustomerController::retrieveAll method
2021-11-17 16:05:19.993 INFO 23300 --- [nio-8080-exec-8] c.l.a.c.s.i.CustomerServiceImpl : Inside of the CustomerServiceImpl :: retrieveAll method
2021-11-17 16:05:19.996 INFO 23300 --- [nio-8080-exec-8] c.l.a.c.s.i.CustomerServiceImpl : End of the CustomerServiceImpl :: retrieveAll method
2021-11-17 16:05:19.996 DEBUG 23300 --- [nio-8080-exec-8] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Using application/xhtml+xml, given [text/html, application/xhtml+xml, image/avif, image/webp, image/apng, application/xml;q=0.9, application/signed-exchange;v=b3;q=0.9, */*;q=0.8] and supported [application/json, application/*+json, application/json, application/*+json, application/xml;charset=UTF-8, text/xml;charset=UTF-8, application/*+xml;charset=UTF-8, application/xml;charset=UTF-8, text/xml;charset=UTF-8, application/*+xml;charset=UTF-8]
2021-11-17 16:05:19.996 DEBUG 23300 --- [nio-8080-exec-8] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Writing [{data=[Customer(email=test1#test.com, password=null, customerId=null, storeName=eos, firstname=test1 (truncated)...]
2021-11-17 16:05:19.998 DEBUG 23300 --- [nio-8080-exec-8] o.s.w.s.DispatcherServlet : Completed 200 OK
Your aspect is triggered. I added an explicit controller method call in order to check:
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(ApiServiceApplication.class, args);
context.getBean(CustomerController.class).retrieveAll();
}
Then I fixed some typos in your code like the one mentioned in my previous comment.
Probably your problem was that you simply did not see the log output because you forgot the log configuration for your application package com.demo.apiservice:
logging:
level:
org:
springframework.web: DEBUG
hibernate: DEBUG
com:
atoz_develop:
mybatissample:
repository: TRACE
demo.apiservice: DEBUG
BTW, I also corrected your typo hibernat to hibernate, but that is unrelated to the problem at hand.
Then I see this in the log:
[ restartedMain] o.s.b.w.e.t.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
[ restartedMain] c.d.a.ApiServiceApplication : Started ApiServiceApplication in 5.101 seconds (JVM running for 6.117)
[ restartedMain] c.d.a.c.AopLoggingConfig : Controller : com.demo.apiservice.customer.CustomerController.######################### retrieveAll()
[ restartedMain] c.d.a.c.AopLoggingConfig : Controller : com.demo.apiservice.customer.CustomerController.######################### retrieveAll()
[ restartedMain] c.d.a.c.CustomerController : Start of CustomerController::retrieveAll method
Do you see the problem? You get duplicate logging, because the aspect is picked up once by component scan and instantiated one more time as a bean in your application configuration. So you need to remove this part from ApiServiceApplication:
#Bean
public AopLoggingConfig loggingAspect() {
return new AopLoggingConfig();
}
Now the duplicate logging is gone.
Next, maybe you want to simplify your aspect a bit and simply log joinPoint or joinPoint.getSignature(). You also want to make name and type local variables, because the static fields are not thread-safe. Instead, probably you want a static logger in the aspect.
#Component
#Aspect
public class AopLoggingConfig {
private static Logger logger = LoggerFactory.getLogger(AopLoggingConfig.class);
#Around("execution(* com.demo.apiservice.customer.*Controller.*(..))")
public Object logPrint(ProceedingJoinPoint joinPoint) throws Throwable {
String type = joinPoint.getSignature().getDeclaringTypeName();
String name = "";
if (type.contains("Controller")) {
name = "Controller \t: ";
}
else if (type.contains("Service")) {
name = "ServiceImpl \t: ";
}
else if (type.contains("DAO")) {
name = "DAO \t\t: ";
}
logger.debug(name + joinPoint.getSignature());
return joinPoint.proceed();
}
}
The log line becomes:
Controller : ResponseEntity com.demo.apiservice.customer.CustomerController.retrieveAll()
But actually, both the package name and the class name indicate that we are dealing with a controller, DAO or service. So why bother with the if-else stuff in the first place? Why make a simple matter complicated and the aspect slower? Besides, if you only want to log something and not influence the control flow, the method parameters or the return value, a simple #Before advice would do, the expensive #Around is unnecessary.
#Component
#Aspect
public class AopLoggingConfig {
private static Logger logger = LoggerFactory.getLogger(AopLoggingConfig.class);
#Before("execution(* com.demo.apiservice.customer.*Controller.*(..))")
public void logPrint(JoinPoint joinPoint) {
logger.debug(joinPoint.getSignature().toString());
}
}
The log line becomes:
ResponseEntity com.demo.apiservice.customer.CustomerController.retrieveAll()
Isn't that enough?
Or even simpler:
logger.debug(joinPoint.toString());
Log:
execution(ResponseEntity com.demo.apiservice.customer.CustomerController.retrieveAll())
Keep it simple!
The following should work:
package com.demo.apiservice.config;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
#Component
#Aspect
public class AopLoggingConfig {
Logger logger = LoggerFactory.getLogger(AopLoggingConfig.class);
static String name = "";
static String type = "";
#Pointcut("within(#org.springframework.web.bind.annotation.RestController *)")
public void controllerClassMethods() {}
#Around("controllerClassMethods()")
public Object logPrint(ProceedingJoinPoint joinPoint) throws Throwable {
type = joinPoint.getSignature().getDeclaringTypeName();
if (type.indexOf("Controller") -1) {
name = "Controller \t: ";
}
else if (type.indexOf("Service") -1) {
name = "ServiceImpl \t: ";
}
else if (type.indexOf("DAO") -1) {
name = "DAO \t\t: ";
}
logger.debug(name + type + ".######################### " + joinPoint.getSignature().getName() + "()");
return joinPoint.proceed();
}
}
This will match all the methods in all classes annotated with #RestController.

Spring Boot testing: Cannot bind #ConfigurationProperties - Ensure that #ConstructorBinding has not been applied

In a Spring Boot unit test, how can you mock #ConstructorBinding #ConfigurationProperties data class?
Setup
Both
Kotlin 1.4.30 (for unit tests and config classes)
Java 15 (with --enable-preview) (for business logic)
Spring Boot 2.4.2
Junit 5.7.1
Mockito (mockito-inline) 3.7.7
Maven 3.6.3_1
I want to test FtpService (a #Service, which has a RestTemplate) with different configurations.
Properties for the FtpService come from a Kotlin data class - UrlProperties - which is annotated with ConstructorBinding and #ConfigurationProperties.
Note: FtpService's constructor extracts a property from UrlProperties. This means that UrlProperties must be both mocked and stubbed before Spring loads FtpService
Error
When I try and mock UrlProperties so that I can set the properties for different tests, I either receive an error, or am unable to insert the bean
Cannot bind #ConfigurationProperties for bean 'urlProperties'. Ensure that #ConstructorBinding has not been applied to regular bean
Code
`#SpringBootTest` of FtpService | `src/test/kotlin/com/example/FtpServiceTest.kt`
import com.example.service.FtpService
import com.example.service.UrlProperties
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.client.AutoConfigureWebClient
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.context.TestConfiguration
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.context.annotation.Bean
import org.springframework.test.context.ContextConfiguration
#TestConfiguration
#SpringBootTest(classes = [FtpService::class])
#AutoConfigureWebClient(registerRestTemplate = true)
class FtpServiceTest
#Autowired constructor(
private val ftpService: FtpService
) {
// MockBean inserted into Spring Context too late,
// FtpService constructor throws NPE
// #MockBean
// lateinit var urlProperties: UrlProperties
#ContextConfiguration
class MyTestContext {
// error -
// > Cannot bind #ConfigurationProperties for bean 'urlProperties'.
// > Ensure that #ConstructorBinding has not been applied to regular bean
var urlProperties: UrlProperties = mock(UrlProperties::class.java)
#Bean
fun urlProperties() = urlProperties
// error -
// > Cannot bind #ConfigurationProperties for bean 'urlProperties'.
// > Ensure that #ConstructorBinding has not been applied to regular bean
// #Bean
// fun urlProperties(): UrlProperties {
// return UrlProperties(
// UrlProperties.FtpProperties(
// url = "ftp://localhost:21"
// ))
// }
}
#Test
fun `test fetch file root`() {
`when`(MyTestContext().urlProperties.ftp)
.thenReturn(UrlProperties.FtpProperties(
url = "ftp://localhost:21"
))
assertEquals("I'm fetching a file from ftp://localhost:21!",
ftpService.fetchFile())
}
#Test
fun `test fetch file folder`() {
`when`(MyTestContext().urlProperties.ftp)
.thenReturn(UrlProperties.FtpProperties(
url = "ftp://localhost:21/user/folder"
))
assertEquals("I'm fetching a file from ftp://localhost:21/user/folder!",
ftpService.fetchFile())
}
}
Workaround - manual definition every test
The only 'workaround' is to manually define all beans (which means I miss out on Spring Boot magic during testing) and in my view is more confusing.
Workaround - manual redefinition each test | `src/test/kotlin/com/example/FtpServiceTest2.kt`
import com.example.service.FtpService
import com.example.service.UrlProperties
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.mockito.Mockito
import org.mockito.Mockito.`when`
import org.mockito.Mockito.doReturn
import org.mockito.Mockito.mock
import org.springframework.boot.web.client.RestTemplateBuilder
class FtpServiceTest2 {
private val restTemplate =
RestTemplateBuilder()
.build()
private lateinit var ftpService: FtpService
private lateinit var urlProperties: UrlProperties
#BeforeEach
fun beforeEachTest() {
urlProperties = mock(UrlProperties::class.java)
`when`(urlProperties.ftp)
.thenReturn(UrlProperties.FtpProperties(
url = "default"
))
ftpService = FtpService(restTemplate, urlProperties)
}
/** this is the only test that allows me to redefine 'url' */
#Test
fun `test fetch file folder - redefine`() {
urlProperties = mock(UrlProperties::class.java)
`when`(urlProperties.ftp)
.thenReturn(UrlProperties.FtpProperties(
url = "ftp://localhost:21/redefine"
))
// redefine the service
ftpService = FtpService(restTemplate, urlProperties)
assertEquals("I'm fetching a file from ftp://localhost:21/redefine!",
ftpService.fetchFile())
}
#Test
fun `test default`() {
assertEquals("I'm fetching a file from default!",
ftpService.fetchFile())
}
#Test
fun `test fetch file root`() {
`when`(urlProperties.ftp)
.thenReturn(UrlProperties.FtpProperties(
url = "ftp://localhost:21"
))
assertEquals("I'm fetching a file from ftp://localhost:21!",
ftpService.fetchFile())
}
#Test
fun `test fetch file folder`() {
doReturn(
UrlProperties.FtpProperties(
url = "ftp://localhost:21/user/folder"
)).`when`(urlProperties).ftp
assertEquals("I'm fetching a file from ftp://localhost:21/user/folder!",
ftpService.fetchFile())
}
#Test
fun `test fetch file folder - reset`() {
Mockito.reset(urlProperties)
`when`(urlProperties.ftp)
.thenReturn(UrlProperties.FtpProperties(
url = "ftp://localhost:21/mockito/reset/when"
))
assertEquals("I'm fetching a file from ftp://localhost:21/mockito/reset/when!",
ftpService.fetchFile())
}
#Test
fun `test fetch file folder - reset & doReturn`() {
Mockito.reset(urlProperties)
doReturn(
UrlProperties.FtpProperties(
url = "ftp://localhost:21/reset/doReturn"
)).`when`(urlProperties).ftp
assertEquals("I'm fetching a file from ftp://localhost:21/reset/doReturn!",
ftpService.fetchFile())
}
}
Spring App | `src/main/kotlin/com/example/MyApp.kt`
package com.example
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.context.properties.ConfigurationPropertiesScan
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.boot.runApplication
#SpringBootApplication
#EnableConfigurationProperties
#ConfigurationPropertiesScan
class MyApp
fun main(args: Array<String>) {
runApplication<MyApp>(*args)
}
Example #Service | `src/main/kotlin/com/example/service/FtpService.kt`
package com.example.service
import org.springframework.stereotype.Service
import org.springframework.web.client.RestTemplate
#Service
class FtpService(
val restTemplate: RestTemplate,
urlProperties: UrlProperties,
val ftpProperties: UrlProperties.FtpProperties = urlProperties.ftp
) {
fun fetchFile(): String {
println(restTemplate)
return "I'm fetching a file from ${ftpProperties.url}!"
}
}
#ConfigurationProperties with #ConstructorBinding - `src/main/kotlin/com/example/service/UrlProperties.kt`
package com.example.service
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.context.properties.ConstructorBinding
#ConstructorBinding
#ConfigurationProperties("url")
data class UrlProperties(val ftp: FtpProperties) {
data class FtpProperties(
val url: String,
)
}

Kotlin Can't create #Autowired field in Class that are annotated with #Configuration #EnableWebMvc

Autowired field is null when initializing the project:
package com.lynas.config
import org.springframework.stereotype.Component
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
#Component
open class InterceptorConfig : HandlerInterceptorAdapter() {
override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any?): Boolean {
return true
}
}
package com.lynas.config
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.ComponentScan
import org.springframework.context.annotation.Configuration
import org.springframework.web.servlet.config.annotation.EnableWebMvc
import org.springframework.web.servlet.config.annotation.InterceptorRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
#Configuration
#EnableWebMvc
#ComponentScan("com.lynas")
open class WebConfig() : WebMvcConfigurerAdapter() {
// this field show null
#Autowired
lateinit var interceptorConfig: InterceptorConfig
override fun addInterceptors(registry: InterceptorRegistry) {
registry.addInterceptor(interceptorConfig)
}
}
lateinit var interceptorConfig: InterceptorConfig is null when I run the application. How to fix this?
full code https://github.com/lynas/kotlinSpringBug
try #field:Autowired lateinit var interceptorConfig or #set:Autowired which will tell kotlin compiler to put annotations explicitly on field/setter. by default it places them on "property" which is kotlin-only construct and Java may have problems accessing it. refer to kotlin docs here

Resources