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);
}
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("");
}
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());
}
}
}
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);
}
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);
}
Aggregations