13 Eylül 2022 Salı

SpringTest Testcontainers MongoDBContainer

Giriş
MongoDBContainer yaratmak için tercih edilmeyen bazı yollar şöyle
// direct implementation
MongoDBContainer mongoDBContainer =
new MongoDBContainer(DockerImageName.parse("mongo:4.0.10")) //Bunu kullan
// generic implementation
MongoDBContainer mongoDBContainer =
new FixedHostPortGenericContainer("mongo:4.0.10"); //Bunu kullanma
Açıklaması şöyle. Yani esas sebep sabit port numarası kullanılması. Bu da testlerin paralel koşmasına mani.
Both versions should work. The difference is MongoDBContainer will run on a random port while with FixedHostPortGenericContainer you can use a port of your choosing. It simplifies connecting to Mongo a lot, cause you can enforce a good old localhost:27017 this way, so no dynamic configurations would be required.

The problem with this solution is it does not work well if you have multiple tests suits using non-shared container running at once. Processes will often kill MongoDB container in their teardown phase when other suits are already running or will try to start their Mongo and find out the port is already taken.
Örnek
Şöyle yaparız
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@Testcontainers @Import(Configuration.class) public abstract class BaseApiTest { @Container static final MongoDBContainer mongo = new MongoDBContainer("mongo:3.6-xenial"); @DynamicPropertySource static void properties(DynamicPropertyRegistry registry) { registry.add("spring.data.mongodb.uri", mongo::getReplicaSetUrl); } @TestConfiguration public static class Configuration { @Lazy @Bean("testSetupMongoClient") public MongoClient testSetupMongoClient() { return MongoClients.create(mongo.getReplicaSetUrl("test")); } } }
Örnek
Şöyle yaparız. Burada Spock kullanılıyor.
@Testcontainers
@SpringBootTest
class SampleSuite extends Specification {
   @Shared
   static MongoDBContainer mongoDBContainer = new MongoDBContainer("mongo:4.0.18-xenial")

   @DynamicPropertySource
   static void mongoProps(DynamicPropertyRegistry registry) {
      mongoDBContainer.start()
      registry.add("spring.data.mongodb.uri", () ->   mongoDBContainer.replicaSetUrl)
   }
   void cleanup() {
      // cleaning up a bit should be a good idea...
      mongoDBContainer.stop()
   }
}

12 Eylül 2022 Pazartesi

SpringSecurity SecurityFilterChain Sınıfı - Yeni Component Based Approach

Giriş
Açıklaması şöyle
With Spring Security 5 a security configuration class or classes would normally inherit WebSecurityConfigurerAdapter and override the configure method.

In Spring Security 6, it is now a Bean that takes HttpSecurity object as a parameter and returns SecurityFilterChain object.
WebSecurityConfigurerAdapter sınıfından kalıtıp "configure(HttpSecurity http)" metodunu override etmek yerine, kendimiz bir SecurityFilterChain döndürüyoruz. 

Bu sınıfı oluşturturken lambda'lar ağırlıklı olarak kullanılıyor. 

SpringBoot 3 ile Gelen Farklılıklar
1. antMatchers() yerine requestMatchers() metodu kullanılıyor
Açıklaması şöyle
One change requires source modification: with Spring Security 5, we used .antMatchers method of authorizeRequest object. With Spring Security 6, it has been renamed to .requestMatchers. Otherwise, everything is as it was before, except that this method must now have a call to create SecurityFilterChain object from http parameter by calling http.build().
2. Açıklaması şöyle. Yani iki tane yıldız olmak zorunda
After switching to Spring Security 6, the previous configuration does not work any longer. In order to handle requests properly, it has to be as follows :

