Powered by Blogger.

How to receive a JWT-based access token from the client, verify the token, and push data using the client's URL?

1 comment :
JWT OAuth2 Integration and JSON Payload Handling in Java: JWT (JSON Web Token) is a token format used in OAuth2.
A JWT is:
  • Stateless
  • Digitally signed
  • Self-contained
Integrating with client APIs using APIs and JSON-based payloads involves an end-to-end process that includes making API calls with JSON payloads and pushing master/other data to REST API endpoints.

Step 1: Obtain the authentication details/Requirements from the client as shown in the example below.

############_MK_TOKEN_CLIENT_SECRET_#################### 

TOKEN_URL=https://a143mk-uat.client.com/api/v1/client/authentication/generate_token CLIENT_ID=AA143Mkbolgs  
CLIENT_SECRET=testa143mk

 ####Example of Configure URL ############# 
CUST_URL=https://a143mk-uat.client.com/api/master/push_customer 
CUST_USER_PASS_AUTH=useradmin:password //if it is required or not


Step 2: Making an API call with an Json payload and pushing master data to the location.
  1. A REST API Controller is responsible for handling HTTP requests (such as GET, POST, PUT, DELETE) from clients and routing them to the appropriate service methods. It acts as the entry point for external clients to interact with the backend application. 
  2. Purpose: The main role of the controller is to manage incoming HTTP requests, map them to specific methods (often called endpoints), and return appropriate responses to the client. 
  3. Responsibilities: Handle HTTP requests (e.g., GET, POST, PUT, DELETE). Map the incoming requests to service methods. Return HTTP responses, often in JSON or Json format. Perform basic request validation or authentication. Act as the "interface" between the client and the service layer. In a Spring Boot application, for example, the controller is typically annotated with @RestController and the request mappings are handled using annotations like @GetMapping, @PostMapping, etc. 
Example "ClientApiController.java" of a REST Controller in Spring Boot with handlined Json Payload :
 
 
The Service class is a part of the business logic layer of your application. It contains methods that implement the core functionality of the application (e.g., creating, reading, updating, deleting data). The service class is called by the controller to perform operations that are not directly related to the web request itself. 
  1. Purpose: The service layer acts as a mediator between the controller and the data layer (such as a repository or database). It focuses on business logic and operations. 
  2. Responsibilities: Perform the core business logic of the application. Interact with the database (via repositories or DAOs). Provide methods for the controller to use (i.e., encapsulate business operations). Handle any necessary validation or transformation before sending data back to the controller. In a Spring Boot application, service classes are typically annotated with @Service, and they are injected into the controller using @Autowired (or constructor injection). 
Example "CustMastSystemNameService.java" of a Service Class in Spring Boot: 
 Method Internal Working ->geta143mkCustMasterFOrSYS() ->pusha143mkCustToSystemNameSystem().
 


Step 3: The authorization server issues an access token in JWT format The client sends this token in requests using Authorization: Bearer<Token>
The API validates the JWT by checking its signature, expiration, issuer, and audience See the example below for how to obtain an access token for the client: Use this for server-to-server authentication.
 Method Internal Working ->geta143mkCustMasterFOrSYS() ->pusha143mkCustToSystemNameSystem().
 

JWT-based access tokens are secure, stateless, and scalable, making them ideal for modern authentication and authorization systems.

API Integration and XML payload Handling

No comments :
API integration and XML payload handling in Java using HttpURLConnection and the Apache HttpClient library. To integrate with a client API using an API and XML-based payload, the entire process includes:
  1. ClientURLConfig.properties: Used to store client credential details Making an API call with an JSON/XML payload and pushing data communication.
  2. Data Communication from the two Client API using the JSON/XML payload API.
Step 1: ClientURLConfig.properties
 ####Example of Configure URL ############# 
CUST_URL=https://a143mk.com:443/a143mk1_test/MK/api/init_stage_interface/ CUST_USER_PASS_AUTH=useradmin:password

