REST Service with Basic Authentication
Use case
This REST service is designed to expose customer data securely. The service requires Basic Authentication, ensuring that only authorized users with a valid username and password can access the data.
Design
The solution consists of two main components:
-
REST Service: Implemented using Apache Camel's REST DSL in
rest.camel.yaml
-
Route Implementation: The business logic of the service is implemented in a Camel route. This route handles the processing of requests and returning the customer data. Implementd in
service.camel.yaml
Authentication:
The service uses Basic Authentication for security. The username and password are extracted from the HTTP headers of incoming requests. These credentials are then verified against a static example for validation. If the credentials match the expected values, the request is processed; otherwise, the request is denied.
YAML
- rest:
id: rest-b46b
description: Customer Service
consumes: application/json
produces: application/json
get:
- id: get-0fa7
description: Get Customer
path: /customer
to: direct:get-customer
- route:
id: route-customer
description: Get Customer
nodePrefixId: route-48d
from:
id: from-8182
uri: direct
parameters:
name: get-customer
steps:
- script:
id: script-4a0e
description: Get Authorization Header
expression:
groovy:
id: groovy-ee51
expression: |-
import java.nio.charset.StandardCharsets;
import java.util.Base64;
def authorization = headers["Authorization"]
if (authorization) {
def token = authorization.substring("Basic".length()).trim()
def decoded = Base64.getDecoder().decode(token)
def decodedStr = new String(decoded, StandardCharsets.UTF_8)
def parts = decodedStr.split(":")
exchange.setVariable("username", parts[0])
exchange.setVariable("password", parts[1])
} else {
exchange.getIn().setHeader("CamelHttpResponseCode", 401);
}
- choice:
id: choice-18af
when:
- id: when-81e0
description: Validated
expression:
groovy:
id: groovy-2cea
expression: >-
variables.username == 'Aladdin' && variables.password ==
'OpenSesame'
steps:
- setBody:
id: setBody-b1aa
description: Set Response
expression:
groovy:
id: groovy-904b
expression: |-
[
id: "000001",
name: "John Smith",
account: "special"
]
- marshal:
id: marshal-6528
description: Marshal to JSON
json:
id: json-ffa3
otherwise:
id: otherwise-5ce8
steps:
- setHeader:
id: setHeader-ed89
name: CamelHttpResponseCode
expression:
constant:
id: constant-a283
expression: "401"
Examples
Call service
curl --location 'localhost:8080/customer' --header 'Content-Type: application/json' --header 'Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l'
Expected response: