Search in sources :

Example 6 with JWTResponse

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());
        }
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) RequestConfig(org.apache.http.client.config.RequestConfig) HttpEntity(org.apache.http.HttpEntity) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) URI(java.net.URI) ParseException(org.apache.http.ParseException) SEPASecurityException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) StringEntity(org.apache.http.entity.StringEntity) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) JsonParser(com.google.gson.JsonParser) JWTResponse(it.unibo.arces.wot.sepa.commons.response.JWTResponse)

Example 7 with JWTResponse

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);
}
Also used : Response(it.unibo.arces.wot.sepa.commons.response.Response) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) JWTResponse(it.unibo.arces.wot.sepa.commons.response.JWTResponse) SEPAProtocolException(it.unibo.arces.wot.sepa.commons.exceptions.SEPAProtocolException) SEPAPropertiesException(it.unibo.arces.wot.sepa.commons.exceptions.SEPAPropertiesException) SEPASecurityException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException) JWTResponse(it.unibo.arces.wot.sepa.commons.response.JWTResponse) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse)

Example 8 with JWTResponse

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());
}
Also used : BadJOSEException(com.nimbusds.jose.proc.BadJOSEException) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) SignedJWT(com.nimbusds.jwt.SignedJWT) ParseException(java.text.ParseException) JOSEException(com.nimbusds.jose.JOSEException) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException) Date(java.util.Date) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) JWTResponse(it.unibo.arces.wot.sepa.commons.response.JWTResponse)

Example 9 with JWTResponse

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);
}
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 10 with JWTResponse

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;
}
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) Date(java.util.Date) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) JWTResponse(it.unibo.arces.wot.sepa.commons.response.JWTResponse)

Aggregations

ErrorResponse (it.unibo.arces.wot.sepa.commons.response.ErrorResponse)11 JWTResponse (it.unibo.arces.wot.sepa.commons.response.JWTResponse)11 SEPASecurityException (it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException)6 Response (it.unibo.arces.wot.sepa.commons.response.Response)5 Date (java.util.Date)5 JsonObject (com.google.gson.JsonObject)4 JsonParser (com.google.gson.JsonParser)4 RegistrationResponse (it.unibo.arces.wot.sepa.commons.response.RegistrationResponse)4 JOSEException (com.nimbusds.jose.JOSEException)3 BadJOSEException (com.nimbusds.jose.proc.BadJOSEException)3 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)3 SignedJWT (com.nimbusds.jwt.SignedJWT)3 SEPAPropertiesException (it.unibo.arces.wot.sepa.commons.exceptions.SEPAPropertiesException)3 IOException (java.io.IOException)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)3 URISyntaxException (java.net.URISyntaxException)3 ParseException (java.text.ParseException)3 HttpEntity (org.apache.http.HttpEntity)3 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)3 JWSHeader (com.nimbusds.jose.JWSHeader)2