Step 2: Making an API call with an XML payload and pushing master data to the location.
  1. A REST API Controller is responsible for handling HTTP requests (such as GET, POST, PUT, DELETE) from clients and routing them to the appropriate service methods. It acts as the entry point for external clients to interact with the backend application. 
  2. Purpose: The main role of the controller is to manage incoming HTTP requests, map them to specific methods (often called endpoints), and return appropriate responses to the client. 
  3. Responsibilities: Handle HTTP requests (e.g., GET, POST, PUT, DELETE). Map the incoming requests to service methods. Return HTTP responses, often in JSON or XML format. Perform basic request validation or authentication. Act as the "interface" between the client and the service layer. In a Spring Boot application, for example, the controller is typically annotated with @RestController and the request mappings are handled using annotations like @GetMapping, @PostMapping, etc. 
Example of a REST Controller in Spring Boot with handlined XML Payload :
 
 
The Service class is a part of the business logic layer of your application. It contains methods that implement the core functionality of the application (e.g., creating, reading, updating, deleting data). The service class is called by the controller to perform operations that are not directly related to the web request itself. 
  1. Purpose: The service layer acts as a mediator between the controller and the data layer (such as a repository or database). It focuses on business logic and operations. 
  2. Responsibilities: Perform the core business logic of the application. Interact with the database (via repositories or DAOs). Provide methods for the controller to use (i.e., encapsulate business operations). Handle any necessary validation or transformation before sending data back to the controller. In a Spring Boot application, service classes are typically annotated with @Service, and they are injected into the controller using @Autowired (or constructor injection). 
Example of a Service Class in Spring Boot: 
 Method Internal Working ->getAllCustomerStores()->buildCustomerXmlPayload()->pushCustomerXmlToa143mkClient().
 


To test an API endpoint URL like https://a143mk.com/api/puchCustData/pushCustomerToClient using Postman, refer to the image. This will allow you to verify the API's functionality and inspect the response.



Cross-Origin Resource Sharing

No comments :
CROSS is a system that allows client web applications (such as JavaScript code) loaded on one domain to interact with resources located on a different domain.
Origin: An "Origin" (or source) URL consists of three parts: 
Protocol (scheme): Such as http or https.
Domain (host): Such as a143mk.blogspot.com or localhost. 
Port (port number): Such as 8080 or 3000. 
If any of these three parts are different in a request, it is called a Cross-Origin request.
Example:
If your frontend (endpoints.com) sends a request to a backend API (api.com), it is Cross-Origin and will be intercepted by the browser. CORS is a way to relax this security restriction in a controlled manner, allowing legitimate cross-origin communication.
 


Configuring CORS globally in Spring Boot is the preferred approach, as it saves you from having to apply the @CrossOrigin annotation to every controller or method and keeps the configuration centralized.
Example: This method defines global CORS settings 
  1.  addMapping("/**"): This indicates that the CORS mapping will apply to all paths. 
  2.  allowedOrigins: Defines the client origins that are allowed to access your API. 
  3.  allowedMethods: The HTTP methods that are allowed. 
  4.  allowedHeaders: Allows all headers sent by the client. 
  5.  allowedCredentials: Set this to 'true' if the client is using cookies or HTTP authentication. 
  6.  maxAge: The time (in seconds) to cache the results of a pre-flight request.

Implementing JWT Token for secure authentication

1 comment :
Implementing JWT (JSON Web Token) in Java typically involves creating a secure authentication mechanism for your web applications. Below is a basic guide to implement JWT using Java, Spring MVC, and jjwt (a popular Java JWT library).
WorkFlow:
















The lifecycle of a JSON Web Token (JWT) typically involves several stages, from creation to expiration and validation. JWTs are widely used for securely transmitting information between parties in the form of a signed and optionally encrypted token. Here’s an overview of the typical lifecycle: Token Creation
Authentication: When a user logs in, they typically provide credentials (e.g., username and password).
Server Validation: The server validates these credentials (e.g., checks the database for the user’s password).
JWT Creation: If the credentials are correct, the server generates a JWT. The token contains:
Header: Describes the signing algorithm (e.g., HS256, RS256) and token type (JWT).
Payload: Contains the claims. Claims are pieces of information (e.g., user ID, expiration time) that are encoded in the token.
Signature: The header and payload are signed with a secret key (HMAC) or a private key (RSA or ECDSA) to ensure integrity.
 
