60 lines
2.1 KiB
Java
60 lines
2.1 KiB
Java
package com.example.keycloakpattern;
|
|
|
|
import java.nio.charset.StandardCharsets;
|
|
import java.security.MessageDigest;
|
|
import java.util.LinkedHashMap;
|
|
import java.util.Map;
|
|
|
|
import jakarta.servlet.http.HttpServletRequest;
|
|
|
|
import org.springframework.http.ResponseEntity;
|
|
import org.springframework.beans.factory.annotation.Value;
|
|
import org.springframework.web.bind.annotation.GetMapping;
|
|
import org.springframework.web.bind.annotation.RestController;
|
|
|
|
@RestController
|
|
public class EdgeIdentityController {
|
|
|
|
private final byte[] internalAuthToken;
|
|
|
|
EdgeIdentityController(@Value("${edge.internal-auth-token}") String internalAuthToken) {
|
|
if (!hasText(internalAuthToken)) {
|
|
throw new IllegalStateException("edge.internal-auth-token must be configured");
|
|
}
|
|
this.internalAuthToken = internalAuthToken.getBytes(StandardCharsets.UTF_8);
|
|
}
|
|
|
|
@GetMapping("/edge/me")
|
|
ResponseEntity<Map<String, Object>> currentUser(HttpServletRequest request) {
|
|
String authRequestUser = request.getHeader("X-Auth-Request-User");
|
|
if (!hasText(authRequestUser) || !hasValidInternalToken(request)) {
|
|
return ResponseEntity.status(401).body(Map.of(
|
|
"error",
|
|
"trusted edge authentication is required"
|
|
));
|
|
}
|
|
|
|
Map<String, Object> response = new LinkedHashMap<>();
|
|
response.put("pattern", "AP4-edge-forward-auth");
|
|
response.put("user", authRequestUser);
|
|
response.put("email", request.getHeader("X-Auth-Request-Email"));
|
|
response.put("identityHeader", "X-Auth-Request-User");
|
|
return ResponseEntity.ok(response);
|
|
}
|
|
|
|
private boolean hasValidInternalToken(HttpServletRequest request) {
|
|
String suppliedToken = request.getHeader("X-Internal-Auth-Token");
|
|
if (!hasText(suppliedToken)) {
|
|
return false;
|
|
}
|
|
return MessageDigest.isEqual(
|
|
internalAuthToken,
|
|
suppliedToken.getBytes(StandardCharsets.UTF_8)
|
|
);
|
|
}
|
|
|
|
private static boolean hasText(String value) {
|
|
return value != null && !value.isBlank();
|
|
}
|
|
}
|