Search in sources :

Example 16 with SEPASecurityException

use of it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException in project SEPA by arces-wot.

the class KeyCloakSecurityManager method validateToken.

/**
 * Requesting Party Token
 *
 * If you want to validate these tokens without a call to the remote introspection endpoint, you can decode the RPT and query for its validity locally.
 * Once you decode the token, you can also use the permissions within the token to enforce authorization decisions.
 *
 * This is essentially what the policy enforcers do. Be sure to:
 * 1) Validate the signature of the RPT (based on the realm’s public key)
 * 2) Query for token validity based on its exp, iat, and aud claims
 *
 * The claim "preferred_username" is used to identify the user
 */
@Override
public synchronized ClientAuthorization validateToken(String accessToken) {
    logger.log(Level.getLevel("oauth"), "VALIDATE TOKEN");
    // Parse token
    SignedJWT signedJWT = null;
    try {
        signedJWT = SignedJWT.parse(accessToken);
    } catch (ParseException e) {
        logger.log(Level.getLevel("oauth"), e.getMessage());
        return new ClientAuthorization("invalid_request", "ParseException: " + e.getMessage());
    }
    // Verify token
    try {
        if (!signedJWT.verify(verifier)) {
            logger.log(Level.getLevel("oauth"), "Signed JWT not verified");
            return new ClientAuthorization("invalid_grant", "Signed JWT not verified");
        }
    } catch (JOSEException e) {
        logger.log(Level.getLevel("oauth"), e.getMessage());
        return new ClientAuthorization("invalid_grant", "JOSEException: " + e.getMessage());
    }
    String uid;
    // Process token (validate)
    JWTClaimsSet claimsSet = null;
    try {
        claimsSet = signedJWT.getJWTClaimsSet();
        logger.log(Level.getLevel("oauth"), claimsSet);
        // Get client credentials for accessing the SPARQL endpoint
        uid = claimsSet.getStringClaim("username");
        if (uid == null) {
            logger.log(Level.getLevel("oauth"), "<username> claim is null. Look for <preferred_username>");
            uid = claimsSet.getStringClaim("preferred_username");
            if (uid == null) {
                logger.log(Level.getLevel("oauth"), "USER ID not found...");
                return new ClientAuthorization("invalid_grant", "Username claim not found");
            }
        }
        logger.log(Level.getLevel("oauth"), "Subject: " + claimsSet.getSubject());
        logger.log(Level.getLevel("oauth"), "Issuer: " + claimsSet.getIssuer());
        logger.log(Level.getLevel("oauth"), "Username: " + uid);
    } catch (ParseException e) {
        logger.error(e.getMessage());
        return new ClientAuthorization("invalid_grant", "ParseException. " + e.getMessage());
    }
    // Check token expiration (an "invalid_grant" error is raised if the token is
    // expired)
    Date now = new Date();
    long nowUnixSeconds = (now.getTime() / 1000) * 1000;
    Date expiring = claimsSet.getExpirationTime();
    Date notBefore = claimsSet.getNotBeforeTime();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
    if (expiring.getTime() - nowUnixSeconds < 0) {
        logger.log(Level.getLevel("oauth"), "Token is expired: " + sdf.format(claimsSet.getExpirationTime()) + " < " + sdf.format(new Date(nowUnixSeconds)));
        return new ClientAuthorization("invalid_grant", "Token issued at " + sdf.format(claimsSet.getIssueTime()) + " is expired: " + sdf.format(claimsSet.getExpirationTime()) + " < " + sdf.format(now));
    }
    if (notBefore != null && nowUnixSeconds < notBefore.getTime()) {
        logger.log(Level.getLevel("oauth"), "Token can not be used before: " + claimsSet.getNotBeforeTime());
        return new ClientAuthorization("invalid_grant", "Token can not be used before: " + claimsSet.getNotBeforeTime());
    }
    Credentials cred = null;
    try {
        cred = getEndpointCredentials(uid);
        logger.log(Level.getLevel("oauth"), "Endpoint credentials: " + cred);
    } catch (SEPASecurityException e) {
        logger.log(Level.getLevel("oauth"), "Failed to retrieve credentials (" + uid + ")");
        return new ClientAuthorization("invalid_grant", "Failed to get credentials (" + uid + ")");
    }
    return new ClientAuthorization(cred);
}
Also used : ClientAuthorization(it.unibo.arces.wot.sepa.commons.security.ClientAuthorization) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) SEPASecurityException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException) SignedJWT(com.nimbusds.jwt.SignedJWT) ParseException(java.text.ParseException) JOSEException(com.nimbusds.jose.JOSEException) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date) Credentials(it.unibo.arces.wot.sepa.commons.security.Credentials)

