Wednesday 1 March 2023

Event driven architecture using Spring Boot framework

What is the Event or Message Driven approach in software development?

Event-driven architecture is an approach to software development that enables loosely coupled systems to communicate with each other by exchanging events. In this approach, software components are designed to react to events triggered by other components or external systems, rather than being tightly integrated through direct calls or synchronous communication.

An event can be defined as any change in the state of a system or a significant occurrence that has a meaningful impact on the system. Examples of events include user interactions, system failures, updates to data, or changes in the external environment.

Event-driven architecture can be implemented using various messaging technologies such as message queues, publish-subscribe systems, or event streams. These technologies provide a way for components to communicate with each other asynchronously, without requiring direct connections between them.

Benefits of event-driven architecture include:

  1. Scalability: Event-driven systems can easily scale horizontally to handle high volumes of traffic and demand.

  2. Loose coupling: Components in an event-driven system are loosely coupled, which makes them more modular and easier to maintain and update.

  3. Resilience: The asynchronous and decoupled nature of event-driven architecture makes systems more resilient to failures and errors.

  4. Flexibility: Event-driven systems are flexible and can easily adapt to changes in requirements and business needs.

Event-driven architecture is widely used in modern software development, particularly in the development of microservices, IoT systems, and real-time applications.

Real Life Examples-

There are many real-life examples of software products that use event-driven architecture to achieve their goals. Here are a few examples:

  1. Uber: Uber uses an event-driven architecture to handle millions of ride requests every day. When a user requests a ride, an event is generated that triggers a series of actions in the system, including finding the closest available driver, calculating the estimated time of arrival, and providing real-time updates to the user.

  2. LinkedIn: LinkedIn uses an event-driven architecture to handle its large-scale networking platform. When a user updates their profile, sends a message, or interacts with other users, an event is generated that triggers a series of actions, including updating the user's profile, notifying relevant users, and analyzing the user's behavior to provide personalized recommendations.

  3. Amazon Web Services (AWS): AWS uses an event-driven architecture to provide its cloud computing services. When a user requests a service, an event is generated that triggers a series of actions, including provisioning the necessary resources, deploying the code, and managing the service's lifecycle.

Options for event-driven frameworks to work with Spring Boot

There are several options for event-driven frameworks that can be used in conjunction with Spring Boot. Some of the popular options are:

  • Spring Cloud Stream: This framework provides a simple and powerful way to build messaging microservices that can exchange data between them. It is built on top of Spring Boot and provides a set of abstractions for working with message brokers.
Doc Link: https://docs.spring.io/spring-cloud-stream/docs/current/reference/html/
  • Apache Kafka: This is a popular distributed streaming platform that can be used to build real-time data pipelines and streaming applications. It provides a high-throughput, low-latency, and fault-tolerant messaging system that can be integrated with Spring Boot using the Spring Kafka project.
Doc link: https://kafka.apache.org/24/documentation.html
  • Apache Pulsar: This is another distributed messaging and streaming platform that provides similar features to Apache Kafka, but with additional features like multi-tenancy and geo-replication. It can be integrated with Spring Boot using the Spring Pulsar project.
          Doc link: https://pulsar.apache.org/docs/next/
  • Axon Framework: This is a CQRS and event sourcing framework that provides a way to build scalable and resilient applications based on the principles of DDD (Domain-Driven Design). It can be integrated with Spring Boot using the Spring Axon project.
          Doc link: https://docs.axoniq.io/reference-guide/
  • Vert.x: This is a reactive toolkit that provides a way to build high-performance, low-latency applications that can handle a large number of concurrent connections. It provides a set of abstractions for working with event-driven architectures and can be integrated with Spring Boot using the Spring Vert.x project.
          Doc link: https://vertx.io/docs/

How Implementation work with Spring boot?

We are using apache kafka to demonstrate how we can integrate/use Apache Kafa with springboot.

To setup Kafka with Spring Boot, you can follow these steps:

Step 1:

Add the required dependencies to your project's build file (e.g. pom.xml for Maven or build.gradle for Gradle).

For Maven, add the following dependencies:

<dependency> <groupId>org.springframework.kafka</groupId> <artifactId>spring-kafka</artifactId> <version>${spring-kafka.version}</version> </dependency> <dependency> <groupId>org.apache.kafka</groupId> <artifactId>kafka-clients</artifactId> <version>${kafka-clients.version}</version> </dependency>

 
For Gradle, add the following dependencies:
implementation 'org.springframework.kafka:spring-kafka:${spring-kafka.version}' implementation 'org.apache.kafka:kafka-clients:${kafka-clients.version}'

Note that you need to specify the versions of the dependencies that you want to use.

Step 2:

Configure the Kafka properties in your Spring Boot application's properties file (e.g. application.properties or application.yml).

For example, to configure Kafka to use a local broker with default settings, you can add the following properties:

spring.kafka.bootstrap-servers=localhost:9092


Step 3:

Create a Kafka producer or consumer by using the Spring Kafka template or listener. For example, to create a Kafka producer that sends messages to a topic called "my-topic", you can create a KafkaTemplate bean and use it to send messages: 
import org.springframework.kafka.core.KafkaTemplate; import org.springframework.stereotype.Component; @Component public class MyProducer { private final KafkaTemplate<String, String> kafkaTemplate; public MyProducer(KafkaTemplate<String, String> kafkaTemplate) { this.kafkaTemplate = kafkaTemplate; } public void sendMessage(String message) { kafkaTemplate.send("my-topic", message); } }    
To create a Kafka consumer that listens to messages from the same topic, you can create a KafkaListener bean and annotate a method with @KafkaListener:

import org.springframework.kafka.annotation.KafkaListener;

import org.springframework.stereotype.Component;


@Component

public class MyConsumer {


    @KafkaListener(topics = "my-topic")

    public void receiveMessage(String message) {

        System.out.println("Received message: " + message);

    }

}

With these steps, you can setup Kafka with Spring Boot and start building your event-driven application. 

 

Tuesday 28 February 2023

Create and use self-signed SSL Certificate with Apache

Create and use self-signed SSL Certificate with Apache

PDF
A self-signed SSL Certificate can be used for testing purposes or on websites where the visitors are people who know you and trust you. For situations where you ask for credit card or other payment information I strongly advice you to use a signed certificate (Make sure openssl is installed on your system, on a typically installation of CentOs it is installed by default) The first step is to generate the private key:
openssl genrsa -des3 -out server.key 1024
You will be asked for a password twice. Make it a stong password and don't forget this it. Once the private key has been generated you have to generate Certificate Signing Request
openssl req -new -key server.key -out server.csr
This will ask you serveral questions:
Country Name (2 letter code) [GB]:
State or Province Name (full name) [Berkshire]:
Locality Name (eg, city) [Newbury]:
Organization Name (eg, company) [My Company Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []: FQDN of the server
Email Address []: myaddress at mydomain.com
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
Make sure that the Common Name matches the Fully Qualified DomainName of your SSL website.
As we signed the key with a password we should remove it, otherwise Apache cann't start up withou prompting for this password. We can remove the password:
cp server.key server.key.org
openssl rsa -in server.key.org -out server.key
Generate the cerficate which will be valid for 365 days:
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
Last step is to configure Apache to use the self-signed certificate. Make sure the mod_ssl is enabled in your config. Open /etc/httpd/conf/httpd.conf find and uncomment by removing the # in the line:
# LoadModule ssl_module modules/mod_ssl.so
Copy the certificate and the private key to the Apache conf directory:
cp server.crt /etc/httpd/conf/ssl/server.crt
cp server.key /etc/httpd/conf/ssl/server.key
Now edit the directive in your config matching the server you created this certificate for and add:
SSLEngine on
SSLCertificateFile /usr/local/apache/conf/ssl.crt/server.crt
SSLCertificateKeyFile /usr/local/apache/conf/ssl.key/server.key
SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown
CustomLog logs/ssl_request_log "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
and restart Apache:
/etc/init.d/apache restart

Spring Security Concept and end to end implementation example

 What is Spring Security?


Spring Security is a widely used and highly customizable security framework for Java-based applications. It provides a range of features and tools to enable developers to implement security features such as authentication, authorization, and attack prevention in their applications.

The Importance of Security in Applications

In today's world, security is a significant concern for software applications. Applications that lack proper security measures are vulnerable to various types of attacks, including data breaches, identity theft, and other malicious activities. Thus, it is essential for developers to implement robust security measures in their applications to prevent such attacks and safeguard sensitive data.

Spring Security Overview

Spring Security is an open-source security framework that provides a wide range of features to ensure the security of Java-based applications. It is built on the Spring Framework and is designed to be highly customizable and extensible. Spring Security offers a range of features, including authentication and authorization, secure session management, password management, and various attack prevention mechanisms.

Key Concepts of Spring Security

Spring Security provides several key concepts that are essential for understanding the framework's functionality. These concepts include:

  1. Authentication: Authentication is the process of verifying the identity of a user. Spring Security provides several authentication mechanisms, including form-based authentication, basic authentication, and OAuth2 authentication.
  2. Authorization: Authorization is the process of determining whether a user has access to a particular resource or functionality within an application. Spring Security provides several authorization mechanisms, including role-based access control, permission-based access control, and expression-based access control.

  3. Security Filters: Spring Security uses a chain of filters to process incoming requests and perform security-related actions such as authentication and authorization. These filters can be customized to suit specific application requirements.

  4. Security Context: The Security Context is a thread-local object that stores information about the currently authenticated user and their associated roles and permissions. The Security Context is used throughout the application to enforce security policies and restrictions.

  5. Access Control List (ACL): ACL is a mechanism for defining fine-grained access control rules for individual resources within an application. Spring Security provides support for ACLs through its integration with the Spring Framework's Security module.

  6. Password Encoding: Spring Security provides a range of password encoding mechanisms, including BCrypt, PBKDF2, and SHA-256. These mechanisms help to ensure that passwords are securely stored and transmitted.

  7. Cross-Site Request Forgery (CSRF) Protection: CSRF protection is a mechanism for preventing CSRF attacks, where an attacker tricks a user into performing an action on their behalf. Spring Security provides CSRF protection by generating and validating unique tokens for each user session.

Benefits of Spring Security

Some of the benefits of using Spring Security for security implementation in applications include:

  1. Customizability: Spring Security is highly customizable and extensible. It provides various configuration options that enable developers to implement security features that meet their application's specific requirements.

  2. Scalability: Spring Security is scalable and can be easily integrated into large enterprise applications.

  3. Integration with other Spring modules: Spring Security integrates seamlessly with other Spring modules, such as Spring Framework, Spring Data, and Spring MVC.

  4. Community Support: Spring Security has a large and active community that provides support, guidance, and updates.

Conclusion In conclusion, Spring Security is an essential tool for developers looking to implement security measures in their Java-based applications. Its comprehensive set of features, customizability, and community support make it an ideal choice for securing applications against various types of attacks. By implementing Spring Security, developers can ensure that their applications are secure, reliable, and trusted by their users.



Spring Security Implementation in spring boot


Implementing Spring Security in a Spring Boot application involves several steps. Here's a basic outline of the process:

  1. Add Spring Security to your dependencies: Open your pom.xml file and add the following dependency:
<dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> </dependency>
  1. Create a Security Configuration class: Create a new class that extends the WebSecurityConfigurerAdapter class. This class is responsible for configuring Spring Security in your application.
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/public/**").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/dashboard") .permitAll() .and() .logout() .permitAll(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user").password("{noop}password").roles("USER") .and() .withUser("admin").password("{noop}password").roles("ADMIN"); } }
This configuration enables HTTP basic authentication for all requests except those that match /public/**, which are accessible without authentication. It also defines two users, "user" and "admin", with passwords "password" and roles "USER" and "ADMIN", respectively.
  1. Secure your endpoints: You can secure individual endpoints by adding the @Secured annotation to the method or class. For example:
@RestController public class MyController { @Secured("ROLE_USER") @GetMapping("/nik-endpoint") public String nikEndpoint() { return "Hello, user!"; } }
This endpoint can only be accessed by users with the "USER" role. You can add multiple role as well.
  1. Customize the login and logout pages: You can customize the login and logout pages by creating templates in your src/main/resources/templates directory. For example, create a file called login.html with the following contents:
<!DOCTYPE html> <html> <head> <title>Login</title> </head> <body> <h1>Login</h1> <form action="/login" method="post"> <div> <label for="username">Username:</label> <input type="text" id="username" name="username"/> </div> <div> <label for="password">Password:</label> <input type="password" id="password" name="password"/> </div> <div> <button type="submit">Login</button> </div> </form> </body> </html>
  1. Test your application: Start your application and navigate to the login page. Enter the credentials of one of the users defined in your configuration, and you should be redirected to the dashboard page.

These are the basic steps for implementing Spring Security in a Spring Boot application. Of course, you can customize your configuration in many ways to fit your specific requirements.

Best Practices while implementing Spring security


Implementing Spring Security in Spring Boot is a critical aspect of building secure applications. Here are some best practices to follow while implementing Spring Security in Spring Boot:

  1. Use a Strong Password Encoder: Spring Security provides several password encoders such as BCrypt, SCrypt, and PBKDF2. It is essential to choose a strong password encoder to ensure the security of user passwords.

  2. Use HTTPS: It is recommended to use HTTPS to secure communications between the client and the server. Spring Boot makes it easy to configure HTTPS by using an SSL certificate.

  3. Implement Role-based Access Control (RBAC): Role-based access control allows you to restrict access to certain resources based on a user's role. It is essential to implement RBAC to prevent unauthorized access to sensitive information.

  4. Avoid Storing Sensitive Information in Plain Text: It is essential to avoid storing sensitive information such as passwords, API keys, and access tokens in plain text. Spring Security provides several ways to encrypt sensitive information, such as using Jasypt or the Spring Security Crypto module.

  5. Implement CSRF Protection: Cross-Site Request Forgery (CSRF) attacks are a common web application security vulnerability. Spring Security provides built-in CSRF protection, which you can enable by adding a CSRF token to each form.

  6. Keep Dependencies Up-to-date: It is crucial to keep your dependencies up-to-date to avoid security vulnerabilities. Spring Boot provides a dependency management plugin that makes it easy to manage your dependencies.

  7. Enable Security Auditing: Enabling security auditing can help you identify security vulnerabilities and track security-related events. Spring Security provides several auditing features, such as audit logging and event publication.

  8. Use Security Headers: Security headers can help protect your application against common web application security vulnerabilities such as cross-site scripting (XSS) and clickjacking. Spring Security provides built-in support for security headers, which you can configure in your application.

By following these best practices, you can improve the security of your Spring Boot applications and reduce the risk of security vulnerabilities.