.requestMatchers(HttpMethod.GET,"/ws/user/**",
addFilterBefore metodu
Örnek
Şöyle yaparız
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { 
  http
    .csrf()
    .disable()

    // Add Paseto token filter
    .addFilterBefore(authTokenFilter, UsernamePasswordAuthenticationFilter.class)
    .authenticationProvider(authenticationProvider())

    // Set unauthorized requests exception handler
    .exceptionHandling()
        .authenticationEntryPoint(new HandlerAuthenticationEntryPoint())
        .accessDeniedHandler(new HandlerAccessDeniedHandler())
    .and()
      .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    .and()

      // Set permissions on endpoints
      .authorizeHttpRequests()
      .requestMatchers("/api/account/authenticate").permitAll()
      .requestMatchers("/api/account/register").permitAll()
      .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
      .requestMatchers(
        "/configuration/ui",
        "/swagger-resources/**",
        "/configuration/security",
        "/webjars/**").permitAll()
        .requestMatchers("/api/**").authenticated();
      
  return http.build();
}
authorizeHttpRequests  metodu
SecurityFilterChain.authorizeHttpRequests metodu yazısına taşıdım

csrf metodu
CsrfConfigurer yazısına taşıdım

cors metodu
Örnek
Şöyle yaparız
@Configuration
@EnableWebSecurity public class WebSecurityConfig { ... @Bean public SecurityFilterChain auth0FilterChain(HttpSecurity http) throws Exception { http.cors() .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .securityMatcher("/ws/**") .authorizeHttpRequests(autorizeRequests -> autorizeRequests .requestMatchers(HttpMethod.GET, "/ws/healthz", "/ws/ready", "/ws/version") .permitAll() .requestMatchers(HttpMethod.GET, "/ws/user/**","/ws/user/avatar/*","/ws/user/search") .hasAnyAuthority("SCOPE_tmt:user") .requestMatchers(HttpMethod.POST, "/ws/friend","/ws/user/trip", "/ws/trip/*") .hasAnyAuthority("SCOPE_tmt:user") ) .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt); http.csrf().disable(); http.headers().frameOptions().disable(); return http.build(); } }
Örnek
Şöyle yaparız
// Spring Boot 3.0.0
@Bean
protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  // ...
  http.authorizeHttpRequests()
    // Public endpoints
    .requestMatchers(HttpMethod.GET, "/swagger-ui.html").permitAll()
    .requestMatchers(HttpMethod.GET, "/swagger-ui/**").permitAll()
    .requestMatchers(HttpMethod.GET, "/v3/api-docs/**").permitAll()
    .requestMatchers(HttpMethod.POST, "/api/auth/login").permitAll()
    .requestMatchers(HttpMethod.POST, "/api/auth/token-refresh").permitAll()
    .anyRequest().authenticated();
    // ...
}
exceptionHandling metodu
accessDeniedHandler için ServerAccessDeniedHandler nesnesi takılır
authenticationEntryPoint hatası için ServerAuthenticationEntryPoint nesnesi takılır
Örnek
Şöyle yaparız
@Configuration
@EnableWebFluxSecurity //webflux related
@EnableReactiveMethodSecurity //webflux related
public class SecurityConfig {

  //whitlisting swagger urls
  private static final String[] AUTH_WHITELIST = {
    // -- swagger ui
    "/swagger-resources/**",
    "/configuration/ui",
    "/configuration/security",
    "/swagger-ui.html",
    "/webjars/**",
    "/v3/api-docs/**"};

  //custom auth classes for validating JWT
  @Autowired
  private AuthenticationManager authenticationManager;
    
  //custom auth classes for validating JWT
  @Autowired
  private SecurityContextRepository securityContextRepository;

  @Bean
  SecurityWebFilterChain springSecurityFilterChain(final ServerHttpSecurity http) {
     http.csrf()
       .disable()
       //Disable Sessions
       .securityContextRepository(NoOpServerSecurityContextRepository.getInstance())
       // handlers fro 401 and 403
       .exceptionHandling(exception -> exception.accessDeniedHandler(new CustomAccessDeniedHandler())
         .authenticationEntryPoint(new CustomAuthenticationEntryPoint()))
       //rest services don't have a login form
       .formLogin()
       .disable()
       //disabled basic authentication
       .httpBasic()
       .disable()
       .authorizeExchange()
       //used when connecting from browsers
       .pathMatchers(HttpMethod.OPTIONS)
       .permitAll()
       //other whitelist URL, like swagger. ensure to disable in production
       .pathMatchers(AUTH_WHITELIST)
       .permitAll()
       //your auth URL
       .pathMatchers("/auth/login")
       .permitAll()
       .and()
       //spring authentication manager
       .authenticationManager(authenticationManager)
       .securityContextRepository(securityContextRepository)
       .authorizeExchange()
       .anyExchange()
       .authenticated()
       .and();
       return http.build();
    }
}

formLogin metodu
SecurityFilterChain.formLogin metodu  metodu yazısına taşıdım

oauth2ResourceServer metodu


9 Eylül 2022 Cuma

SpringMVC LocaleResolver Arayüzü

