Search in sources :

Example 1 with RegistrationResponse

use of it.unibo.arces.wot.sepa.commons.response.RegistrationResponse in project SEPA by arces-wot.

the class AuthorizationManager method securityCheck.

private void securityCheck(String identity) {
    logger.debug("*** Security check ***");
    // Add identity
    addAuthorizedIdentity(identity);
    // Register
    logger.debug("Register: " + identity);
    Response response = register(identity);
    if (response.getClass().equals(RegistrationResponse.class)) {
        RegistrationResponse ret = (RegistrationResponse) response;
        String auth = ret.getClientId() + ":" + ret.getClientSecret();
        logger.debug("ID:SECRET=" + auth);
        // Get token
        String encodedCredentials = Base64.getEncoder().encodeToString(auth.getBytes());
        logger.debug("Authorization Basic " + encodedCredentials);
        response = getToken(encodedCredentials);
        if (response.getClass().equals(JWTResponse.class)) {
            logger.debug("Access token: " + ((JWTResponse) response).getAccessToken());
            // Validate token
            Response valid = validateToken(((JWTResponse) response).getAccessToken());
            if (!valid.getClass().equals(ErrorResponse.class))
                logger.debug("PASSED");
            else {
                ErrorResponse error = (ErrorResponse) valid;
                logger.debug("FAILED Code: " + error.getErrorCode() + "Message: " + error.getErrorMessage());
            }
        } else
            logger.debug("FAILED");
    } else
        logger.debug("FAILED");
    logger.debug("**********************");
    System.out.println("");
    // Add identity
    removeAuthorizedIdentity(identity);
}
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) RegistrationResponse(it.unibo.arces.wot.sepa.commons.response.RegistrationResponse) JWTResponse(it.unibo.arces.wot.sepa.commons.response.JWTResponse) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse)

Example 2 with RegistrationResponse

use of it.unibo.arces.wot.sepa.commons.response.RegistrationResponse in project SEPA by arces-wot.

the class SecurityManager method securityCheck.

public void securityCheck(String identity) throws SEPASecurityException {
    logger.info("*** Security check ***");
    // Add identity
    addAuthorizedIdentity(new ApplicationIdentity(identity));
    // Register
    Response response = register(identity);
    if (response.getClass().equals(RegistrationResponse.class)) {
        RegistrationResponse ret = (RegistrationResponse) response;
        String basicAuth = ret.getClientId() + ":" + ret.getClientSecret();
        // Get token
        String encodedCredentials = Base64.getEncoder().encodeToString(basicAuth.getBytes());
        logger.debug("Authorization Basic " + encodedCredentials);
        response = getToken(encodedCredentials);
        if (response.getClass().equals(JWTResponse.class)) {
            logger.debug("Access token: " + ((JWTResponse) response).getAccessToken());
            // Validate token
            ClientAuthorization authRet = validateToken(((JWTResponse) response).getAccessToken());
            if (authRet.isAuthorized()) {
                removeCredentials(new ApplicationIdentity(ret.getClientId()));
                removeJwt(ret.getClientId());
                logger.info("*** PASSED ***");
            } else {
                logger.error(authRet.getError());
                logger.info("*** FAILED ***");
            }
        } else {
            logger.debug(response.toString());
            logger.info("*** FAILED ***");
        }
    } else {
        logger.debug(response.toString());
        logger.info("*** FAILED ***");
        // Remove identity
        removeAuthorizedIdentity(identity);
    }
    System.out.println("");
}
Also used : Response(it.unibo.arces.wot.sepa.commons.response.Response) RegistrationResponse(it.unibo.arces.wot.sepa.commons.response.RegistrationResponse) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) JWTResponse(it.unibo.arces.wot.sepa.commons.response.JWTResponse) ClientAuthorization(it.unibo.arces.wot.sepa.commons.security.ClientAuthorization) ApplicationIdentity(it.unibo.arces.wot.sepa.engine.dependability.authorization.identities.ApplicationIdentity) RegistrationResponse(it.unibo.arces.wot.sepa.commons.response.RegistrationResponse) JWTResponse(it.unibo.arces.wot.sepa.commons.response.JWTResponse)

Example 3 with RegistrationResponse

use of it.unibo.arces.wot.sepa.commons.response.RegistrationResponse in project SEPA by arces-wot.

the class DefaultAuthenticationService method registerClient.

