use of it.unibo.arces.wot.sepa.commons.response.Response in project SEPA by arces-wot.
the class JWTRequestHandler method handle.
@Override
public void handle(HttpRequest request, HttpAsyncExchange httpExchange, HttpContext context) throws HttpException, IOException {
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, HttpStatus.SC_BAD_REQUEST, "Content-Type is missing");
}
if (headers.length > 1) {
logger.error("Too many Content-Type headers");
HttpUtilities.sendFailureResponse(httpExchange, HttpStatus.SC_BAD_REQUEST, "Too many Content-Type headers");
}
if (!headers[0].getValue().equals("application/json")) {
logger.error("Content-Type must be: application/json");
HttpUtilities.sendFailureResponse(httpExchange, HttpStatus.SC_BAD_REQUEST, "Content-Type must be: application/json");
}
headers = request.getHeaders("Accept");
if (headers.length == 0) {
logger.error("Accept is missing");
HttpUtilities.sendFailureResponse(httpExchange, HttpStatus.SC_BAD_REQUEST, "Accept is missing");
}
if (headers.length > 1) {
logger.error("Too many Accept headers");
HttpUtilities.sendFailureResponse(httpExchange, HttpStatus.SC_BAD_REQUEST, "Too many Accept headers");
}
if (!headers[0].getValue().equals("application/json")) {
logger.error("Accept must be: application/json");
HttpUtilities.sendFailureResponse(httpExchange, HttpStatus.SC_BAD_REQUEST, "Accept must be: application/json");
}
// Authorization header
headers = request.getHeaders("Authorization");
if (headers.length != 1) {
logger.error("Authorization is missing or multiple");
HttpUtilities.sendFailureResponse(httpExchange, 401, "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, 401, "Authorization must be \"Basic Basic64(<client_id>:<client_secret>)\"");
return;
}
// *************
// Get token
// *************
Response token = am.getToken(basic.split(" ")[1]);
if (token.getClass().equals(ErrorResponse.class)) {
ErrorResponse error = (ErrorResponse) token;
logger.error(token.toString());
HttpUtilities.sendFailureResponse(httpExchange, error.getErrorCode(), error.getErrorMessage());
} else {
HttpUtilities.sendResponse(httpExchange, HttpStatus.SC_CREATED, token.toString());
}
}
use of it.unibo.arces.wot.sepa.commons.response.Response 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");
String name = null;
try {
Header[] headers;
// Parsing and validating request headers
// Content-Type: application/json
// Accept: application/json
headers = exchange.getRequest().getHeaders("Content-Type");
if (headers.length == 0) {
logger.error("Content-Type is missing");
HttpUtilities.sendFailureResponse(exchange, HttpStatus.SC_BAD_REQUEST, "Content-Type is missing");
}
if (headers.length > 1) {
logger.error("Too many Content-Type headers");
HttpUtilities.sendFailureResponse(exchange, HttpStatus.SC_BAD_REQUEST, "Too many Content-Type headers");
}
if (!headers[0].getValue().equals("application/json")) {
logger.error("Content-Type must be: application/json");
HttpUtilities.sendFailureResponse(exchange, HttpStatus.SC_BAD_REQUEST, "Content-Type must be: application/json");
}
headers = exchange.getRequest().getHeaders("Accept");
if (headers.length == 0) {
logger.error("Accept is missing");
HttpUtilities.sendFailureResponse(exchange, HttpStatus.SC_BAD_REQUEST, "Accept is missing");
}
if (headers.length > 1) {
logger.error("Too many Accept headers");
HttpUtilities.sendFailureResponse(exchange, HttpStatus.SC_BAD_REQUEST, "Too many Accept headers");
}
if (!headers[0].getValue().equals("application/json")) {
logger.error("Accept must be: application/json");
HttpUtilities.sendFailureResponse(exchange, HttpStatus.SC_BAD_REQUEST, "Accept must be: application/json");
}
// Parsing and validating request body
/*
* { "client_identity": "IDENTITY", "grant_types":
* ["client_credentials"] }
*/
String jsonString = "";
HttpEntity entity = ((HttpEntityEnclosingRequest) exchange.getRequest()).getEntity();
try {
jsonString = EntityUtils.toString(entity, Charset.forName("UTF-8"));
} catch (ParseException | IOException e) {
jsonString = e.getLocalizedMessage();
}
JsonObject json = new JsonParser().parse(jsonString).getAsJsonObject();
JsonArray credentials = json.get("grant_types").getAsJsonArray();
boolean found = false;
for (JsonElement elem : credentials) {
if (elem.getAsString() != null)
if (elem.getAsString().equals("client_credentials")) {
found = true;
break;
}
}
if (!found) {
logger.error("\"grant_types\" must contain \"client_credentials\"");
HttpUtilities.sendFailureResponse(exchange, HttpStatus.SC_BAD_REQUEST, "\"grant_types\" must contain \"client_credentials\"");
return;
}
name = json.get("client_identity").getAsString();
} catch (NullPointerException e) {
logger.error(e.getMessage());
HttpUtilities.sendFailureResponse(exchange, HttpStatus.SC_BAD_REQUEST, e.getMessage());
return;
}
// *****************************************
// Register client and retrieve credentials
// *****************************************
Response cred = am.register(name);
if (cred.getClass().equals(ErrorResponse.class)) {
ErrorResponse error = (ErrorResponse) cred;
logger.error(error.toString());
HttpUtilities.sendFailureResponse(exchange, error.getErrorCode(), error.getErrorMessage());
return;
}
HttpUtilities.sendResponse(exchange, HttpStatus.SC_CREATED, cred.toString());
}
use of it.unibo.arces.wot.sepa.commons.response.Response in project SEPA by arces-wot.
the class MQTTSmartifier method start.
public boolean start(boolean simulate) {
// Subscribe to observation-topic mapping
Response ret = subscribe(null);
if (ret.isError()) {
logger.fatal("Failed to subscribe: " + ret);
return false;
}
SubscribeResponse results = (SubscribeResponse) ret;
onAddedResults(results.getBindingsResults());
if (simulate)
simulator();
else {
// MQTT: begin
JsonObject mqtt = getApplicationProfile().getExtendedData().get("mqtt").getAsJsonObject();
String url = mqtt.get("url").getAsString();
int port = mqtt.get("port").getAsInt();
JsonArray topics = mqtt.get("topics").getAsJsonArray();
topicsFilter = new String[topics.size()];
int i = 0;
for (JsonElement topic : topics) {
topicsFilter[i] = topic.getAsString();
i++;
}
boolean sslEnabled = false;
if (mqtt.get("ssl") != null)
sslEnabled = mqtt.get("ssl").getAsBoolean();
String serverURI = null;
if (sslEnabled) {
serverURI = "ssl://" + url + ":" + String.format("%d", port);
} else {
serverURI = "tcp://" + url + ":" + String.format("%d", port);
}
// Create client
logger.info("Creating MQTT client...");
String clientID = MqttClient.generateClientId();
logger.info("Client ID: " + clientID);
logger.info("Server URI: " + serverURI);
try {
mqttClient = new MqttClient(serverURI, clientID);
} catch (MqttException e) {
logger.error(e.getMessage());
return false;
}
// Connect
logger.info("Connecting...");
MqttConnectOptions options = new MqttConnectOptions();
if (sslEnabled) {
SSLSecurityManager sm;
try {
sm = new SSLSecurityManager("TLSv1", "sepa.jks", "sepa2017", "sepa2017");
} catch (UnrecoverableKeyException | KeyManagementException | KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) {
logger.error(e.getMessage());
return false;
}
logger.info("Set SSL security");
try {
options.setSocketFactory(sm.getSSLContext().getSocketFactory());
} catch (KeyManagementException | NoSuchAlgorithmException e) {
logger.error(e.getMessage());
return false;
}
}
try {
mqttClient.connect(options);
} catch (MqttException e) {
logger.error(e.getMessage());
}
// Subscribe
mqttClient.setCallback(this);
logger.info("Subscribing...");
try {
mqttClient.subscribe(topicsFilter);
} catch (MqttException e) {
logger.error(e.getMessage());
return false;
}
for (String topic : topicsFilter) logger.info("MQTT client " + clientID + " subscribed to " + serverURI + " Topic filter " + topic);
// MQTT: end
}
return true;
}
use of it.unibo.arces.wot.sepa.commons.response.Response in project SEPA by arces-wot.
the class MeanMonitor method subscribe.
public boolean subscribe() {
Response ret;
ret = super.subscribe(null);
if (ret.isError())
return false;
SubscribeResponse results = (SubscribeResponse) ret;
// Previous mean values
for (Bindings binding : results.getBindingsResults().getBindings()) {
logger.info(binding.getBindingValue("mean") + " : " + Float.parseFloat(binding.getBindingValue("value").replaceAll(",", ".")) + " (values: " + Integer.parseInt(binding.getBindingValue("counter")) + ")");
}
return true;
}
use of it.unibo.arces.wot.sepa.commons.response.Response in project SEPA by arces-wot.
the class AuthorizationManager method authorizeRequest.
/**
* Operation when receiving a HTTP request at a protected endpoint
*
* 1. Check if the request contains an Authorization header. 2. Check if the
* request contains an Authorization: Bearer-header with non-null/empty
* contents 3. Check if the value of the Authorization: Bearer-header is a
* JWT object 4. Check if the JWT object is signed 5. Check if the signature
* of the JWT object is valid. This is to be checked with AS public
* signature verification key 6. Check the contents of the JWT object 7.
* Check if the value of "iss" is
* https://wot.arces.unibo.it:8443/oauth/token 8. Check if the value of
* "aud" contains https://wot.arces.unibo.it:8443/sparql 9. Accept the
* request as well as "sub" as the originator of the request and process it
* as usual
*
* *** Respond with 401 if not
*/
public boolean authorizeRequest(HttpRequest request) {
// Extract Bearer authorization
Header[] bearer = request.getHeaders("Authorization");
if (bearer.length != 1) {
logger.error("Authorization header is missing or multiple");
return false;
}
if (!bearer[0].getValue().startsWith("Bearer ")) {
logger.error("Authorization must be \"Bearer JWT\"");
return false;
}
// ******************
// JWT validation
// ******************
String jwt = bearer[0].getValue().split(" ")[1];
Response valid = validateToken(jwt);
if (valid.getClass().equals(ErrorResponse.class))
return false;
return true;
}
Aggregations