Giriş
Açıklaması şöyle
Another way to determine which locale is currently being used is to use LocaleResolver. This interface has different implementations that determine the current locale based on the session, cookies, the Accept-Language header, or a fixed value.
FixedLocaleResolver Sınıfı
Açıklaması şöyle
This implementation is used mostly for debugging purposes and you will always have a single fixed language set up in the project application properties file
Örnek
Şöyle yaparız
@Bean
public LocaleResolver localeResolver() {
   FixedLocaleResolver lr = new FixedLocaleResolver();
   lr.setDefaultLocale(Locale.US);
   return lr;
}
AcceptHeaderLocaleResolver Sınıfı
Açıklaması şöyle
For web applications, one of the options is to use the “accept-language” HTTP header on the request. This implementation will take the value from the HTTP status header and apply it.
Örnek
Şöyle yaparız
@Bean
public LocaleResolver localeResolver() {
   AcceptHeaderLocaleResolver lr = new AcceptHeaderLocaleResolver();
   lr.setDefaultLocale(Locale.US);
   return lr;
}
SessionLocaleResolver Sınıfı
Açıklaması şöyle
Another approach for web a1pplications is to use Session to get the local for the user visiting the application. In this implementation, the value will store inside the session and will be available during the session’s lifetime.
Açıklaması şöyle. LocaleChangeInterceptor yazısına bakabilirsiniz
Note: For SessionLocaleResolver and CookieLocaleResolver we need to have an interceptor to get the parameter sent from the user for the preferred language and store it in session or cookie. Thanks to spring this has been done already don and you can use LocaleChangeInterceptor and just pass the name of the property to set the locale.
Örnek
Şöyle yaparız
@Bean
public LocaleResolver localeResolver() {
    SessionLocaleResolver lr = new SessionLocaleResolver();
    lr.setDefaultLocale(Locale.US);
    return lr;
}
CookieLocaleResolver Sınıfı
CookieLocaleResolver yazısına taşıdım


SpringContext Internationalization — i18n Kullanımı

Açıklaması şöyle
Spring Boot looks for the presence of a messages.properties resource bundle at the root of the classpath.
Şeklen şöyle

properties dosyalarının içi şöyle
message.properties

welcome=Hello! this is a test message!
lang.change=Change the language
lang.eng=English
lang.fr=French

message_fr.properties

welcome=Bonjour! Ceci est un message test!
lang.change=Changer la langue
lang.eng=English
lang.fr=French
application.properties Dosyası
Açıklaması şöyle
Of course, there are several attributes like basenamethat you can use to change the resource bundle configuration using spring.messages namespace in application.properties or application.yaml.

spring.messages.basename=messages, i18n.list
spring.messages.fallback-to-system-locale=false
Stringleri Okumak
Eğer locale'i açıktan belirtmek istersek ResourceBundleMessageSource  kullanılır
Eğer locale'i bulmak istersek LocaleResolver kullanılır




1 Eylül 2022 Perşembe

SpringCache application.properties Ayarları

Örnek - none
Cache işlevini kapatmak için şöyle yaparız.
spring.cache.type = none
Redis
SpringCache Redis Kullanımı yazısına taşıdım

30 Ağustos 2022 Salı

SpringIntegration Redis RedisLockRegistry Sınıfı

Giriş
Açıklaması şöyle. Kilidi @RedisLockable ile otomatik bırakmak yerine kodla bırakmak için kullanılabilir
To release the lock early, you can use the LockRegistry interface provided by Spring Integration. You can inject the LockRegistry bean and obtain a lock on the same key used by the @RedisLockable annotation.
constructor - RedisConnectionFactory + registryKey
Örnek
Şöyle yaparız
private static final String LOCK_NAME = "lock";

@Bean(destroyMethod = "destroy")
public RedisLockRegistry redisLockRegistry(
  RedisConnectionFactory redisConnectionFactory) {
    return new RedisLockRegistry(redisConnectionFactory, LOCK_NAME);
}
constructor - RedisConnectionFactory + registryKey + expireAfter
Açıklaması şöyle
When creating a RedisLockRegistry instance, you need to provide three parameters: `connectionFactory`, `registryKey`, and `expireAfter`.

The `connectionFactory` parameter is used to generate the redisTemplate instance field within the RedisLockRegistry. This redisTemplate facilitates interaction with Redis using string values.

The `registryKey` parameter serves as a prefix for key names. These key names are formed by combining the `registryKey` and the key’s specific value, separated by a colon. For example, if `registryKey` is set to “Spring” and you intend to lock a key with the value “Integration”, the actual key used to communicate with Redis would be “Spring:Integration”.

The `expireAfter` parameter, of type long, determines the Time To Live (TTL) for the lock status data inserted into Redis by RedisLock instances.
Örnek
Şöyle yaparız
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.integration.support.locks.ExpirableLockRegistry;

@Configuration
public class RedisDistributedLockConfiguration {
    private static final String LOCK_REGISTRY_REDIS_KEY = "MY_REDIS_KEY";
    private static final Duration RELEASE_TIME_DURATION = Duration.ofSeconds(30);