Download Jar file: jjwt-api-0.10.5.jar

To create a A143mk.JWTAPIConfig, we first need to define a package that will be handled in the configuration.
Create classes name in the A143mk.JWTAPIConfig package. 
  1.  JwtRequestFilter 
  2.  JwtUtil 
  3.  SecurityConfig 
  4.  AuthRequest
1. JwtRequestFilter
2.JwtUtil
3. SecurityConfig
4. AuthRequest/PayloderBeanClass
Create a Controller class create a simple controller name is AuthController an endpoint is accessed.

Steps to Test JWT Token in Postman:
Obtain the JWT Token: First, you need to obtain the JWT token from your authentication endpoint. Typically, this is done by making a POST request to your login endpoint with the correct user credentials (username, password, etc.). 
Example (login request):
{
  "username": "A143mk@Manoj"
}

Result :
eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJCQVRBQGRtc0Vjb20iLCJpYXQiOjE3NDc5MDc5MzYsImV4cCI6MTc0NzkxMTUzNn0.1eEK4gwwR3mr2bqcIoYYjxwpcTzUKOCtBMH-GBo6X_4

LDAP (Lightweight Directory Access Protocol) authentication in a Spring Boot.

3 comments :
LDAP
(Lightweight Directory Access Protocol) authentication in a Spring Boot application typically involves using Spring Security to configure LDAP authentication properly, ensuring that sensitive data like passwords is protected and communication with the LDAP server is secure.
Here’s a basic guide to securing LDAP authentication in a Spring Boot application:
Add Dependencies:In your pom.xml, add the following dependencies for Spring Security and LDAP:

LDAP Configuration: In your application.properties or application.yml, configure the LDAP server details:
# application.properties 
spring.ldap.urls=ldap://localhost:389 
spring.ldap.base=dc=example,dc=com 
spring.ldap.username=uid=admin,ou=system 
spring.ldap.password=password 
spring.ldap.embedded.enabled=false

Spring Security Configuration :You can configure Spring Security to authenticate using LDAP by defining a SecurityConfig class.
Here is an example:
Enable Secure LDAP Connections:
If you are using LDAP over TLS/SSL (LDAPS), it’s critical to ensure that your LDAP communication is secured. Change the URL to:
spring.ldap.urls=ldaps://localhost:636
Ensure that your LDAP server supports LDAPS and that proper certificates are installed on the server. If you are using SSL, you can also import the certificate into your Java Keystore (JKS).
Secure Password Handling:In the above configuration, passwords are compared using passwordCompare(). It's recommended to use a hashed password encoder like BCryptPasswordEncoder, which is configured in the example to secure the passwords.
Customizing the Login Page:You can customize your login page if needed by creating a controller for the login and error handling views:


Role Mapping (Optional):If you want to map roles from LDAP groups or other attributes, you can use LdapAuthoritiesPopulator to fetch roles.


This will ensure the roles are properly populated from LDAP.
Test the Application:Start your Spring Boot application, and it should authenticate users against the LDAP server. Make sure you test with the proper credentials to confirm everything is working securely.

Summary of Key Points:
  1.  LDAP Configuration: Use spring.ldap properties to configure the LDAP server details. 
  2.  Spring Security: Configure Spring Security to handle LDAP authentication with ldapAuthentication(). 
  3.  SSL/TLS: Ensure the LDAP communication is encrypted (use ldaps://). 
  4.  Password Encoding: Use a secure password encoder like BCryptPasswordEncoder. 
  5.  Role Mapping: Map roles from LDAP as needed using LdapAuthoritiesPopulator. This setup will help you integrate LDAP securely in your Spring Boot application.


Configuration SSL Certificate in Tomcat server

1 comment :
To, configure SSL in the server.xml file for Apache Tomcat, follow these steps.
Steps: 
1. Generate or Obtain an SSL Certificate with Other Files.
Required Files:
 
2. Locate the server.xml file.
The server.xml file is typically located in the conf directory inside your Tomcat installation.
Path example:/path/to/tomcat/conf/server.xml

3. Edit server.xml
Open the server.xml file in a text editor and find the section for the HTTPS connector. By default, it may be commented out. You need to configure this section to enable SSL. Here’s an example of how to configure SSL for Tomcat:

4. Configure Redirect from HTTP to HTTPS (Optional) To force all HTTP traffic to be redirected to HTTPS, you can add a redirect connector for HTTP (typically port 80). For example, below the HTTP connector section in the server.xml file:

This will redirect traffic from HTTP (port 8080) to HTTPS (port 8443).
5. Restart Tomcat After making these changes, restart your Tomcat server for the changes to take effect. ..../bin/shutdown.sh
..../bin/startup.sh
6. Verify SSL Configuration
Open a browser and navigate to https://:8443.
Check for a secure connection (padlock symbol) in the browser's address bar.

Additional Notes:
  • You can use port 443 (standard HTTPS port) instead of 8443, but you may need root privileges to bind to port 443, or use a reverse proxy to map it.
  • If you're running Tomcat behind a reverse proxy (like Apache HTTPD), you may need to adjust the connector settings accordingly. Let me know if you need further clarification or help!

Introduction of Angular and AngularJS

3 comments :
Here’s a list of common Angular and AngularJS along with detailed examples to help you prepare.
Angular: Angular is a platform and framework for building single-page client applications using HTML, CSS, and JavaScript/TypeScript. It is a complete rewrite of AngularJS, developed by Google. Angular uses TypeScript, which is a superset of JavaScript, offering strong typing, interfaces, and decorators. 
  • Key features of Angular:
  • Two-way data binding
  • Directives for extending HTML capabilities
  • Dependency injection
  • Routing and navigation
  • Components-based architecture
Difference between AngularJS and Angular:
AngularJS  is the original version of Angular, and Angular (2 and above) is a complete rewrite.
Key differences:
Architecture: Angular uses a component-based architecture, whereas AngularJS uses a directive-based architecture.
Language: Angular uses TypeScript, while AngularJS uses JavaScript.
Performance: Angular has better performance because of the use of a new change detection mechanism (in Angular 2+).
Dependency Injection (DI): Angular's DI is more powerful and more flexible than AngularJS.
Angular Components:
In Angular, a component is a building block of the application. It controls a portion of the user interface (UI), with each component consisting of:
  • HTML template (view)
  • CSS styles (view styles)
  • TypeScript class (logic and data)
Example:

In this example, HelloComponent is an Angular component with a template displaying a message.
Data binding in Angular? Explain the types of data binding. Data binding in Angular is the mechanism to synchronize the data between the component and the view. Angular supports several types of data binding:
Interpolation: Binding data from the component to the view.
{{ title }}

Property Binding: Bind an element property to a component property.
<img [src]="imageUrl" alt="Image">

Event Binding: Bind an event (e.g., click) to a method in the component.
<button (click)="onClick()">Click Me</button>

Two-Way Data Binding: Combines property and event binding.
<input [(ngModel)]="username">

Dependency Injection (DI) in Angular?
Dependency Injection (DI) is a design pattern used in Angular to achieve Inversion of Control (IoC). It allows services or objects to be injected into components or other services rather than being created manually inside the component.
Example:

In this example, the DataService is injected into DataComponent via DI, and its method getData() is used in the component.
Angular Routing:
Angular Routing allows you to define routes and navigate between different views or pages in a single-page application (SPA). The routing module helps handle navigation and deep linking.
Example: Define routes in app-routing.module.ts:
Use the router-outlet in app.component.html:
<router-outlet></router-outlet>

Navigating using the routerLink directive:
<a routerLink="/about">About</a>

Service in Angular:
A service is a class in Angular used to handle logic that can be shared across multiple components. Services are commonly used for business logic, data fetching, and state management. Services are injected into components or other services using Angular’s Dependency Injection system.
Example:

In the component, the service is injected:

Directives in Angular:
Directives are special markers in the DOM that allow Angular to modify the DOM structure. There are three types of directives in Angular:
Component Directives: These are the most common type of directives and include templates and logic (e.g., @Component).
Structural Directives: These modify the structure of the DOM (e.g., *ngIf, *ngFor).
Attribute Directives: These change the appearance or behavior of an element (e.g., ngClass, ngStyle).
Example: *ngIf: Conditionally display an element.
<div *ngIf="isVisible">This content is visible.</div>

Observables in Angular:
Observables are a core part of Angular’s reactive programming. They represent a stream of asynchronous events. Angular uses RxJS (Reactive Extensions for JavaScript) for handling asynchronous operations like HTTP requests, user input, or timer events.
Example:

In this example, the HttpClient service returns an Observable, and subscribe() is used to handle the response asynchronously.
Pipes in Angular:
Pipes are used to transform data in the template before it is displayed. Angular provides several built-in pipes like DatePipe, UpperCasePipe, LowerCasePipe, and CurrencyPipe. You can also create custom pipes.
Example:
{{ birthday | date: 'shortDate' }}

In this example, birthday will be transformed into a formatted date using the DatePipe.
You can also create custom pipes:

In the template:
{{ 'Angular' | reverse }}

These are some of the key Angular and AngularJS, along with practical examples. Practicing these concepts and writing code will help you to be more prepared for your Development!

How To Use Predicate In Java 8

1 comment :
In Java 8,
The Predicate is a functional interface that represents a single argument function that returns a boolean value. It is widely used in functional programming, especially when working with streams, as it allows you to define conditions that can be tested.
The Predicate Interface: Let’s look at an example of how to use the @FunctionalInterface annotation in a Spring Boot application:

The Predicate interface contains a method called test(T t) that evaluates a condition and returns a boolean. It also contains some useful default methods like:
  • and(Predicate other): Combines two predicates with a logical AND. 
  • or(Predicate other): Combines two predicates with a logical OR. 
  • negate(): Negates the result of the predicate.
Example 1: Simple Predicate In the following example, a Predicate is used to test whether a number is greater than 10

Example 2: Combining Predicates with and(), or(), and negate() You can combine multiple predicates to create more complex conditions using and(), or(), and negate().

Example 3: Using Predicate with Collections and Streams The Predicate interface is often used with the Streams API to filter collections based on certain conditions.

Example 4: Predicate with isEqual Static Method Java 8 introduces a static method isEqual in the Predicate interface, which is used to create a predicate that checks if two objects are equal.

Example 5: Using Predicate with a List of Objects You can use predicates to filter lists of custom objects. Hare's an example where we filter a list of Person objects based on age.

Summary of Predicate Methods: 
test(T t): Evaluates the predicate on the given argument and returns true or false. 
and(Predicate other): Combines this predicate with another one using logical AND. 
or(Predicate other): Combines this predicate with another one using logical OR. 
negate(): Reverses the result of the predicate (logical NOT). 
isEqual(Object targetRef): Creates a predicate that checks if an object is equal to the given target.
 
* Common Use Cases: 
 Filtering collections with Stream.filter(). Validating input, such as checking if a string matches a pattern or if a number falls within a range. Using complex conditional logic in combination with other predicates.
Predicates are a powerful tool in functional programming and are heavily used in Java 8's Streams API to make code more readable and expressive.

Spring Framework `@ExceptionHandler`

No comments :
In Spring Framework, the `@ExceptionHandler` annotation is used to handle exceptions that occur during the execution of a controller method. This allows you to handle specific exceptions in a centralized manner without cluttering your code with `try-catch` blocks. You can define exception handler methods in your controller or in a global exception handler class.
 
Example of using @ExceptionHandler:
Let’s look at an example of how to use the `@ExceptionHandler` annotation in a Spring Boot application:
Create a custom exception class First, let's define a custom exception that we will handle in the controller.
 


Create a Controller that throws the exception In this step, we’ll create a simple controller that throws a `ResourceNotFoundException` when an endpoint is accessed.
 


Handle the exception using `@ExceptionHandler`  Now, let’s handle the `ResourceNotFoundException` using the `@ExceptionHandler` annotation in the same controller.
 


For Explanation :
  • @RestControllerAdvice: This is a specialized version of @ControllerAdvice that is used for global exception handling in @RestController methods. It allows you to handle exceptions across all controllers.
  •  @ExceptionHandler(ResourceNotFoundException.class): This annotation tells Spring that whenever a `ResourceNotFoundException` is thrown, the `handleResourceNotFoundException` method should handle it. 
  • ResponseEntity: The method returns a ResponseEntity with a custom message and HTTP status code (404 in this case).
 
Running the Application When you run this Spring Boot application and access the /resource/{id} endpoint with an invalid ID (e.g., `/resource/0` or `/resource/-1`), it will return a response like:
HTTP Status: 404 Not Found Body: Resource with ID 0 not found!
Example Output:
  • - When accessing `/resource/1`, it will return "Resource found with ID 1"
  • - When accessing `/resource/0`, it will return a 404 response with the message "Resource with ID 0 not found!".
Advantages of using @ExceptionHandler:
 Centralized exception handling. - Cleaner code with no need for `try-catch` blocks in each controller method. 
 Ability to return custom error responses with HTTP status codes. You can handle multiple exceptions in a similar way by adding more `@ExceptionHandler` methods in the same class, or even define exception handling globally for all controllers using `@ControllerAdvice` instead of `@RestControllerAdvice`.

Handling Exceptions in an API when Integrating with an API Gateway.

5 comments :
Handling exceptions in an API when integrating with an API Gateway is crucial for maintaining robust, secure, and user-friendly services. The API Gateway often acts as a middleman between your clients and your backend services, so it needs to handle errors effectively to ensure that meaningful and actionable responses are provided to clients. Here's a structured approach to handling exceptions from your API to the API Gateway:
Design Consistent Error Responses:
Ensure that your backend APIs provide consistent and meaningful error responses. This helps the API Gateway understand and relay errors appropriately. 
Example Error Response Structure:
json
{
    "error": {
        "code": "RESOURCE_NOT_FOUND",
        "message": "The requested resource was not found.",
        "details": "Resource ID: 12345"
    }
}

Handle Exceptions in Backend Services: Implement proper exception handling in your backend services. Catch exceptions and convert them into meaningful error responses. 
Java Example:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<ErrorResponse> handleResourceNotFound(ResourceNotFoundException ex) {
        ErrorResponse errorResponse = new ErrorResponse("RESOURCE_NOT_FOUND", ex.getMessage());
        return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResponse> handleGeneralException(Exception ex) {
        ErrorResponse errorResponse = new ErrorResponse("INTERNAL_SERVER_ERROR", "An unexpected error occurred.");
        return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    // Define ErrorResponse class
    public static class ErrorResponse {
        private String code;
        private String message;

        // Constructor, getters, and setters
    }
}

Configure API Gateway for Error Handling:
API Gateways like AWS API Gateway, Google Cloud Endpoints, or Azure API Management allow you to configure how errors are handled and transformed. 
AWS API Gateway Example: 
Create Custom Error Responses: Define custom error responses in the API Gateway settings. This includes mapping HTTP status codes from your backend to user-friendly messages or custom error codes. 
Set Up Gateway Responses: Configure Gateway Responses to handle specific HTTP status codes (e.g., 500 Internal Server Error) and provide custom error messages or redirection. 
Use Integration Responses: Map backend error responses to different HTTP status codes and customize the response format in the API Gateway
Logging and Monitoring:
Implement logging and monitoring to track and analyze errors. This helps in diagnosing issues and improving your API services. 
Example Using AWS CloudWatch: 
Enable Logging: Configure API Gateway to log request and response details. 
Set Up Alarms: Create CloudWatch Alarms for specific error conditions (e.g., high 5xx error rates).
Testing and Validation: Thoroughly test your API error handling to ensure that errors are propagated and transformed correctly through the API Gateway. 
Steps: 
Unit Tests: Test backend error responses and exception handling. 
Integration Tests: Test the full flow through the API Gateway to ensure errors are handled correctly and responses are as expected.
Summary:
Backend Services: Handle exceptions and return consistent error responses. 
API Gateway Configuration: Map and customize error responses, configure Gateway Responses, and set up logging. 
Logging and Monitoring: Track errors and performance using tools like AWS CloudWatch. 
Testing: 
Validate error handling through unit and integration tests. By following these steps, you ensure that your API Gateway can effectively manage and relay errors, providing a better experience for clients and aiding in the maintenance and debugging of your services.