use of it.unibo.arces.wot.sepa.commons.response.JWTResponse in project SEPA by arces-wot.
the class KeycloakAuthenticationService method requestToken.
@Override
public Response requestToken(String authorization, int timeout) {
/*
* POST /auth/realms/demo/protocol/openid-connect/token Authorization: Basic
* cHJvZHVjdC1zYS1jbGllbnQ6cGFzc3dvcmQ= Content-Type:
* application/x-www-form-urlencoded
*
* grant_type=client_credentials
**/
logger.log(Level.getLevel("oauth"), "TOKEN_REQUEST: " + authorization);
CloseableHttpResponse response = null;
long start = Timings.getTime();
try {
URI uri = new URI(oauthProperties.getTokenRequestUrl());
HttpPost httpRequest = new HttpPost(uri);
StringEntity body = new StringEntity("grant_type=client_credentials");
httpRequest.setEntity(body);
httpRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpRequest.setHeader("Authorization", authorization);
// Set timeout
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build();
httpRequest.setConfig(requestConfig);
try {
response = httpClient.execute(httpRequest);
// break;
} catch (Exception e) {
ErrorResponse err = new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getClass().getName(), e.getMessage());
logger.error(err);
return err;
}
logger.log(Level.getLevel("oauth"), "Response: " + response);
HttpEntity entity = response.getEntity();
String jsonResponse = EntityUtils.toString(entity, Charset.forName("UTF-8"));
EntityUtils.consume(entity);
// Parse response
JsonObject json = new JsonParser().parse(jsonResponse).getAsJsonObject();
if (json.has("error")) {
Timings.log("TOKEN_REQUEST", start, Timings.getTime());
ErrorResponse error = new ErrorResponse(response.getStatusLine().getStatusCode(), "token_request", json.get("error").getAsString());
return error;
}
return new JWTResponse(json);
} catch (Exception e) {
logger.error(e.getMessage());
Timings.log("TOKEN_REQUEST", start, Timings.getTime());
return new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Exception", e.getMessage());
} finally {
try {
if (response != null)
response.close();
} catch (IOException e) {
logger.error(e.getMessage());
Timings.log("TOKEN_REQUEST", start, Timings.getTime());
return new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "IOException", e.getMessage());
}
}
}
use of it.unibo.arces.wot.sepa.commons.response.JWTResponse in project SEPA by arces-wot.
the class WebsocketSubscriptionProtocol method onError.
@Override
public void onError(ErrorResponse errorResponse) {
// REFRESH TOKEN
if (errorResponse.isTokenExpiredError()) {
String authHeader = null;
try {
Response ret = sm.refreshToken();
if (ret.isError()) {
logger.error(ret);
handler.onError((ErrorResponse) ret);
return;
}
JWTResponse token = (JWTResponse) ret;
authHeader = token.getTokenType() + " " + token.getAccessToken();
} catch (SEPAPropertiesException | SEPASecurityException e1) {
logger.error(e1.getMessage());
handler.onError(errorResponse);
return;
}
synchronized (mutex) {
if (lastRequest == null) {
handler.onError(errorResponse);
return;
}
}
try {
lastRequest.setAuthorizationHeader(authHeader);
logger.trace("SEND LAST REQUEST WITH NEW TOKEN");
client.send(lastRequest.toString());
} catch (SEPAProtocolException e) {
logger.error(e.getMessage());
if (logger.isTraceEnabled())
e.printStackTrace();
ErrorResponse err = new ErrorResponse(401, "invalid_grant", "Failed to send request after refreshing token. " + e.getMessage());
handler.onError(err);
}
} else
handler.onError(errorResponse);
}
use of it.unibo.arces.wot.sepa.commons.response.JWTResponse in project SEPA by arces-wot.
the class AuthorizationManager method validateToken.
public Response validateToken(String accessToken) {
logger.debug("Validate token");
// Parse and verify the token
SignedJWT signedJWT = null;
try {
signedJWT = SignedJWT.parse(accessToken);
} catch (ParseException e) {
return new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, e.getMessage());
}
try {
if (!signedJWT.verify(verifier))
return new ErrorResponse(HttpStatus.SC_UNAUTHORIZED);
} catch (JOSEException e) {
return new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, e.getMessage());
}
// Process the token
JWTClaimsSet claimsSet;
try {
claimsSet = jwtProcessor.process(accessToken, context);
} catch (ParseException | BadJOSEException | JOSEException e) {
return new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, e.getMessage());
}
// Check token expiration
Date now = new Date();
if (now.after(claimsSet.getExpirationTime()))
return new ErrorResponse(0, HttpStatus.SC_UNAUTHORIZED, "Token is expired " + claimsSet.getExpirationTime());
if (now.before(claimsSet.getNotBeforeTime()))
return new ErrorResponse(0, HttpStatus.SC_UNAUTHORIZED, "Token can not be used before: " + claimsSet.getNotBeforeTime());
return new JWTResponse(accessToken, "bearer", now.getTime() - claimsSet.getExpirationTime().getTime());
}
use of it.unibo.arces.wot.sepa.commons.response.JWTResponse 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.JWTResponse in project SEPA by arces-wot.
the class ClientSecurityManager method refreshToken.
public Response refreshToken(int timeout) throws SEPAPropertiesException, SEPASecurityException {
if (!oauthProperties.isClientRegistered()) {
return new ErrorResponse(401, "invalid_client", "Client is not registered");
}
Response ret = oauth.requestToken(oauthProperties.getBasicAuthorizationHeader(), timeout);
if (ret.isJWTResponse()) {
JWTResponse jwt = (JWTResponse) ret;
logger.debug("New token: " + jwt);
oauthProperties.setJWT(jwt);
} else {
logger.error("FAILED to refresh token " + new Date() + " Response: " + ret);
}
return ret;
}
Aggregations