Posts

Showing posts with the label Spring Boot

Mapped Diagnostic Context (MDC) - Improved Java Logging

Mapped Diagnostic Context provides a way to enrich log messages with information that could be unavailable in the scope where the logging actually occurs but that can be indeed useful to better track the execution of the program. More detail, refer -  https://www.baeldung.com/mdc-in-log4j-2-logback

Rest Template Vs Web Client

Since the REST era, most developers have become used to working with Spring’s traditional RestTemplate from the package spring-boot-starter-web for consuming Rest services. Spring also has a WebClient in its reactive package called spring-boot-starter-webflux. Since WebClient is supposed to be the successor of RestTemplate, we will be looking into it a bit deeper. RestTemplate provides a synchronous way of consuming Rest services, which means it will block the thread until it receives a response. RestTemplate is deprecated since Spring 5 which means it’s not really that future proof. WebClient exists since Spring 5 and provides an asynchronous way of consuming Rest services, which means it operates in a non-blocking way. WebClient is in the reactive WebFlux library and thus it uses the reactive streams approach. However, to really benefit from this, the entire throughput should be reactive end-to-end.  Another benefit of working with Flux and Mono is that you can do mappings, filte...

Can we have more than 1 SpringBootAppliction Class

Spring Boot - Configure Multiple DBs (In Progress)

  First you have to set application.properties like this #Database database1.datasource.url=jdbc:mysql: //localhost/testdb database1.datasource.username=root database1.datasource.password=root database1.datasource.driver- class -name=com.mysql.jdbc.Driver database2.datasource.url=jdbc:mysql: //localhost/testdb2 database2.datasource.username=root database2.datasource.password=root database2.datasource.driver- class -name=com.mysql.jdbc.Driver Then define them as providers (@Bean) like this : @Bean(name = "datasource1" ) @ConfigurationProperties( "database1.datasource" ) @Primary public DataSource dataSource(){ return DataSourceBuilder.create().build(); } @Bean(name = "datasource2" ) @ConfigurationProperties( "database2.datasource" ) public DataSource dataSource2(){ return DataSourceBuilder.create().build(); } Note that I have @Bean(name= "datasource1" ) and @Bean(name= "datasource2...

Config Server (In Progress)

Image
 In micro-service world, managing configurations of each service separately is a tedious and time-consuming task. In other words, if there are many number of modules, and managing properties for each module with the traditional approach is very difficult. Central configuration server provides configurations (properties) to each micro service connected. As mentioned in the above diagram, Spring Cloud Config Server can be used as a central cloud config server by integrating to several environments.

Spring IOC Container

The IoC container is responsible to instantiate, configure and assemble the objects. The IoC container gets informations from the XML file and works accordingly. The main tasks performed by IoC container are: 1) to instantiate the application class 2) to configure the object 3) to assemble the dependencies between the objects There are two types of IoC containers. They are: 1) BeanFactory 2) ApplicationContext The BeanFactory and the ApplicationContext interfaces acts as the IoC container. The ApplicationContext interface is built on top of the BeanFactory interface. It adds some extra functionality than BeanFactory such as simple integration with Spring's AOP, message resource handling (for I18N), event propagation, application layer specific context (e.g. WebApplicationContext) for web application. So it is better to use ApplicationContext than BeanFactory.

Spring Profiles

Spring Profiles helps segregating your application configurations, and make them available only in certain environments.  Profiles are a core feature of the framework — allowing us to map our beans to different profiles — for example, dev, test, and prod. We can then activate different profiles in different environments to bootstrap only the beans we need. An application run on many different environments. For example, Dev, QA, Test, Stage, Production etc. Therefore, an application may need different configurations on different environments.. In other words, configurations like databases, messaging systems, server ports, security will be different from environment to environment. Spring Profiles helps to easily set right configurations on right environments. Otherwise, without having Spring Profiles it is a big pain to manage environment specific configurations. For example, your application may have to rely on the configurations externalised on the environments. Obviously, that is fa...

Spring Boot Actuator

