Search in sources :

Example 56 with SignedJWT

use of com.nimbusds.jwt.SignedJWT 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 57 with SignedJWT

use of com.nimbusds.jwt.SignedJWT 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)

Example 58 with SignedJWT

use of com.nimbusds.jwt.SignedJWT in project SEPA by arces-wot.

the class SecurityManagerTest method tokens.

// @Test
public void tokens() throws SEPASecurityException, KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, ParseException, IOException, JOSEException {
    String uid = UUID.randomUUID().toString();
    DigitalIdentity device = new DeviceIdentity(uid);
    auth.storeCredentials(device, uid);
    SignedJWT token = generateToken(device, uid);
    Date expirationDate = token.getJWTClaimsSet().getExpirationTime();
    auth.addJwt(uid, token);
    assertFalse("Failed to check token presence", !auth.containsJwt(uid));
    assertFalse("Failed to get expiring period", auth.getTokenExpiringPeriod(uid) != auth.getDeviceExpiringPeriod());
    assertFalse("Failed to get expiring date", !auth.getTokenExpiringDate(uid).equals(expirationDate));
    SignedJWT stored = auth.getJwt(uid);
    assertFalse("Token does not match", !stored.serialize().equals(token.serialize()));
    auth.setTokenExpiringPeriod(uid, 0);
    assertFalse("Failed to set expiring period", auth.getTokenExpiringPeriod(uid) != 0);
}
Also used : DeviceIdentity(it.unibo.arces.wot.sepa.engine.dependability.authorization.identities.DeviceIdentity) SignedJWT(com.nimbusds.jwt.SignedJWT) DigitalIdentity(it.unibo.arces.wot.sepa.engine.dependability.authorization.identities.DigitalIdentity) Date(java.util.Date)

Example 59 with SignedJWT

use of com.nimbusds.jwt.SignedJWT in project Payara by payara.

the class GCPSecretsConfigSource method buildJwt.

// Helpers
private static SignedJWT buildJwt(final String issuer, final String scope) {
    Instant now = Instant.now();
    Instant expiry = now.plus(1, ChronoUnit.MINUTES);
    JWTClaimsSet claims = new JWTClaimsSet.Builder().issuer(issuer).audience(AUTH_URL).issueTime(Date.from(now)).expirationTime(Date.from(expiry)).claim("scope", scope).build();
    JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT).build();
    return new SignedJWT(header, claims);
}
Also used : JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) Instant(java.time.Instant) ClientBuilder(javax.ws.rs.client.ClientBuilder) SignedJWT(com.nimbusds.jwt.SignedJWT) JWSHeader(com.nimbusds.jose.JWSHeader)

Example 60 with SignedJWT

use of com.nimbusds.jwt.SignedJWT in project cruise-control by linkedin.

the class JwtLoginService method login.

@Override
public UserIdentity login(String username, Object credentials, ServletRequest request) {
    if (!(credentials instanceof SignedJWT)) {
        return null;
    }
    if (!(request instanceof HttpServletRequest)) {
        return null;
    }
    SignedJWT jwtToken = (SignedJWT) credentials;
    JWTClaimsSet claimsSet;
    boolean valid;
    try {
        claimsSet = jwtToken.getJWTClaimsSet();
        valid = validateToken(jwtToken, claimsSet, username);
    } catch (ParseException e) {
        JWT_LOGGER.warn(String.format("%s: Couldn't parse a JWT token", username), e);
        return null;
    }
    if (valid) {
        String serializedToken = (String) request.getAttribute(JwtAuthenticator.JWT_TOKEN_REQUEST_ATTRIBUTE);
        UserIdentity rolesDelegate = _authorizationService.getUserIdentity((HttpServletRequest) request, username);
        if (rolesDelegate == null) {
            return null;
        } else {
            return getUserIdentity(jwtToken, claimsSet, serializedToken, username, rolesDelegate);
        }
    } else {
        return null;
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) UserIdentity(org.eclipse.jetty.server.UserIdentity) SignedJWT(com.nimbusds.jwt.SignedJWT) ParseException(java.text.ParseException)

Aggregations

SignedJWT (com.nimbusds.jwt.SignedJWT)204 Test (org.junit.Test)84 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)75 Date (java.util.Date)66 HttpServletRequest (javax.servlet.http.HttpServletRequest)64 HttpServletResponse (javax.servlet.http.HttpServletResponse)54 JWSHeader (com.nimbusds.jose.JWSHeader)53 Properties (java.util.Properties)49 ServletException (javax.servlet.ServletException)46 ParseException (java.text.ParseException)31 RSASSASigner (com.nimbusds.jose.crypto.RSASSASigner)28 JOSEException (com.nimbusds.jose.JOSEException)25 JWSSigner (com.nimbusds.jose.JWSSigner)21 Cookie (javax.servlet.http.Cookie)21 ArrayList (java.util.ArrayList)15 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)14 SignedJWTInfo (org.wso2.carbon.apimgt.impl.jwt.SignedJWTInfo)13 Test (org.junit.jupiter.api.Test)12 OAuth2TokenValidator (org.springframework.security.oauth2.core.OAuth2TokenValidator)12 Cache (javax.cache.Cache)11