Example 17 with SEPASecurityException

use of it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException in project SEPA by arces-wot.

the class LdapSecurityManager method getDeviceExpiringPeriod.

@Override
public long getDeviceExpiringPeriod() throws SEPASecurityException {
    logger.log(Level.getLevel("ldap"), "[LDAP] getDeviceExpiringPeriod " + "uid=device,uid=expiring,ou=jwt," + prop.getBase(), "(objectclass=*)");
    bind();
    try {
        cursor = ldap.search("uid=device,uid=expiring,ou=jwt," + prop.getBase(), "(objectclass=*)", SearchScope.OBJECT, "*");
        if (!cursor.next())
            throw new SEPASecurityException("uid=device,uid=expiring,ou=jwt," + prop.getBase() + " NOT FOUND");
        if (cursor.get().get("pwdGraceExpire") == null)
            throw new SEPASecurityException("uid=device,uid=expiring,ou=jwt," + prop.getBase() + " pwdGraceExpire NOT FOUND");
        return Long.parseLong(cursor.get().get("pwdGraceExpire").getString());
    } catch (LdapException | CursorException e) {
        logger.error("getDeviceExpiringPeriod exception " + e.getMessage());
        throw new SEPASecurityException("getDeviceExpiringPeriod exception " + e.getMessage());
    } finally {
        unbind();
    }
}
Also used : CursorException(org.apache.directory.api.ldap.model.cursor.CursorException) SEPASecurityException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException) LdapException(org.apache.directory.api.ldap.model.exception.LdapException)

Example 18 with SEPASecurityException

use of it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException in project SEPA by arces-wot.

the class LdapSecurityManager method getEndpointCredentials.

@Override
public Credentials getEndpointCredentials(String uid) throws SEPASecurityException {
    bind();
    try {
        logger.log(Level.getLevel("ldap"), "[LDAP] getEndpointCredentials Base DN: " + "uid=" + uid + ",ou=credentials," + prop.getBase());
        cursor = ldap.search("uid=" + uid + ",ou=credentials," + prop.getBase(), "(objectclass=*)", SearchScope.OBJECT, "*");
        if (cursor.next()) {
            Attribute attr = cursor.get().get("javaSerializedData");
            if (attr != null) {
                byte[] cred = attr.getBytes();
                Credentials auth = Credentials.deserialize(cred);
                // TODO: WARNING. PRINTING CREDENTIALS just for debugging purposes
                logger.debug("[LDAP] " + auth);
                return auth;
            }
        }
    } catch (LdapException | CursorException e) {
        logger.error("[LDAP] LdapException|CursorException : " + e.getMessage());
        throw new SEPASecurityException(e.getMessage());
    } finally {
        unbind();
    }
    return null;
}
Also used : Attribute(org.apache.directory.api.ldap.model.entry.Attribute) CursorException(org.apache.directory.api.ldap.model.cursor.CursorException) SEPASecurityException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException) LdapException(org.apache.directory.api.ldap.model.exception.LdapException) Credentials(it.unibo.arces.wot.sepa.commons.security.Credentials)

Example 19 with SEPASecurityException

use of it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException in project SEPA by arces-wot.

the class LdapSecurityManager method addJwt.