  @Bean(LOCK_REGISTRY_BEAN)
  public ExpirableLockRegistry lockRegistry(RedisConnectionFactory redisConnectionFactory){
    RedisLockRegistry redisLockRegistry =
      new RedisLockRegistry(redisConnectionFactory, LOCK_REGISTRY_REDIS_KEY,
        RELEASE_TIME_DURATION.toMillis());
      return redisLockRegistry;
  }
}
expireUnusedOlderThan metodu
Açıklaması şöyle
In some situations, you might need to acquire a lock but not release it. For example, you have a @Scheduled task that runs each 15 seconds on each instance and you don’t want it to be run more often than once per 15 seconds.
To do it you can get a lock and exit from a method without releasing. In such cases, I suggest calling lockRegistry.expireUnusedOlderThan(TTL) each time before obtaining a lock (actually it is better to call it for all cases). This method removes old not released locks from the map locks and prevents the situation when one instance has a map with old locks and all threads of this instance (except the one which acquired this lock) cannot acquire it.
obtain metodu
Açıklaması şöyle
Each object LockRegistry has a random id of type UUID and contains a map of locks (lock name / lock object) that are called locks and that are held by the current instance. When we do lockRegistry.obtain(lockKey), lockRegistry first checks if the map contains this lock (in other words, if the current instance has the lock with the same name acquired at this moment), if so then this lock is returned. Otherwise, lockRegistry checks if Redis contains the key with the name “registry key:lock name” and if the value equals the id of the lockRegistry object. If so, it returns this lock, else it tries to create the key “registry key:lock name” in Redis. When you got a lock and call lock.tryLock() basically the similar steps are performed as in lockRegistry.obtain(lockKey), first the map locks with locks is checked, then Redis.
Şöyle yaparız
import org.springframework.integration.support.locks.ExpirableLockRegistry;

@Slf4j
@Component
public class LockService implements ILockService {

  @Qualifier(LOCK_REGISTRY_BEAN)
  @Autowired
  private ExpirableLockRegistry lockRegistry;

  @Override
  public boolean update(UpdateRequest request) {
    Lock lock = lockRegistry.obtain(request.getId());
    boolean success = lock.tryLock();

    if (!success) {
      return false;
    }
        
    // ...
    // update a shared resource  
    // ... 
        
    lock.unlock();
    return true;
  }
}
Örnek
Şöyle yaparız
@Service
public class MyService {

  @Autowired
  private RedisLockRegistry redisLockRegistry;

  @RedisLockable(key = "my-lock-key", leaseTime = 60_000, waitTime = 5_000)
  public void doSomethingWithLock() throws InterruptedException {
    Lock lock = redisLockRegistry.obtain("my-lock-key");
    try {
      // Do something with the lock
    } finally {
       lock.unlock();
    }
  }
}
setRedisLockType metodu
Açıklaması şöyle
... there can be configured 2 types of locks (both Reentrant ones)
- RedisLockType.SPIN_LOCK - the lock is acquired by periodic loop (100ms) checking whether the lock can be acquired. Default.
- RedisLockType.PUB_SUB_LOCK - The lock is acquired by redis pub-sub subscription.

The pub-sub is preferred mode — less network chatter between client Redis server, and more performant — the lock is acquired immediately when subscription is notified about unlocking in the other process. However, the Redis does not support pub-sub in the Master/Replica connections (for example in AWS ElastiCache environment), therefore a busy-spin mode is chosen as a default to make the registry working in any environment.



SpringCloud AWS Secrets Manager - AWS Secrets Manager'dan Bilgileri Alır

Giriş
AWS secret değerlerini actuator ile env altında görebiliriz.
http://localhost:8080/actuator/env
SpringCloud AWS Systems Manager kullanımına çok benziyor

Maven
Şu satırı dahil ederiz
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>io.awspring.cloud</groupId>
      <artifactId>spring-cloud-aws-dependencies</artifactId>
      <version>3.0.0-M2</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
</dependencies>

<dependency>
  <groupId>io.awspring.cloud</groupId>
  <artifactId>spring-cloud-aws-starter-secrets-manager</artifactId>
</dependency>
Gradle
Şu satırı dahil ederiz
dependencies {
  implementation 'org.springframework.boot:spring-boot-starter'
  implementation('io.awspring.cloud:spring-cloud-starter-aws-secrets-manager-config:2.4.2')
}
application.yaml Dosyası
spring.config.import AWS'ten parametreleri çeker ve bunları Spring’in ortam değişkenlerine (environment properties) ekler