public Response registerClient(String client_id, String username, String initialAccessToken, int timeout) throws SEPASecurityException {
    if (client_id == null)
        throw new SEPASecurityException("Identity is null");
    logger.log(Level.getLevel("oauth"), "REGISTER " + client_id);
    CloseableHttpResponse response = null;
    long start = Timings.getTime();
    try {
        URI uri = new URI(oauthProperties.getRegisterUrl());
        ByteArrayEntity body = new ByteArrayEntity(new RegistrationRequest(client_id).toString().getBytes("UTF-8"));
        HttpPost httpRequest = new HttpPost(uri);
        httpRequest.setHeader("Content-Type", "application/json");
        httpRequest.setHeader("Accept", "application/json");
        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_INTERNAL_SERVER_ERROR, "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(code, error, description);
            logger.error(ret);
            return ret;
        }
        String id = json.get("credentials").getAsJsonObject().get("client_id").getAsString();
        String secret = json.get("credentials").getAsJsonObject().get("client_secret").getAsString();
        JsonElement signature = json.get("credentials").getAsJsonObject().get("signature");
        Timings.log("REGISTER", start, Timings.getTime());
        return new RegistrationResponse(id, secret, signature);
    } catch (URISyntaxException e) {
        logger.error(e.getMessage());
        Timings.log("REGISTER_ERROR", start, Timings.getTime());
        return new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "URISyntaxException", e.getMessage());
    } catch (UnsupportedEncodingException e) {
        logger.error(e.getMessage());
        Timings.log("REGISTER_ERROR", start, Timings.getTime());
        return new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "UnsupportedEncodingException", e.getMessage());
    } catch (ParseException e) {
        logger.error(e.getMessage());
        Timings.log("REGISTER_ERROR", start, Timings.getTime());
        return new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "ParseException", e.getMessage());
    } catch (IOException e) {
        logger.error(e.getMessage());
        Timings.log("REGISTER_ERROR", start, Timings.getTime());
        return new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "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_INTERNAL_SERVER_ERROR, "IOException", e.getMessage());
        }
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) RequestConfig(org.apache.http.client.config.RequestConfig) HttpEntity(org.apache.http.HttpEntity) SEPASecurityException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException) JsonObject(com.google.gson.JsonObject) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) RegistrationRequest(it.unibo.arces.wot.sepa.commons.request.RegistrationRequest) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) JsonElement(com.google.gson.JsonElement) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) ParseException(org.apache.http.ParseException) RegistrationResponse(it.unibo.arces.wot.sepa.commons.response.RegistrationResponse) JsonParser(com.google.gson.JsonParser)

Example 4 with RegistrationResponse

use of it.unibo.arces.wot.sepa.commons.response.RegistrationResponse in project SEPA by arces-wot.

the class SPARQL11SEProtocol method parseSPARQL11SEResponse.

protected Response parseSPARQL11SEResponse(String response, SPARQL11SEPrimitive op) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
    if (response == null)
        return new ErrorResponse(0, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Response is null");
    JsonObject json = null;
    try {
        json = new JsonParser().parse(response).getAsJsonObject();
    } catch (JsonParseException | IllegalStateException e) {
        return new ErrorResponse(0, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Unknown response: " + response);
    }
    // Error response
    if (json.get("code") != null)
        if (json.get("code").getAsInt() >= 400)
            return new ErrorResponse(0, json.get("code").getAsInt(), json.get("body").getAsString());
    if (op == SPARQL11SEPrimitive.SECUREQUERY)
        return new QueryResponse(json);
    if (op == SPARQL11SEPrimitive.SECUREUPDATE)
        return new UpdateResponse(response);
    if (op == SPARQL11SEPrimitive.REGISTER) {
        if (json.get("client_id") != null && json.get("client_secret") != null) {
            try {
                properties.setCredentials(json.get("client_id").getAsString(), json.get("client_secret").getAsString());
            } catch (SEPASecurityException | SEPAPropertiesException e) {
                return new ErrorResponse(-1, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Failed to save credentials");
            }
            return new RegistrationResponse(json.get("client_id").getAsString(), json.get("client_secret").getAsString(), json.get("signature"));
        }
        return new ErrorResponse(-1, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Credentials not found in registration response");
    }
    if (op == SPARQL11SEPrimitive.REQUESTTOKEN) {
        if (json.get("access_token") != null && json.get("expires_in") != null && json.get("token_type") != null) {
            int seconds = json.get("expires_in").getAsInt();
            Date expires = new Date();
            expires.setTime(expires.getTime() + (1000 * seconds));
            try {
                properties.setJWT(json.get("access_token").getAsString(), expires, json.get("token_type").getAsString());
            } catch (SEPASecurityException | SEPAPropertiesException e) {
                return new ErrorResponse(-1, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Failed to save JWT");
            }
            return new JWTResponse(json.get("access_token").getAsString(), json.get("token_type").getAsString(), json.get("expires_in").getAsLong());
        } else if (json.get("code") != null && json.get("body") != null)
            return new ErrorResponse(0, json.get("code").getAsInt(), json.get("body").getAsString());
        else if (json.get("code") != null)
            return new ErrorResponse(0, json.get("code").getAsInt(), "");
        return new ErrorResponse(0, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Response not recognized: " + json.toString());
    }
    return new ErrorResponse(0, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Response unknown: " + response);
}
Also used : SEPAPropertiesException(it.unibo.arces.wot.sepa.commons.exceptions.SEPAPropertiesException) JsonObject(com.google.gson.JsonObject) SEPASecurityException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException) JsonParseException(com.google.gson.JsonParseException) Date(java.util.Date) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) UpdateResponse(it.unibo.arces.wot.sepa.commons.response.UpdateResponse) QueryResponse(it.unibo.arces.wot.sepa.commons.response.QueryResponse) RegistrationResponse(it.unibo.arces.wot.sepa.commons.response.RegistrationResponse) JsonParser(com.google.gson.JsonParser) JWTResponse(it.unibo.arces.wot.sepa.commons.response.JWTResponse)

Example 5 with RegistrationResponse

use of it.unibo.arces.wot.sepa.commons.response.RegistrationResponse in project SEPA by arces-wot.

the class SecurityManager method register.

/**
 * <pre>
 * POST https://wot.arces.unibo.it:8443/oauth/token
 *
 * Accept: application/json
 * Content-Type: application/json
 *
 * {
 *  "client_identity": ”<ClientIdentity>",
 *  "grant_types": ["client_credentials"]
 * }
 *
 * Response example:
 *
 * {
 *  "clientId": "889d02cf-16dd-4934-9341-a754088faxyz",
 *  "clientSecret": "ahd5MU42J0hIxPXzhUhjJHt2d0Oc5M6B644CtuwUlE9zpSuF14-kXYZ",
 *  "signature" : JWK RSA public key (can be used to verify the signature),
 *  "authorized" : Boolean
 * }
 *
 * In case of error, the following applies:
 *	{
 *	"error":"Unless specified otherwise see RFC6749. Otherwise, this is specific of the SPARQL 1.1 SE Protocol",
 *	"error_description":"Unless specified otherwise, see RFC6749. Otherwise, this is specific of the SPARQL 1.1 SE Protocol", (OPTIONAL)
 *	"status_code" : the HTTP status code (would be 400 for Oauth 2.0 errors).
 *	}
 * </pre>
 *
 * Create client credentials for an authorized identity
 *
 * @param identity the client identity to be registered
 * @throws SEPASecurityException
 */
public synchronized Response register(String uid) {
    logger.info("REGISTER: " + uid);
    // Check if entity is authorized to request credentials
    try {
        if (!isAuthorized(uid)) {
            logger.warn("Not authorized identity " + uid);
            return new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, "not_authorized_identity", "Client " + uid + " is not authorized");
        }
    } catch (SEPASecurityException e) {
        logger.error(e.getMessage());
        return new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, "not_authorized_identity", "Exception on authorizing client " + uid + " " + e.getMessage());
    }
    // Generate password
    String client_secret = UUID.randomUUID().toString();
    boolean forTesting = false;
    try {
        forTesting = isForTesting(uid);
    } catch (SEPASecurityException e1) {
        logger.error(e1.getMessage());
        return new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, "check_for_testing", "Exception on for test checking " + uid + " " + e1.getMessage());
    }
    if (forTesting)
        client_secret = uid;
    // Store credentials
    try {
        boolean res = storeCredentials(getIdentity(uid), client_secret);
        if (!res) {
            return new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, "storing_credentials", "Failed to store credentials for uid:" + uid);
        }
    } catch (SEPASecurityException e) {
        logger.error(e.getMessage());
        return new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, "storing_credentials", "Exception on storing credentials " + uid + " " + e.getMessage());
    }
    // One time registration (not removed for testing purposes)
    if (!forTesting)
        try {
            removeAuthorizedIdentity(uid);
        } catch (SEPASecurityException e) {
            logger.error(e.getMessage());
            return new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, "remove_identity", "Exception on removing identity " + uid + " " + e.getMessage());
        }
    return new RegistrationResponse(uid, client_secret, jwkPublicKey);
}
Also used : SEPASecurityException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException) RegistrationResponse(it.unibo.arces.wot.sepa.commons.response.RegistrationResponse) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse)

Aggregations

ErrorResponse (it.unibo.arces.wot.sepa.commons.response.ErrorResponse)7 RegistrationResponse (it.unibo.arces.wot.sepa.commons.response.RegistrationResponse)7 SEPASecurityException (it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException)4 JWTResponse (it.unibo.arces.wot.sepa.commons.response.JWTResponse)4 JsonObject (com.google.gson.JsonObject)3 JsonParser (com.google.gson.JsonParser)3 Response (it.unibo.arces.wot.sepa.commons.response.Response)3 SEPAPropertiesException (it.unibo.arces.wot.sepa.commons.exceptions.SEPAPropertiesException)2 IOException (java.io.IOException)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 URI (java.net.URI)2 URISyntaxException (java.net.URISyntaxException)2 HttpEntity (org.apache.http.HttpEntity)2 ParseException (org.apache.http.ParseException)2 RequestConfig (org.apache.http.client.config.RequestConfig)2 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)2 HttpPost (org.apache.http.client.methods.HttpPost)2 JsonArray (com.google.gson.JsonArray)1 JsonElement (com.google.gson.JsonElement)1 JsonParseException (com.google.gson.JsonParseException)1