@Override
public void addJwt(String uid, SignedJWT token) throws SEPASecurityException {
    logger.log(Level.getLevel("ldap"), "[LDAP] addToken " + uid + " uid=" + uid + ",ou=tokens," + prop.getBase(), "(objectclass=*)");
    bind();
    try {
        cursor = ldap.search("uid=" + uid + ",ou=tokens," + prop.getBase(), "(objectclass=*)", SearchScope.OBJECT, "*");
        if (!cursor.next()) {
            ldap.add(new DefaultEntry("uid=" + uid + ",ou=tokens," + prop.getBase(), "ObjectClass: top", "ObjectClass: account", "ObjectClass: javaSerializedObject", "javaClassName: " + token.getClass().getName(), "javaSerializedData: " + token.serialize()));
        } else {
            Modification replaceGn = new DefaultModification(ModificationOperation.REPLACE_ATTRIBUTE, "javaSerializedData", token.serialize());
            ldap.modify("uid=" + uid + ",ou=tokens," + prop.getBase(), replaceGn);
        }
    } catch (LdapException | CursorException e) {
        logger.error("[LDAP] addToken exception " + e.getMessage());
        throw new SEPASecurityException("addToken exception " + e.getMessage());
    } finally {
        unbind();
    }
}
Also used : DefaultModification(org.apache.directory.api.ldap.model.entry.DefaultModification) Modification(org.apache.directory.api.ldap.model.entry.Modification) DefaultModification(org.apache.directory.api.ldap.model.entry.DefaultModification) CursorException(org.apache.directory.api.ldap.model.cursor.CursorException) DefaultEntry(org.apache.directory.api.ldap.model.entry.DefaultEntry) SEPASecurityException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException) LdapException(org.apache.directory.api.ldap.model.exception.LdapException)

Example 20 with SEPASecurityException

use of it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException in project SEPA by arces-wot.

the class LdapSecurityManager method getTokenExpiringDate.

@Override
public Date getTokenExpiringDate(String uid) throws SEPASecurityException {
    logger.log(Level.getLevel("ldap"), "[LDAP] getTokenExpiringDate " + uid + " uid=" + uid + ",ou=tokens," + prop.getBase(), "(objectclass=*)");
    bind();
    try {
        cursor = ldap.search("uid=" + uid + ",ou=tokens," + prop.getBase(), "(objectclass=*)", SearchScope.OBJECT, "*");
        if (!cursor.next())
            throw new SEPASecurityException("uid=" + uid + ",ou=tokens," + prop.getBase() + " NOT FOUND");
        SignedJWT jwt = SignedJWT.parse(cursor.get().get("javaSerializedData").getString());
        return jwt.getJWTClaimsSet().getExpirationTime();
    } catch (LdapException | CursorException | ParseException e) {
        logger.error("[LDAP] getTokenExpiringDate exception " + e.getMessage());
        throw new SEPASecurityException("getTokenExpiringDate exception " + e.getMessage());
    } finally {
        unbind();
    }
}
Also used : CursorException(org.apache.directory.api.ldap.model.cursor.CursorException) SEPASecurityException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException) SignedJWT(com.nimbusds.jwt.SignedJWT) ParseException(java.text.ParseException) LdapException(org.apache.directory.api.ldap.model.exception.LdapException)

Aggregations

SEPASecurityException (it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException)69 LdapException (org.apache.directory.api.ldap.model.exception.LdapException)29 IOException (java.io.IOException)20 CursorException (org.apache.directory.api.ldap.model.cursor.CursorException)18 ErrorResponse (it.unibo.arces.wot.sepa.commons.response.ErrorResponse)15 Response (it.unibo.arces.wot.sepa.commons.response.Response)12 SEPAPropertiesException (it.unibo.arces.wot.sepa.commons.exceptions.SEPAPropertiesException)11 SEPAProtocolException (it.unibo.arces.wot.sepa.commons.exceptions.SEPAProtocolException)10 JsonObject (com.google.gson.JsonObject)7 JsonParser (com.google.gson.JsonParser)7 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)7 DefaultModification (org.apache.directory.api.ldap.model.entry.DefaultModification)7 Modification (org.apache.directory.api.ldap.model.entry.Modification)7 SEPABindingsException (it.unibo.arces.wot.sepa.commons.exceptions.SEPABindingsException)5 Credentials (it.unibo.arces.wot.sepa.commons.security.Credentials)5 HttpEntity (org.apache.http.HttpEntity)5 JOSEException (com.nimbusds.jose.JOSEException)4 SignedJWT (com.nimbusds.jwt.SignedJWT)4 JWTResponse (it.unibo.arces.wot.sepa.commons.response.JWTResponse)4 ParseException (java.text.ParseException)4