Örnek
Maven ile şöyle yaparız
<dependency>
     <groupId>com.amazonaws</groupId>
     <artifactId>aws-java-sdk-secretsmanager</artifactId>
  </dependency>
  <dependency>
     <groupId>com.amazonaws.secretsmanager</groupId>
     <artifactId>aws-secretsmanager-jdbc</artifactId>
     <version>1.0.5</version>
  </dependency>
application.properties ile şöyle yaparız
spring.datasource.url = (name/path of your secrets manager)
spring.datasource.username = (name/path of your secrets manager)
spring.datasource.driver-class-name = com.amazonaws.secretsmanager.sql.AWSSecretsManagerMySQLDriver
Örnek - Other Secret Type

Örnek
yaml dosyası şöyle olsun. 3 tane farklı secret dosyası içinde sev/value çiftleri tanımladık.
spring:
  config:
    import:
      - aws-secretsmanager:dev/my-app/database-creds
      - aws-secretsmanager:dev/my-app/oauth-creds
      - optional:aws-secretsmanager:dev/my-app/some-other-creds
Bu çiftlerin herhangi birine @Value ile erişebiliriz. Şöyle yaparız
@SpringBootApplication
public class SpringBootAwsSecretsApplication implements CommandLineRunner {

  @Value("${dbUser}")
  private String dbUser;

  @Value("${dbPassword}")
  private String dbPassword;
  ...
}
Örnek
Şöyle bir secret yaratalım
aws secretsmanager create-secret 
  --name /secret/db-credential 
  --secret-string '{"dbuser": "user1", "dbpassword": "password"}'
Şöyle yaparız. spring/cloud/config/import ile secret ismi belirtiliyor. Secret içindeki dbuser ve dbpassword değişkenleri kullanılıyor. AWS için kullanılan profile ismi "personal"
# actuator configuration
management:
  endpoints:
    web:
      exposure:
        include:
        - env
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/database
    username: ${dbuser}
    password: ${dbpassword}
  jpa:
    hibernate:
      ddl-auto: create

#  AWS configuration
  cloud:
    aws:
      secretsmanager:
        region: eu-central-1
          
      credentials:
        profile:
          name: personal
  config:
    import:
       - aws-secretsmanager:/secret/db-credential
       - optional:aws-secretsmanager:/secrets/optional-secret
Localstack İle Unit Test
Docker compose ile Localstack'i çalıştırmak için şöyle yaparız
version: "3.8"

services:
  localstack:
    image: localstack/localstack
    ports:
      - "4566:4566"            # LocalStack endpoint
    environment:
      - DOCKER_HOST=unix:///var/run/docker.sock
      - DEFAULT_REGION=eu-central-1
    volumes:
      - ./localstack-script:/docker-entrypoint-initaws.d
      - /var/run/docker.sock:/var/run/docker.sock
localstack-script/script.sh içinde şöyle yaparız. awslocal localstack tarafından sağlanır ve aws komutu için bir wrapper
awslocal secretsmanager create-secret 
  --name /secret/spring-boot-app 
  --secret-string '{"property1": "property1-value", "property2": "property2-value"}'

awslocal secretsmanager create-secret 
  --name /secret/db-credential 
  --secret-string '{"dbuser": "user1", "dbpassword": "password"}'
test için application.properties şöyledir
spring:
  cloud:
     aws:
      secretsmanager:
        region: eu-central-1
        endpoint: http://localhost:4566
      credentials:
        access-key: none
        secret-key: none
Test içinde şöyle yaparız. Burada @DynamicPropertySource kullanılmıyor
@SpringBootTest
@AutoConfigureMockMvc
class ApplicationIT {

  @Autowired
  MockMvc mockMvc;

  @Container
  private static LocalStackContainer localStackContainer = 
    new LocalStackContainer(DockerImageName.parse("localstack/localstack"))
      .withCopyFileToContainer(MountableFile.forClasspathResource("script.sh"),
                    "/docker-entrypoint-initaws.d/")
      .withServices(LocalStackContainer.Service.SECRETSMANAGER);

  @BeforeAll
  static void beforeAll() throws IOException, InterruptedException {
    System.setProperty("spring.cloud.aws.secretsmanager.endpoint",
      localStackContainer.getEndpointOverride(
        LocalStackContainer.Service.SECRETSMANAGER).toString());

    System.setProperty("spring.cloud.aws.secretsmanager.region", 
      localStackContainer.getRegion());
    System.setProperty("spring.cloud.aws.credentials.access-key", "none");
    System.setProperty("spring.cloud.aws.credentials.secret-key", "none");
  }
  ...
 
}