use of it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException in project SEPA by arces-wot.
the class RegisterHandler method handle.
@Override
public void handle(HttpRequest data, HttpAsyncExchange exchange, HttpContext context) throws HttpException, IOException {
logger.info(">> REGISTRATION");
if (!corsHandling(exchange))
return;
String name = null;
// Accept: application/json
try {
Header[] headers = exchange.getRequest().getHeaders("Content-Type");
if (headers.length == 0) {
logger.error("Content-Type is missing");
HttpUtilities.sendFailureResponse(exchange, new ErrorResponse(HttpStatus.SC_BAD_REQUEST, "content_type_error", "Content-Type is missing"));
return;
}
if (headers.length > 1) {
logger.error("Too many Content-Type headers");
HttpUtilities.sendFailureResponse(exchange, new ErrorResponse(HttpStatus.SC_BAD_REQUEST, "content_type_error", "Too many Content-Type headers"));
return;
}
if (!headers[0].getValue().equals("application/json")) {
logger.error("Content-Type must be: application/json");
HttpUtilities.sendFailureResponse(exchange, new ErrorResponse(HttpStatus.SC_BAD_REQUEST, "content_type_error", "Content-Type must be: application/json"));
return;
}
headers = exchange.getRequest().getHeaders("Accept");
if (headers.length == 0) {
logger.error("Accept is missing");
HttpUtilities.sendFailureResponse(exchange, new ErrorResponse(HttpStatus.SC_BAD_REQUEST, "accept_error", "Accept is missing"));
return;
}
if (headers.length > 1) {
logger.error("Too many Accept headers");
HttpUtilities.sendFailureResponse(exchange, new ErrorResponse(HttpStatus.SC_BAD_REQUEST, "accept_error", "Too many Accept headers"));
return;
}
if (!headers[0].getValue().equals("application/json")) {
logger.error("Accept must be: application/json");
HttpUtilities.sendFailureResponse(exchange, new ErrorResponse(HttpStatus.SC_BAD_REQUEST, "accept_error", "Accept must be: application/json"));
return;
}
} catch (NullPointerException e) {
logger.error(e.getMessage());
HttpUtilities.sendFailureResponse(exchange, new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "NullPointerException", e.getMessage()));
return;
}
/*
* {"register", { "client_identity": "IDENTITY", "grant_types":
* ["client_credentials"] } }
*/
try {
String jsonString = "";
HttpEntity entity = ((HttpEntityEnclosingRequest) exchange.getRequest()).getEntity();
try {
jsonString = EntityUtils.toString(entity, Charset.forName("UTF-8"));
} catch (ParseException e) {
HttpUtilities.sendFailureResponse(exchange, new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "ParseException", e.getMessage()));
return;
}
JsonObject json = new JsonParser().parse(jsonString).getAsJsonObject();
// Client identity
name = json.get("register").getAsJsonObject().get("client_identity").getAsString();
// Client credentials
if (!json.get("register").getAsJsonObject().get("grant_types").getAsJsonArray().contains(new JsonPrimitive("client_credentials"))) {
logger.error("\"grant_types\" must contain \"client_credentials\"");
HttpUtilities.sendFailureResponse(exchange, new ErrorResponse(HttpStatus.SC_BAD_REQUEST, "invalid_grant", "\"grant_types\" must contain \"client_credentials\""));
return;
}
} catch (NullPointerException e) {
logger.error(e.getMessage());
HttpUtilities.sendFailureResponse(exchange, new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "NullPointerException", e.getMessage()));
return;
}
// *****************************************
// Register client and retrieve credentials
// *****************************************
Response cred = null;
try {
cred = Dependability.register(name);
} catch (SEPASecurityException e) {
if (logger.isTraceEnabled())
e.printStackTrace();
logger.error(e.getMessage());
HttpUtilities.sendFailureResponse(exchange, new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "dependability_not_configured", e.getMessage()));
return;
}
if (cred.getClass().equals(ErrorResponse.class)) {
ErrorResponse error = (ErrorResponse) cred;
logger.warn(error.toString());
HttpUtilities.sendFailureResponse(exchange, error);
return;
}
HttpUtilities.sendResponse(exchange, HttpStatus.SC_CREATED, cred.toString());
}
use of it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException in project SEPA by arces-wot.
the class JWTRequestHandler method handleTokenRequest.
private void handleTokenRequest(HttpRequest request, HttpAsyncExchange httpExchange) {
logger.info(">> REQUEST TOKEN");
Header[] headers;
// Parsing and validating request headers
// Content-Type: application/json
// Accept: application/json
headers = request.getHeaders("Content-Type");
if (headers.length == 0) {
logger.error("Content-Type is missing");
HttpUtilities.sendFailureResponse(httpExchange, new ErrorResponse(HttpStatus.SC_BAD_REQUEST, "content_type_error", "Content-Type is missing"));
return;
}
if (headers.length > 1) {
logger.error("Too many Content-Type headers");
HttpUtilities.sendFailureResponse(httpExchange, new ErrorResponse(HttpStatus.SC_BAD_REQUEST, "content_type_error", "Too many Content-Type headers"));
return;
}
if (!headers[0].getValue().equals("application/json")) {
logger.error("Content-Type must be: application/json");
HttpUtilities.sendFailureResponse(httpExchange, new ErrorResponse(HttpStatus.SC_BAD_REQUEST, "content_type_error", "Content-Type must be: application/json"));
return;
}
headers = request.getHeaders("Accept");
if (headers.length == 0) {
logger.error("Accept is missing");
HttpUtilities.sendFailureResponse(httpExchange, new ErrorResponse(HttpStatus.SC_BAD_REQUEST, "accept_error", "Accept is missing"));
return;
}
if (headers.length > 1) {
logger.error("Too many Accept headers");
HttpUtilities.sendFailureResponse(httpExchange, new ErrorResponse(HttpStatus.SC_BAD_REQUEST, "accept_error", "Too many Accept headers"));
return;
}
if (!headers[0].getValue().equals("application/json")) {
logger.error("Accept must be: application/json");
HttpUtilities.sendFailureResponse(httpExchange, new ErrorResponse(HttpStatus.SC_BAD_REQUEST, "accept_error", "Accept must be: application/json"));
return;
}
// Authorization header
headers = request.getHeaders("Authorization");
if (headers.length != 1) {
logger.error("Authorization is missing or multiple");
HttpUtilities.sendFailureResponse(httpExchange, new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, "unauthorized_client", "Authorization is missing or multiple"));
return;
}
// Extract Basic64 authorization
String basic = headers[0].getValue();
if (!basic.startsWith("Basic ")) {
logger.error("Authorization must be \"Basic Basic64(<client_id>:<client_secret>)\"");
HttpUtilities.sendFailureResponse(httpExchange, new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, "unauthorized_client", "Authorization must be \"Basic Basic64(<client_id>:<client_secret>)\""));
return;
}
// *************
// Get token
// *************
Response token = null;
try {
token = Dependability.getToken(basic.split(" ")[1]);
} catch (SEPASecurityException e) {
logger.error(e.getMessage());
if (logger.isTraceEnabled())
e.printStackTrace();
HttpUtilities.sendFailureResponse(httpExchange, new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "dependability_not_configured", e.getMessage()));
return;
}
if (token.getClass().equals(ErrorResponse.class)) {
ErrorResponse error = (ErrorResponse) token;
logger.error(token.toString());
HttpUtilities.sendFailureResponse(httpExchange, error);
} else {
HttpUtilities.sendResponse(httpExchange, HttpStatus.SC_CREATED, token.toString());
}
}
use of it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException in project SEPA by arces-wot.
the class VirtuosoIsql method removeUser.
public void removeUser(String uid) throws SEPASecurityException {
logger.info("removeUser " + uid);
if (new File("command.sql").exists())
new File("command.sql").delete();
try {
PrintWriter f = new PrintWriter(new BufferedWriter(new FileWriter("command.sql")));
f.write("DB.DBA.USER_DROP ('" + uid + "', '" + endpointUsersPassword + "');");
f.close();
isql();
} catch (IOException | InterruptedException e) {
throw new SEPASecurityException(e.getMessage());
}
}
use of it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException in project SEPA by arces-wot.
the class QueryProcessingThread method run.
public void run() {
while (processor.isRunning()) {
ScheduledRequest request;
try {
request = processor.waitQueryRequest();
} catch (InterruptedException e) {
return;
}
InternalQueryRequest query = (InternalQueryRequest) request.getRequest();
Response ret;
try {
ret = processor.processQuery(query);
} catch (SEPASecurityException | IOException e) {
logger.error(e.getMessage());
if (logger.isTraceEnabled())
e.printStackTrace();
ret = new ErrorResponse(401, "SEPASecurityException", e.getMessage());
}
processor.addResponse(request.getToken(), ret);
}
}
use of it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException in project SEPA by arces-wot.
the class KeycloakAuthenticationService method registerClient.
/**
* Client Registration Request
*
*curl --location --request POST 'https://sepa.vaimee.it:8443/auth/realms/MONAS/clients-registrations/default' \
*--header 'Content-Type: application/json' \
*--header 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICI4Y2E2ZGNiNC1jZmY5LTQzNGUtODNhNi05NTk4MzQ1NjUxZGMifQ.eyJleHAiOjAsImlhdCI6MTU5OTgwNTYzMywianRpIjoiMzNkZjRjZDYtMjJkZC00M2UxLWFmMzItYWE3NTMwMmJmZGUzIiwiaXNzIjoiaHR0cHM6Ly9zZXBhLnZhaW1lZS5pdDo4NDQzL2F1dGgvcmVhbG1zL01PTkFTIiwiYXVkIjoiaHR0cHM6Ly9zZXBhLnZhaW1lZS5pdDo4NDQzL2F1dGgvcmVhbG1zL01PTkFTIiwidHlwIjoiSW5pdGlhbEFjY2Vzc1Rva2VuIn0.edceIxjn2Fdc3NzXYIu--lWbDVBF0YXQfrUJ1R94myc' \
*--data-raw '{"clientId":"sepatest_client","standardFlowEnabled" : false, "implicitFlowEnabled" : false, "authorizationServicesEnabled":true,"directAccessGrantsEnabled" : false, "serviceAccountsEnabled" : true, "publicClient":false, "protocol":"openid-connect","protocolMappers":[{"name":"hardcoded_username","protocol":"openid-connect","protocolMapper" : "oidc-hardcoded-claim-mapper","config" : {"claim.value":"sepatest","userinfo.token.claim":"false","id.token.claim":"false","access.token.claim":"true","claim.name":"preferred_username","jsonType.label":"String"}}]}'
*/
@Override
public Response registerClient(String client_id, String username, String initialAccessToken, int timeout) throws SEPASecurityException {
if (client_id == null)
throw new SEPASecurityException("client_id is null");
logger.log(Level.getLevel("oauth"), "REGISTER " + client_id);
CloseableHttpResponse response = null;
long start = Timings.getTime();
try {
URI uri = new URI(oauthProperties.getRegisterUrl());
// 1) Register client
HttpPost httpRequest = new HttpPost(uri);
httpRequest.setHeader("Content-Type", "application/json");
httpRequest.setHeader("Authorization", "bearer " + initialAccessToken);
// oidc_hardcoded_claim_mapper for username link
JsonObject usernameClaim = new JsonObject();
usernameClaim.add("claim.value", new JsonPrimitive(username));
usernameClaim.add("claim.name", new JsonPrimitive("username"));
usernameClaim.add("userinfo.token.claim", new JsonPrimitive(false));
usernameClaim.add("id.token.claim", new JsonPrimitive(false));
usernameClaim.add("access.token.claim", new JsonPrimitive(true));
usernameClaim.add("jsonType.label", new JsonPrimitive("String"));
JsonArray protocolMappers = new JsonArray();
JsonObject oidc_hardcoded_claim_mapper = new JsonObject();
oidc_hardcoded_claim_mapper.add("name", new JsonPrimitive("hardcoded_username"));
oidc_hardcoded_claim_mapper.add("protocol", new JsonPrimitive("openid-connect"));
oidc_hardcoded_claim_mapper.add("protocolMapper", new JsonPrimitive("oidc-hardcoded-claim-mapper"));
oidc_hardcoded_claim_mapper.add("config", usernameClaim);
protocolMappers.add(oidc_hardcoded_claim_mapper);
JsonObject jsonBody = new JsonObject();
jsonBody.add("clientId", new JsonPrimitive(client_id));
jsonBody.add("standardFlowEnabled", new JsonPrimitive(false));
jsonBody.add("implicitFlowEnabled", new JsonPrimitive(false));
jsonBody.add("directAccessGrantsEnabled", new JsonPrimitive(false));
jsonBody.add("serviceAccountsEnabled", new JsonPrimitive(true));
jsonBody.add("authorizationServicesEnabled", new JsonPrimitive(false));
jsonBody.add("publicClient", new JsonPrimitive(false));
jsonBody.add("protocol", new JsonPrimitive("openid-connect"));
jsonBody.add("protocolMappers", protocolMappers);
StringEntity body = new StringEntity(jsonBody.toString());
httpRequest.setEntity(body);
// Set timeout
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build();
httpRequest.setConfig(requestConfig);
logger.log(Level.getLevel("oauth"), "Request: " + httpRequest);
try {
response = httpClient.execute(httpRequest);
} catch (IOException e) {
logger.error("HTTP EXECUTE: " + e.getMessage());
return new ErrorResponse(HttpStatus.SC_SERVICE_UNAVAILABLE, "HttpExecute", e.getMessage());
}
logger.log(Level.getLevel("oauth"), "Response: " + response);
HttpEntity entity = response.getEntity();
String jsonResponse = EntityUtils.toString(entity, Charset.forName("UTF-8"));
EntityUtils.consume(entity);
JsonObject json = new JsonParser().parse(jsonResponse).getAsJsonObject();
if (json.has("error")) {
// int code = json.get("status_code").getAsInt();
String error = json.get("error").getAsString();
String description = json.get("error_description").getAsString();
ErrorResponse ret = new ErrorResponse(response.getStatusLine().getStatusCode(), error, description);
logger.error(ret);
return ret;
}
return new RegistrationResponse(client_id, json.get("secret").getAsString(), json);
} catch (URISyntaxException e) {
logger.error(e.getMessage());
Timings.log("REGISTER_ERROR", start, Timings.getTime());
return new ErrorResponse(HttpStatus.SC_BAD_REQUEST, "URISyntaxException", e.getMessage());
} catch (UnsupportedEncodingException e) {
logger.error(e.getMessage());
Timings.log("REGISTER_ERROR", start, Timings.getTime());
return new ErrorResponse(HttpStatus.SC_BAD_REQUEST, "UnsupportedEncodingException", e.getMessage());
} catch (ParseException e) {
logger.error(e.getMessage());
Timings.log("REGISTER_ERROR", start, Timings.getTime());
return new ErrorResponse(HttpStatus.SC_BAD_REQUEST, "ParseException", e.getMessage());
} catch (IOException e) {
logger.error(e.getMessage());
Timings.log("REGISTER_ERROR", start, Timings.getTime());
return new ErrorResponse(HttpStatus.SC_SERVICE_UNAVAILABLE, "IOException", e.getMessage());
} finally {
try {
if (response != null)
response.close();
} catch (IOException e) {
logger.error(e.getMessage());
Timings.log("REGISTER_ERROR", start, Timings.getTime());
return new ErrorResponse(HttpStatus.SC_SERVICE_UNAVAILABLE, "IOException", e.getMessage());
}
}
}
Aggregations