Enhanced OAuth2 API Tester tool, updated validation and improved CORS configuration:

- Improved OAuth2 Tester UI/UX: added support for multiple HTTP methods, query parameters, request body validation, collapsible result sections, and dynamic input handling.
- Enhanced `UserController` with validation annotations for `UserDTO` in API requests.
- Updated `UserDTO` to include stricter validation constraints (`@NotNull`, `@NotBlank`, `@Email`).
- Adjusted CORS configuration to allow all origins for OAuth endpoints.
This commit is contained in:
Jan 2025-10-28 18:01:21 +01:00
parent 42913045b3
commit d840b05da2
4 changed files with 323 additions and 79 deletions

View file

@ -67,7 +67,7 @@ public class CorsConfig implements WebMvcConfigurer {
// OAuth endpoints // OAuth endpoints
registry.addMapping("/oauth/**") registry.addMapping("/oauth/**")
.allowedOriginPatterns(allowedCors) .allowedOriginPatterns("*")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*") .allowedHeaders("*")
.allowCredentials(true); .allowCredentials(true);

View file

@ -4,6 +4,7 @@ package de.avatic.lcc.controller.users;
import de.avatic.lcc.dto.users.UserDTO; import de.avatic.lcc.dto.users.UserDTO;
import de.avatic.lcc.repositories.pagination.SearchQueryResult; import de.avatic.lcc.repositories.pagination.SearchQueryResult;
import de.avatic.lcc.service.users.UserService; import de.avatic.lcc.service.users.UserService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Min; import jakarta.validation.constraints.Min;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
@ -60,7 +61,7 @@ public class UserController {
*/ */
@PutMapping({"/", ""}) @PutMapping({"/", ""})
@PreAuthorize("hasRole('RIGHT-MANAGEMENT')") @PreAuthorize("hasRole('RIGHT-MANAGEMENT')")
public ResponseEntity<Void> updateUser(@RequestParam UserDTO user) { public ResponseEntity<Void> updateUser(@Valid @RequestBody UserDTO user) {
userService.updateUser(user); userService.updateUser(user);
return ResponseEntity.ok().build(); return ResponseEntity.ok().build();
} }

View file

@ -2,28 +2,36 @@ package de.avatic.lcc.dto.users;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.Valid;
import jakarta.validation.constraints.*;
import java.util.List; import java.util.List;
public class UserDTO { public class UserDTO {
@NotNull
@JsonProperty("firstname") @JsonProperty("firstname")
private String firstName; private String firstName;
@NotNull
@JsonProperty("lastname") @JsonProperty("lastname")
private String lastName; private String lastName;
@Email
@JsonProperty("mail") @JsonProperty("mail")
private String email; private String email;
@NotNull
@JsonProperty("workday_id") @JsonProperty("workday_id")
private String workdayId; private String workdayId;
@JsonProperty("is_active") @JsonProperty("is_active")
private boolean isActive; private boolean isActive;
@NotNull
@Size(min = 1)
@JsonProperty("groups") @JsonProperty("groups")
private List<String> groups; private List<@NotBlank String> groups;
public String getFirstName() { public String getFirstName() {
return firstName; return firstName;

View file

@ -57,7 +57,7 @@
font-size: 14px; font-size: 14px;
} }
input { input, textarea {
width: 100%; width: 100%;
padding: 12px; padding: 12px;
border: 2px solid #e0e0e0; border: 2px solid #e0e0e0;
@ -67,6 +67,12 @@
transition: border-color 0.3s; transition: border-color 0.3s;
} }
textarea {
min-height: 100px;
resize: vertical;
font-family: 'Courier New', monospace;
}
select { select {
width: 100%; width: 100%;
padding: 12px; padding: 12px;
@ -80,11 +86,23 @@
} }
input:focus, input:focus,
select:focus { select:focus,
textarea:focus {
outline: none; outline: none;
border-color: #667eea; border-color: #667eea;
} }
.method-selector {
display: grid;
grid-template-columns: 120px 1fr;
gap: 10px;
align-items: start;
}
.method-select {
width: 100%;
}
button { button {
width: 100%; width: 100%;
padding: 14px; padding: 14px;
@ -158,7 +176,7 @@
.result-box { .result-box {
background: #f8f9fa; background: #f8f9fa;
border: 1px solid #e0e0e0; border: none;
border-radius: 6px; border-radius: 6px;
padding: 15px; padding: 15px;
max-height: 400px; max-height: 400px;
@ -175,14 +193,14 @@
} }
.error { .error {
color: #d32f2f; color: #333;
background: #ffebee; background-color: #f8f9fa;
border-color: #ef9a9a; border-color: #BC2B72;
} }
.success { .success {
color: #388e3c; color: #333;
background: #e8f5e9; background-color: #f8f9fa;
border-color: #81c784; border-color: #81c784;
} }
@ -222,8 +240,8 @@
} }
.status-error { .status-error {
background: #ffebee; background-color: #BC2B72;
color: #d32f2f; color: #ffffff;
} }
.error-summary { .error-summary {
@ -240,83 +258,195 @@
} }
.error-summary strong { .error-summary strong {
color: #002F54;
font-weight: 600; font-weight: 600;
} }
.details-button { .details-button {
width: 100%; display: none;
}
.result-box-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px; padding: 10px;
background: #e9ecef;
border-radius: 6px 6px 0 0;
cursor: pointer;
user-select: none;
margin: -15px -15px 10px -15px;
}
.result-box-header:hover {
background: #dee2e6;
}
.result-box-title {
font-weight: 500;
color: #333;
font-size: 14px;
}
.toggle-icon {
font-size: 18px;
color: #666;
transition: transform 0.3s;
}
.toggle-icon.collapsed {
transform: rotate(-90deg);
}
.section-divider {
border-top: 2px solid #e0e0e0;
margin: 30px 0;
}
.section-title {
font-size: 18px;
color: #333;
margin-bottom: 15px;
font-weight: 600;
}
.params-section {
background: #f8f9fa;
padding: 15px;
border-radius: 6px;
margin-bottom: 20px;
}
.param-row {
display: grid;
grid-template-columns: 1fr 1fr auto;
gap: 10px;
margin-bottom: 10px;
}
.param-input {
padding: 8px;
border: 1px solid #e0e0e0;
border-radius: 4px;
font-size: 13px;
}
.param-remove {
padding: 8px 12px;
background-color: #BC2B72;
color: #ffffff;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 13px;
}
.param-remove:hover {
background-color: #a02460;
}
.param-add {
padding: 8px 16px;
background-color: #002F54; background-color: #002F54;
color: #ffffff; color: #ffffff;
border: none; border: none;
border-radius: 6px; border-radius: 4px;
font-size: 14px;
font-weight: 500;
font-family: 'Poppins', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
cursor: pointer; cursor: pointer;
margin-bottom: 15px; font-size: 13px;
transition: opacity 0.3s; font-family: 'Poppins', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
width: auto;
margin-top: 5px;
} }
.details-button:hover { .param-add:hover {
opacity: 0.8; background-color: #001a30;
}
.body-section {
display: none;
}
.body-section.active {
display: block;
}
.helper-text {
font-size: 12px;
color: #666;
margin-top: 5px;
} }
</style> </style>
</head> </head>
<body> <body>
<div class="container"> <div class="container">
<h1>OAuth2 API Tester</h1> <h1>OAuth2 API Tester</h1>
<p class="subtitle">Teste deine OAuth2 Client Credentials API-Integration</p> <p class="subtitle">Testen Sie APIs mit OAuth2-Authentifizierung</p>
<div class="info-section"> <div class="info-section">
<h3>Hinweis</h3> <h3>Funktionen:</h3>
<p>Diese Anwendung verwendet den OAuth2 Client Credentials Flow. Stelle sicher, dass deine API diesen Flow unterstützt und CORS für diese Domain aktiviert ist.</p> <p>
• Unterstützt alle HTTP-Methoden (GET, POST, PUT, DELETE, PATCH)<br>
• Query-Parameter für alle Methoden<br>
• Request-Body für POST, PUT und PATCH<br>
• OAuth2 Client Credentials Flow
</p>
</div> </div>
<form id="testForm"> <form id="testForm">
<!-- OAuth2 Konfiguration -->
<div class="section-title">OAuth2 Konfiguration</div>
<div class="form-group"> <div class="form-group">
<label for="tokenUrl">Token URL (OAuth2 Endpoint)</label> <label for="tokenUrl">Token-URL</label>
<input <input type="url" id="tokenUrl" required placeholder="z.B. https://api.example.com/oauth/token">
type="url"
id="tokenUrl"
placeholder="https://deine-app.de/oauth/token"
required
>
</div> </div>
<div class="form-group"> <div class="form-group">
<label for="clientId">Client ID</label> <label for="clientId">Client ID</label>
<input <input type="text" id="clientId" required placeholder="Ihre Client ID">
type="text"
id="clientId"
placeholder="deine-client-id"
required
>
</div> </div>
<div class="form-group"> <div class="form-group">
<label for="clientSecret">Client Secret</label> <label for="clientSecret">Client Secret</label>
<input <input type="text" id="clientSecret" required placeholder="Ihr Client Secret">
type="text"
id="clientSecret"
placeholder="dein-client-secret"
required
>
</div> </div>
<div class="section-divider"></div>
<!-- API Request Konfiguration -->
<div class="section-title">API Request Konfiguration</div>
<div class="form-group"> <div class="form-group">
<label for="apiUrl">API Endpoint URL (zu testende Ressource)</label> <label for="httpMethod">HTTP-Methode und Endpoint</label>
<input <div class="method-selector">
type="url" <select id="httpMethod" class="method-select">
id="apiUrl" <option value="GET">GET</option>
placeholder="https://deine-app.de/api/resource" <option value="POST">POST</option>
required <option value="PUT">PUT</option>
> <option value="DELETE">DELETE</option>
<option value="PATCH">PATCH</option>
</select>
<input type="url" id="apiUrl" required placeholder="z.B. https://api.example.com/v1/resource">
</div>
</div>
<!-- Query-Parameter -->
<div class="form-group">
<label>Query-Parameter (optional)</label>
<div class="params-section">
<div id="queryParams"></div>
<button type="button" class="param-add" onclick="addQueryParam()">+ Parameter hinzufügen</button>
</div>
</div>
<!-- Request Body (nur für POST, PUT, PATCH) -->
<div class="form-group body-section" id="bodySection">
<label for="requestBody">Request-Body (JSON)</label>
<textarea id="requestBody" placeholder='z.B. {"key": "value", "number": 123}'></textarea>
<div class="helper-text">Geben Sie valides JSON ein</div>
</div> </div>
<button type="submit" id="submitBtn"> <button type="submit" id="submitBtn">
API Zugriff Testen API testen
</button> </button>
</form> </form>
@ -333,8 +463,11 @@
</div> </div>
</div> </div>
<div id="errorSummary" class="error-summary"></div> <div id="errorSummary" class="error-summary"></div>
<button id="detailsButton" class="details-button" style="display: none;"></button>
<div class="result-box" id="resultBox"> <div class="result-box" id="resultBox">
<div class="result-box-header" id="toggleHeader" style="display: none;">
<span class="result-box-title">Details anzeigen</span>
<span class="toggle-icon" id="toggleIcon"></span>
</div>
<pre id="resultContent"></pre> <pre id="resultContent"></pre>
</div> </div>
</div> </div>
@ -342,14 +475,100 @@
<script> <script>
let accessToken = null; let accessToken = null;
let queryParamCount = 0;
// HTTP-Methode Änderung Handler
document.getElementById('httpMethod').addEventListener('change', function() {
const method = this.value;
const bodySection = document.getElementById('bodySection');
// Zeige Body-Section nur für POST, PUT, PATCH
if (method === 'POST' || method === 'PUT' || method === 'PATCH') {
bodySection.classList.add('active');
} else {
bodySection.classList.remove('active');
}
});
// Query-Parameter Funktionen
function addQueryParam() {
const container = document.getElementById('queryParams');
const row = document.createElement('div');
row.className = 'param-row';
row.id = `param-${queryParamCount}`;
row.innerHTML = `
<input type="text" class="param-input" placeholder="Parameter-Name" data-param-key="${queryParamCount}">
<input type="text" class="param-input" placeholder="Wert" data-param-value="${queryParamCount}">
<button type="button" class="param-remove" onclick="removeQueryParam(${queryParamCount})">×</button>
`;
container.appendChild(row);
queryParamCount++;
}
function removeQueryParam(id) {
const row = document.getElementById(`param-${id}`);
if (row) {
row.remove();
}
}
function getQueryParams() {
const params = {};
const keys = document.querySelectorAll('[data-param-key]');
const values = document.querySelectorAll('[data-param-value]');
keys.forEach((keyInput, index) => {
const key = keyInput.value.trim();
const value = values[index].value.trim();
if (key) {
params[key] = value;
}
});
return params;
}
function buildUrlWithParams(baseUrl, params) {
if (Object.keys(params).length === 0) {
return baseUrl;
}
const url = new URL(baseUrl);
Object.entries(params).forEach(([key, value]) => {
url.searchParams.append(key, value);
});
return url.toString();
}
// Form Submit Handler
document.getElementById('testForm').addEventListener('submit', async (e) => { document.getElementById('testForm').addEventListener('submit', async (e) => {
e.preventDefault(); e.preventDefault();
const tokenUrl = document.getElementById('tokenUrl').value; const tokenUrl = document.getElementById('tokenUrl').value;
const clientId = document.getElementById('clientId').value; const clientId = document.getElementById('clientId').value;
const clientSecret = document.getElementById('clientSecret').value; const clientSecret = document.getElementById('clientSecret').value;
const apiUrl = document.getElementById('apiUrl').value; const httpMethod = document.getElementById('httpMethod').value;
const baseApiUrl = document.getElementById('apiUrl').value;
const queryParams = getQueryParams();
const apiUrl = buildUrlWithParams(baseApiUrl, queryParams);
let requestBody = null;
if (httpMethod === 'POST' || httpMethod === 'PUT' || httpMethod === 'PATCH') {
const bodyText = document.getElementById('requestBody').value.trim();
if (bodyText) {
try {
requestBody = JSON.parse(bodyText);
} catch (e) {
displayResult({
phase: 'validation',
message: 'Ungültiger Request-Body',
error: 'Der Request-Body muss valides JSON sein: ' + e.message
}, false);
return;
}
}
}
// UI Updates // UI Updates
document.getElementById('loading').classList.add('active'); document.getElementById('loading').classList.add('active');
@ -373,7 +592,7 @@
accessToken = tokenResponse.access_token; accessToken = tokenResponse.access_token;
// Schritt 2: API Endpoint aufrufen // Schritt 2: API Endpoint aufrufen
const apiResponse = await callApi(apiUrl, accessToken); const apiResponse = await callApi(apiUrl, accessToken, httpMethod, requestBody);
if (!apiResponse.success) { if (!apiResponse.success) {
displayResult({ displayResult({
@ -452,15 +671,25 @@
} }
} }
async function callApi(apiUrl, token) { async function callApi(apiUrl, token, method = 'GET', body = null) {
try { try {
const response = await fetch(apiUrl, { const headers = {
method: 'GET', 'Authorization': `Bearer ${token}`,
headers: { 'Accept': 'application/json'
'Authorization': `Bearer ${token}`, };
'Accept': 'application/json'
} const options = {
}); method: method,
headers: headers
};
// Body nur für POST, PUT, PATCH hinzufügen
if (body && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {
headers['Content-Type'] = 'application/json';
options.body = JSON.stringify(body);
}
const response = await fetch(apiUrl, options);
const contentType = response.headers.get('content-type'); const contentType = response.headers.get('content-type');
let data; let data;
@ -507,7 +736,9 @@
statusBadge.className = 'status-badge status-success'; statusBadge.className = 'status-badge status-success';
errorSummary.style.display = 'none'; errorSummary.style.display = 'none';
detailsButton.style.display = 'none';
// Verstecke Toggle-Header bei Erfolg
document.getElementById('toggleHeader').style.display = 'none';
// Stelle sicher, dass resultBox und resultContent sichtbar sind // Stelle sicher, dass resultBox und resultContent sichtbar sind
resultBox.style.display = 'block'; resultBox.style.display = 'block';
@ -527,33 +758,37 @@
} else if (result.phase === 'api') { } else if (result.phase === 'api') {
phaseText = 'API-Aufruf'; phaseText = 'API-Aufruf';
statusBadge.textContent = 'Fehler beim API-Aufruf'; statusBadge.textContent = 'Fehler beim API-Aufruf';
} else if (result.phase === 'validation') {
phaseText = 'Validierung';
statusBadge.textContent = 'Validierungsfehler';
} else { } else {
phaseText = 'Unbekannt'; phaseText = 'Unbekannt';
statusBadge.textContent = 'Fehler'; statusBadge.textContent = 'Fehler';
} }
statusBadge.className = 'status-badge status-error'; statusBadge.className = 'status-badge status-error';
// Zeige Fehler-Zusammenfassung // Verstecke Fehler-Zusammenfassung
errorSummary.style.display = 'block'; errorSummary.style.display = 'none';
errorSummary.innerHTML = `
<strong>Phase:</strong> ${phaseText}<br>
<strong>Fehler:</strong> ${result.message || 'Unbekannter Fehler'}<br>
<strong>Details:</strong> ${result.error || 'Keine Details verfügbar'}
`;
// Details-Button // Zeige Toggle-Header
resultBox.style.display = 'block'; const toggleHeader = document.getElementById('toggleHeader');
detailsButton.style.display = 'block'; const toggleIcon = document.getElementById('toggleIcon');
detailsButton.onclick = function() { toggleHeader.style.display = 'flex';
// Toggle-Funktion
toggleHeader.onclick = function() {
const isHidden = resultContent.style.display === 'none'; const isHidden = resultContent.style.display === 'none';
resultContent.style.display = isHidden ? 'block' : 'none'; resultContent.style.display = isHidden ? 'block' : 'none';
detailsButton.textContent = isHidden ? 'Details verbergen' : 'Vollständige Details anzeigen'; toggleIcon.classList.toggle('collapsed');
toggleHeader.querySelector('.result-box-title').textContent =
isHidden ? 'Details verbergen' : 'Details anzeigen';
}; };
// Verstecke Details initial // Verstecke Details initial
resultBox.style.display = 'block';
resultContent.style.display = 'none'; resultContent.style.display = 'none';
resultContent.textContent = JSON.stringify(result, null, 2); resultContent.textContent = JSON.stringify(result, null, 2);
detailsButton.textContent = 'Vollständige Details anzeigen'; toggleIcon.classList.add('collapsed');
} }
} }
</script> </script>