Image
Actuator is mainly used to expose operational information about the running application — health, metrics, info, dump, env, etc. It uses HTTP endpoints or JMX beans to enable us to interact with it. < dependency > < groupId > org.springframework.boot </ groupId > < artifactId > spring-boot-starter-actuator </ artifactId > </ dependency > management.endpoints.web.exposure.include=* List of endpoints (More than 15 endpoints) Here are some of the most common endpoints Boot provides out of the box: /health  shows application health information (a simple  status  when accessed over an unauthenticated connection or full message details when authenticated); it's not sensitive by default. /info  displays arbitrary application info; it's not sensitive by default. /metrics  shows metrics information for the current application; it's sensitive by default. /trace  displays trace information (by default the last few HTTP re...

Bean Refresh in Spring Boot

Image
Update config values in your microservices at runtime without having to restart them. Use Actuator endpoints to trigger refresh and use the RefreshScope annotation to have the values refresh in the microservices.

Spring Boot Starter

 Dependency management is a critical aspects of any complex project. And doing this manually is less than ideal; the more time you spent on it the less time you have on the other important aspects of the project. Spring Boot starters were built to address exactly this problem. Starter POMs are a set of convenient dependency descriptors that you can include in your application. You get a one-stop-shop for all the Spring and related technology that you need, without having to hunt through sample code and copy-paste loads of dependency descriptors. We have more than 30 Boot starters available. Examples - Web Starter, Test Starter, Data JPA starter, etc. Web Starter - First, let's look at developing the REST service; we can use libraries like Spring MVC, Tomcat and Jackson – a lot of dependencies for a single application. Spring Boot starters can help to reduce the number of manually added dependencies just by adding one dependency. So instead of manually specifying the dependencies j...

JWT Token

The situation is: The user opens the app and provides his login credentials. Now, most probably the app is interacting with a REST backend service. REST is stateless, there isn't a way to authorize access to the APIs. Hence, so far in the discussion, there is no way to check if an authorized user is accessing the APIs or is just some random requests coming through. Now to be able to solve this problem, we need a way to know that the requests are coming from an authorized user. So, what we did was to introduce something called an access token. So now once the user is authenticated successfully, he is issued an access token. This token is supposed to be a long and highly random token (to ensure that it can not be guessed). This is where the JWT comes into the picture. Now you may/may not want to store any user-specific details in a JWT token. Ideally, you would want to just store very simple, extremely non-sensitive details in the JWT. The manipulation of the JWT hash to retrieve oth...

Security Testing Tools

1) Burp Suite Community Version. 2) OWASP ZAP 3) SSLScanner 4) Dirbuster 5) Nikto 6) Nmap

Spring Data JPA

The Spring Data Generated DAO – No More DAO Implementations The DAO layer usually consists of a lot of boilerplate code that can and should be simplified. The advantages of such a simplification are many: a decrease in the number of artifacts that we need to define and maintain, consistency of data access patterns, and consistency of configuration. Spring Data takes this simplification one step further and makes it possible to remove the DAO implementations entirely. The interface of the DAO is now the only artifact that we need to explicitly define. In order to start leveraging the Spring Data programming model with JPA, a DAO interface needs to extend the JPA specific Repository interface, JpaRepository. This will enable Spring Data to find this interface and automatically create an implementation for it. Automatic Custom Queries When Spring Data creates a new Repository implementation, it analyses all the methods defined by the interfaces and tries to automatically generate queries ...

OAuth

Image
It works by delegating user authentication to the service that hosts a user account and authorizing third-party applications to access that user account. OAuth 2 provides authorization flows for web and desktop applications, as well as mobile devices. OAuth Roles OAuth defines four roles: Resource Owner: The resource owner is the user who authorizes an application to access their account. The application’s access to the user’s account is limited to the scope of the authorization granted (e.g. read or write access) Client: The client is the application that wants to access the user’s account. Before it may do so, it must be authorized by the user, and the authorization must be validated by the API. Resource Server: The resource server hosts the protected user accounts. Authorization Server: The authorization server verifies the identity of the user then issues access tokens to the application. Here is a more detailed explanation of the steps in the diagram: 1.The application requests ...

WEB SECURTY

Image
CSRF Cross-Site Request Forgery ( CSRF ) is an attack that forces authenticated users to submit a request to a Web application against which they are currently authenticated. CSRF attacks exploit the trust a Web application has in an authenticated user. Web browser store information in cookies and it contains sessionId and other details. And if someone sends a URL of the website and we click on it then it can place request to the server with our authenticated session.  CORS (Cross Origin Resource Sharing) Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources. If origin A wants to talk to origin B then Origin A Should have Access-Control-Allow-Origin:www.abc.om in header.