Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ This slice provides an internal, bounded authentication foundation:
- container and Helm packaging for local Kubernetes SIT;
- `POST /api/v1/auth/login` with validated credentials and signed JWT issuance;
- `POST /api/v1/auth/logout` with server-side, idempotent session revocation;
- `GET /api/v1/auth/session` with bearer-protected validation against signed JWT claims and PostgreSQL session state;
- configurable `REVOKE_PREVIOUS` or `ALLOW_MULTIPLE` session policy, defaulting conservatively to `REVOKE_PREVIOUS`;
- PostgreSQL-backed session persistence with Flyway migrations, durable token lookup, and replica-safe same-user session policy;
- Maven verification with Spotless, JaCoCo, Surefire, and Failsafe.
Expand Down Expand Up @@ -85,6 +86,7 @@ The current integration tests start the application on a random port and verify:

- `/actuator/health` returns `200` and `UP`;
- `/v3/api-docs` returns the explicit service title, internal description, contract version `1.0.0`, and both auth paths;
- session validation returns the authenticated subject and session ID only while the signed token and server-side session remain valid;
- login returns a JWT with signed `sub`, `sid`, `active`, `iss`, `iat`, and `exp` claims, plus the configured space-delimited `scope` claim when scopes are configured;
- logout revokes the session server-side and is idempotent;
- Flyway creates the session table, and concurrent `REVOKE_PREVIOUS` opens leave only one session active.
Expand Down Expand Up @@ -139,7 +141,16 @@ Authorization: Bearer <access-token>

Logout returns `204 No Content`. Repeating the request with the same valid token returns `204` again. A valid token alone is not sufficient for future protected-service authorization after its session is revoked; consumers must use the session validation application port until a later gateway/service authorization slice exists.

Errors use RFC 7807 `ProblemDetail`: validation failures are `400` with `type` ending in `validation-error`; invalid credentials are `401` with `type` ending in `authentication-failed`; malformed, missing, expired, or revoked bearer tokens are `401` with `type` ending in `invalid-token`.
### Session validation

```http
GET /api/v1/auth/session
Authorization: Bearer <access-token>
```

An active session returns `200 OK` with `username` and `sessionId`. The endpoint checks the signed JWT and authoritative PostgreSQL session state, so a token from a later `REVOKE_PREVIOUS` login or logout returns the existing RFC 7807 `401` authentication failure. This endpoint is service-local and does not add an API Gateway route.

Errors use RFC 7807 `ProblemDetail`: validation failures are `400` with `type` ending in `validation-error`; invalid credentials and revoked session state during validation are `401` with `type` ending in `authentication-failed`; malformed, missing, or expired bearer tokens are `401` with `type` ending in `invalid-token`.

## Container

Expand Down
9 changes: 9 additions & 0 deletions docs/insomnia/auth-service.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,15 @@ Content-Type: application/json

Expected response: `200 OK` with `accessToken`, `tokenType`, `sessionId`, and `expiresAt`. Copy the returned access token to `auth_access_token` for the logout request. The decoded JWT contains signed `sub`, `sid`, `active`, `iss`, `iat`, and `exp` claims, plus the configured space-delimited `scope` claim when scopes are configured; `active` is `true` when issued and `sid` matches `sessionId`. Current authorization still requires the server-side session to remain active.

## Session validation

```http
GET {{ auth_base_url }}/api/v1/auth/session
Authorization: Bearer {{ auth_access_token }}
```

Expected response: `200 OK` with the authenticated `username` and `sessionId`. Validation checks both the signed token and the authoritative PostgreSQL session state. A token revoked by logout or a later `REVOKE_PREVIOUS` login returns the existing RFC 7807 `401` authentication failure.

## Logout

