Search in sources :

Example 11 with Response

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());
    }
}
Also used : Response(it.unibo.arces.wot.sepa.commons.response.Response) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) Header(org.apache.http.Header) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse)

Example 12 with Response

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());
}
Also used : HttpEntity(org.apache.http.HttpEntity) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) JsonArray(com.google.gson.JsonArray) Response(it.unibo.arces.wot.sepa.commons.response.Response) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) Header(org.apache.http.Header) JsonElement(com.google.gson.JsonElement) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest) ParseException(org.apache.http.ParseException) JsonParser(com.google.gson.JsonParser)

Example 13 with Response

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;
}
Also used : JsonObject(com.google.gson.JsonObject) CertificateException(java.security.cert.CertificateException) SubscribeResponse(it.unibo.arces.wot.sepa.commons.response.SubscribeResponse) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) Response(it.unibo.arces.wot.sepa.commons.response.Response) SubscribeResponse(it.unibo.arces.wot.sepa.commons.response.SubscribeResponse) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) JsonArray(com.google.gson.JsonArray) MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) UnrecoverableKeyException(java.security.UnrecoverableKeyException) JsonElement(com.google.gson.JsonElement) MqttException(org.eclipse.paho.client.mqttv3.MqttException) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) SSLSecurityManager(it.unibo.arces.wot.sepa.commons.protocol.SSLSecurityManager)

Example 14 with Response

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;
}
Also used : Response(it.unibo.arces.wot.sepa.commons.response.Response) SubscribeResponse(it.unibo.arces.wot.sepa.commons.response.SubscribeResponse) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) SubscribeResponse(it.unibo.arces.wot.sepa.commons.response.SubscribeResponse) Bindings(it.unibo.arces.wot.sepa.commons.sparql.Bindings)

Example 15 with Response

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;
}
Also used : ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) JWTResponse(it.unibo.arces.wot.sepa.commons.response.JWTResponse) Response(it.unibo.arces.wot.sepa.commons.response.Response) RegistrationResponse(it.unibo.arces.wot.sepa.commons.response.RegistrationResponse) Header(org.apache.http.Header) JWSHeader(com.nimbusds.jose.JWSHeader)

Aggregations

Response (it.unibo.arces.wot.sepa.commons.response.Response)40 ErrorResponse (it.unibo.arces.wot.sepa.commons.response.ErrorResponse)31 SubscribeResponse (it.unibo.arces.wot.sepa.commons.response.SubscribeResponse)19 QueryResponse (it.unibo.arces.wot.sepa.commons.response.QueryResponse)15 Bindings (it.unibo.arces.wot.sepa.commons.sparql.Bindings)12 Test (org.junit.Test)8 RDFTermLiteral (it.unibo.arces.wot.sepa.commons.sparql.RDFTermLiteral)7 UpdateResponse (it.unibo.arces.wot.sepa.commons.response.UpdateResponse)6 RDFTermURI (it.unibo.arces.wot.sepa.commons.sparql.RDFTermURI)5 JsonObject (com.google.gson.JsonObject)3 SubscribeRequest (it.unibo.arces.wot.sepa.commons.request.SubscribeRequest)3 ARBindingsResults (it.unibo.arces.wot.sepa.commons.sparql.ARBindingsResults)3 BindingsResults (it.unibo.arces.wot.sepa.commons.sparql.BindingsResults)3 IOException (java.io.IOException)3 Header (org.apache.http.Header)3 JsonArray (com.google.gson.JsonArray)2 JsonElement (com.google.gson.JsonElement)2 QueryRequest (it.unibo.arces.wot.sepa.commons.request.QueryRequest)2 UnsubscribeRequest (it.unibo.arces.wot.sepa.commons.request.UnsubscribeRequest)2 UpdateRequest (it.unibo.arces.wot.sepa.commons.request.UpdateRequest)2