Update client authorization

This commit is contained in:
2025-12-04 22:11:20 +01:00
parent 6e07688d8b
commit 46b5e6d1e2
2 changed files with 15 additions and 13 deletions

View File

@@ -1,9 +1,6 @@
package httpsServer.httpServer.src.authorization;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.*;
public class AuthorizedClients {
@@ -32,4 +29,7 @@ public class AuthorizedClients {
return clients.contains(client);
}
public boolean isAuthorized(String username, String password) {
return clients.contains(new Client(username, password));
}
}

View File

@@ -16,6 +16,7 @@ import java.io.InputStreamReader;
import java.lang.reflect.*;
import java.nio.Buffer;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class RequestInterceptor implements InvocationHandler {
@@ -36,8 +37,7 @@ public class RequestInterceptor implements InvocationHandler {
Method realMethod = target.getClass().getMethod(method.getName(), method.getParameterTypes());
checkAuthorizedVerb(realMethod, exchange.getRequestMethod());
//String a = exchange.getRequestHeaders().getFirst("Header-Name");
checkAuthorizedClient(realMethod, exchange.getRequestBody());
checkAuthorizedClient(realMethod, exchange.getRequestHeaders().getFirst("Authorization"));
return method.invoke(target, args);
@@ -64,18 +64,20 @@ public class RequestInterceptor implements InvocationHandler {
}
}
private void checkAuthorizedClient(Method method, InputStream data) throws ClientAuthorisationException {
private void checkAuthorizedClient(Method method, String authHeader) throws ClientAuthorisationException {
if (!method.isAnnotationPresent(OnlyAuthorizedClients.class)) return;
Client client = null;
try(BufferedReader reader = new BufferedReader(new InputStreamReader(data, StandardCharsets.UTF_8))){
String body = reader.lines().reduce("", (acc, line) -> acc + line + "\n");
client = mapper.readValue(body, Client.class);
} catch (IOException e){
if(authHeader == null || !authHeader.startsWith("Basic ")) {
throw new ClientAuthorisationException("Unable to read body");
}
if(!authorizedClients.isAuthorized(client)){
String base64Credentials = authHeader.substring("Basic ".length());
String credentials = new String(Base64.getDecoder().decode(base64Credentials));
String[] values = credentials.split(":", 1);
String username = values[0];
String password = values[1];
if(!authorizedClients.isAuthorized(username, password)){
throw new ClientAuthorisationException("Client not authorized");
}
}