```http
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import com.digitalbank.authservice.application.port.in.LoginInputPort;
import com.digitalbank.authservice.application.port.in.LogoutCommand;
import com.digitalbank.authservice.application.port.in.LogoutInputPort;
import com.digitalbank.authservice.application.port.in.ValidateSessionCommand;
import com.digitalbank.authservice.application.port.in.ValidateSessionInputPort;
import com.digitalbank.authservice.domain.exception.InvalidTokenException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
Expand All @@ -16,6 +18,7 @@
import org.springframework.http.MediaType;
import org.springframework.http.ProblemDetail;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
Expand All @@ -29,10 +32,15 @@ class AuthController {

private final LoginInputPort loginInputPort;
private final LogoutInputPort logoutInputPort;
private final ValidateSessionInputPort validateSessionInputPort;

AuthController(LoginInputPort loginInputPort, LogoutInputPort logoutInputPort) {
AuthController(
LoginInputPort loginInputPort,
LogoutInputPort logoutInputPort,
ValidateSessionInputPort validateSessionInputPort) {
this.loginInputPort = loginInputPort;
this.logoutInputPort = logoutInputPort;
this.validateSessionInputPort = validateSessionInputPort;
}

@PostMapping(
Expand Down Expand Up @@ -72,11 +80,28 @@ ResponseEntity<LoginResponse> login(@Valid @RequestBody LoginRequest request) {
mediaType = "application/problem+json",
schema = @Schema(implementation = ProblemDetail.class)))
ResponseEntity<Void> logout(@RequestHeader(name = "Authorization", required = false) String authorization) {
logoutInputPort.logout(new LogoutCommand(extractBearerToken(authorization)));
logoutInputPort.logout(new LogoutCommand(bearerToken(authorization)));
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}

private String extractBearerToken(String authorization) {
@GetMapping(value = "/api/v1/auth/session", produces = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Validate the current authentication session")
@SecurityRequirement(name = "bearerAuth")
@ApiResponse(responseCode = "200", description = "Authentication session is active")
@ApiResponse(
responseCode = "401",
description = "Bearer token is missing, invalid, or revoked",
content =
@Content(
mediaType = "application/problem+json",
schema = @Schema(implementation = ProblemDetail.class)))
ResponseEntity<SessionValidationResponse> validateSession(
@RequestHeader(name = "Authorization", required = false) String authorization) {
var result = validateSessionInputPort.validate(new ValidateSessionCommand(bearerToken(authorization)));
return ResponseEntity.ok(SessionValidationResponse.from(result));
}

private String bearerToken(String authorization) {
if (authorization == null
|| !authorization.startsWith(BEARER_PREFIX)
|| authorization.substring(BEARER_PREFIX.length()).isBlank()) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.digitalbank.authservice.adapter.in.web;

import com.digitalbank.authservice.application.port.in.SessionValidationResult;
import java.util.UUID;

record SessionValidationResponse(String username, UUID sessionId) {

static SessionValidationResponse from(SessionValidationResult result) {
return new SessionValidationResponse(
result.username(), result.sessionId().value());
}
}
41 changes: 41 additions & 0 deletions src/test/java/com/digitalbank/authservice/AuthApiIT.java
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,38 @@ void loginReturnsSignedTokenWithSessionId() throws Exception {
.isGreaterThan(payload.path("iat").asLong());
}

@Test
void sessionValidationReturnsActiveSessionAndRejectsRevokedPriorToken() throws Exception {
var firstLogin = postJson(
"/api/v1/auth/login", "{\"username\":\"alice@example.com\",\"password\":\"correct-password\"}");
var firstBody = objectMapper.readTree(firstLogin.body());
var firstToken = firstBody.path("accessToken").asText();

var activeSession = getWithBearer("/api/v1/auth/session", firstToken);
var activeBody = objectMapper.readTree(activeSession.body());

assertThat(activeSession.statusCode()).isEqualTo(200);
assertThat(activeBody.path("username").asText()).isEqualTo("alice@example.com");
assertThat(activeBody.path("sessionId").asText())
.isEqualTo(firstBody.path("sessionId").asText());

var secondLogin = postJson(
"/api/v1/auth/login", "{\"username\":\"alice@example.com\",\"password\":\"correct-password\"}");
var secondToken =
objectMapper.readTree(secondLogin.body()).path("accessToken").asText();

var revokedPriorSession = getWithBearer("/api/v1/auth/session", firstToken);
var currentSession = getWithBearer("/api/v1/auth/session", secondToken);

assertThat(revokedPriorSession.statusCode()).isEqualTo(401);
assertThat(objectMapper
.readTree(revokedPriorSession.body())
.path("type")
.asText())
.isEqualTo("https://digital-bank-java.local/problems/authentication-failed");
assertThat(currentSession.statusCode()).isEqualTo(200);
}

@Test
void unknownAndWrongPasswordReturnSameUnauthorizedProblem() throws Exception {
var unknown = postJson(
Expand Down Expand Up @@ -129,6 +161,15 @@ private HttpResponse<String> postWithBearer(String path, String token) throws Ex
return httpClient.send(request, HttpResponse.BodyHandlers.ofString());
}

private HttpResponse<String> getWithBearer(String path, String token) throws Exception {
var request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:" + port + path))
.header("Authorization", "Bearer " + token)
.GET()
.build();
return httpClient.send(request, HttpResponse.BodyHandlers.ofString());
}

private JsonNode decodeJwtPayload(String token) throws Exception {
var encodedPayload = token.split("\\.", -1)[1];
return objectMapper.readTree(java.util.Base64.getUrlDecoder().decode(encodedPayload));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,12 @@ void openApiEndpointReturnsExplicitMetadata() throws Exception {
.path("responses")
.has("204"))
.isTrue();
assertThat(document.path("paths")
.path("/api/v1/auth/session")
.path("get")
.path("responses")
.has("200"))
.isTrue();
}

private HttpResponse<String> get(String path) throws Exception {
Expand Down
Loading