Search in sources :

Example 1 with JWSHeader

use of com.nimbusds.jose.JWSHeader in project SEPA by arces-wot.

the class AuthorizationManager method getToken.

/**
 * POST https://wot.arces.unibo.it:8443/oauth/token
 *
 * Content-Type: application/x-www-form-urlencoded
 * Accept: application/json
 * Authorization: Basic Basic64(id:secret)
 *
 * Response example:
 * { 	"access_token": "eyJraWQiOiIyN.........",
 * 		"token_type": "bearer",
 * 		"expires_in": 3600
 * }
 *
 * In case of error, the following applies:
 * {
 * 		"code": Error code,
 * 		"body": "Error details"
 *
 * }
 */
public Response getToken(String encodedCredentials) {
    logger.debug("Get token");
    // Decode credentials
    byte[] decoded = null;
    try {
        decoded = Base64.getDecoder().decode(encodedCredentials);
    } catch (IllegalArgumentException e) {
        logger.error("Not authorized");
        return new ErrorResponse(0, HttpStatus.SC_UNAUTHORIZED, "Client not authorized");
    }
    String decodedCredentials = new String(decoded);
    String[] clientID = decodedCredentials.split(":");
    if (clientID == null) {
        logger.error("Wrong Basic authorization");
        return new ErrorResponse(0, HttpStatus.SC_UNAUTHORIZED, "Client not authorized");
    }
    if (clientID.length != 2) {
        logger.error("Wrong Basic authorization");
        return new ErrorResponse(0, HttpStatus.SC_UNAUTHORIZED, "Client not authorized");
    }
    String id = decodedCredentials.split(":")[0];
    String secret = decodedCredentials.split(":")[1];
    logger.debug("Credentials: " + id + " " + secret);
    // Verify credentials
    if (!credentials.containsKey(id)) {
        logger.error("Client id: " + id + " is not registered");
        return new ErrorResponse(0, HttpStatus.SC_UNAUTHORIZED, "Client not authorized");
    }
    if (!credentials.get(id).equals(secret)) {
        logger.error("Wrong secret: " + secret + " for client id: " + id);
        return new ErrorResponse(0, HttpStatus.SC_UNAUTHORIZED, "Client not authorized");
    }
    // Check is a token has been release for this client
    if (clientClaims.containsKey(id)) {
        // Do not return a new token if the previous one is not expired
        Date expires = clientClaims.get(id).getExpirationTime();
        Date now = new Date();
        logger.debug("Check token expiration: " + now + " > " + expires + " ?");
        if (now.before(expires)) {
            logger.warn("Token is not expired");
            return new ErrorResponse(0, HttpStatus.SC_BAD_REQUEST, "Token is not expired");
        }
    }
    // Prepare JWT with claims set
    JWTClaimsSet.Builder claimsSetBuilder = new JWTClaimsSet.Builder();
    long timestamp = new Date().getTime();
    /*
		 * 4.1.1.  "iss" (Issuer) Claim

	   The "iss" (issuer) claim identifies the principal that issued the
	   JWT.  The processing of this claim is generally application specific.
	   The "iss" value is a case-sensitive string containing a StringOrURI
	   value.  Use of this claim is OPTIONAL.*/
    claimsSetBuilder.issuer(AuthorizationManagerBeans.getIssuer());
    /* 4.1.2.  "sub" (Subject) Claim

	   The "sub" (subject) claim identifies the principal that is the
	   subject of the JWT.  The Claims in a JWT are normally statements
	   about the subject.  The subject value MUST either be scoped to be
	   locally unique in the context of the issuer or be globally unique.
	   The processing of this claim is generally application specific.  The
	   "sub" value is a case-sensitive string containing a StringOrURI
	   value.  Use of this claim is OPTIONAL.*/
    claimsSetBuilder.subject(AuthorizationManagerBeans.getSubject());
    /* 4.1.3.  "aud" (Audience) Claim

	   The "aud" (audience) claim identifies the recipients that the JWT is
	   intended for.  Each principal intended to process the JWT MUST
	   identify itself with a value in the audience claim.  If the principal
	   processing the claim does not identify itself with a value in the
	   "aud" claim when this claim is present, then the JWT MUST be
	   rejected.  In the general case, the "aud" value is an array of case-
	   sensitive strings, each containing a StringOrURI value.  In the
	   special case when the JWT has one audience, the "aud" value MAY be a
	   single case-sensitive string containing a StringOrURI value.  The
	   interpretation of audience values is generally application specific.
	   Use of this claim is OPTIONAL.*/
    ArrayList<String> audience = new ArrayList<String>();
    audience.add(AuthorizationManagerBeans.getHttpsAudience());
    audience.add(AuthorizationManagerBeans.getWssAudience());
    claimsSetBuilder.audience(audience);
    /* 4.1.4.  "exp" (Expiration Time) Claim

	   The "exp" (expiration time) claim identifies the expiration time on
	   or after which the JWT MUST NOT be accepted for processing.  The
	   processing of the "exp" claim requires that the current date/time
	   MUST be before the expiration date/time listed in the "exp" claim.
	   Implementers MAY provide for some small leeway, usually no more than
	   a few minutes, to account for clock skew.  Its value MUST be a number
	   containing a NumericDate value.  Use of this claim is OPTIONAL.*/
    claimsSetBuilder.expirationTime(new Date(timestamp + (AuthorizationManagerBeans.getTokenExpiringPeriod() * 1000)));
    /*4.1.5.  "nbf" (Not Before) Claim

	   The "nbf" (not before) claim identifies the time before which the JWT
	   MUST NOT be accepted for processing.  The processing of the "nbf"
	   claim requires that the current date/time MUST be after or equal to
	   the not-before date/time listed in the "nbf" claim.  Implementers MAY
	   provide for some small leeway, usually no more than a few minutes, to
	   account for clock skew.  Its value MUST be a number containing a
	   NumericDate value.  Use of this claim is OPTIONAL.*/
    claimsSetBuilder.notBeforeTime(new Date(timestamp - 1000));
    /* 4.1.6.  "iat" (Issued At) Claim

	   The "iat" (issued at) claim identifies the time at which the JWT was
	   issued.  This claim can be used to determine the age of the JWT.  Its
	   value MUST be a number containing a NumericDate value.  Use of this
	   claim is OPTIONAL.*/
    claimsSetBuilder.issueTime(new Date(timestamp));
    /*4.1.7.  "jti" (JWT ID) Claim

	   The "jti" (JWT ID) claim provides a unique identifier for the JWT.
	   The identifier value MUST be assigned in a manner that ensures that
	   there is a negligible probability that the same value will be
	   accidentally assigned to a different data object; if the application
	   uses multiple issuers, collisions MUST be prevented among values
	   produced by different issuers as well.  The "jti" claim can be used
	   to prevent the JWT from being replayed.  The "jti" value is a case-
	   sensitive string.  Use of this claim is OPTIONAL.*/
    claimsSetBuilder.jwtID(id + ":" + secret);
    JWTClaimsSet jwtClaims = claimsSetBuilder.build();
    // ******************************
    // Sign JWT with private RSA key
    // ******************************
    SignedJWT signedJWT;
    try {
        signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), JWTClaimsSet.parse(jwtClaims.toString()));
    } catch (ParseException e) {
        logger.error(e.getMessage());
        return new ErrorResponse(0, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Error on signing JWT (1)");
    }
    try {
        signedJWT.sign(signer);
    } catch (JOSEException e) {
        logger.error(e.getMessage());
        return new ErrorResponse(0, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Error on signing JWT (2)");
    }
    // Add the token to the released tokens
    clientClaims.put(id, jwtClaims);
    return new JWTResponse(signedJWT.serialize(), "bearer", AuthorizationManagerBeans.getTokenExpiringPeriod());
}
Also used : ArrayList(java.util.ArrayList) SignedJWT(com.nimbusds.jwt.SignedJWT) Date(java.util.Date) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) ParseException(java.text.ParseException) JOSEException(com.nimbusds.jose.JOSEException) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException) JWSHeader(com.nimbusds.jose.JWSHeader) JWTResponse(it.unibo.arces.wot.sepa.commons.response.JWTResponse)

Example 2 with JWSHeader

use of com.nimbusds.jose.JWSHeader in project ratauth by alfa-laboratory.

the class HS256TokenProcessor method createToken.

@Override
@SneakyThrows
public String createToken(String clientId, String secret, String identifier, Date created, Date expiresIn, Set<String> audience, Set<String> scopes, Collection<String> authContext, String userId, Map<String, Object> userInfo) {
    final JWSSigner signer = new MACSigner(Base64.getDecoder().decode(secret));
    final List<String> aud = new ArrayList<>(audience);
    aud.add(clientId);
    // Prepare JWT with claims set
    JWTClaimsSet.Builder jwtBuilder = new JWTClaimsSet.Builder().issuer(issuer).subject(userId).expirationTime(expiresIn).audience(aud).claim(SCOPE, scopes).claim(CLIENT_ID, clientId).claim(ACR_VALUES, authContext).jwtID(identifier).issueTime(created);
    userInfo.forEach(jwtBuilder::claim);
    SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), jwtBuilder.build());
    // Apply the HMAC protection
    signedJWT.sign(signer);
    // eyJhbGciOiJIUzI1NiJ9.SGVsbG8sIHdvcmxkIQ.onO9Ihudz3WkiauDO2Uhyuz0Y18UASXlSc1eS0NkWyA
    return signedJWT.serialize();
}
Also used : MACSigner(com.nimbusds.jose.crypto.MACSigner) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) SignedJWT(com.nimbusds.jwt.SignedJWT) JWSSigner(com.nimbusds.jose.JWSSigner) JWSHeader(com.nimbusds.jose.JWSHeader) SneakyThrows(lombok.SneakyThrows)

Example 3 with JWSHeader

use of com.nimbusds.jose.JWSHeader in project ORCID-Source by ORCID.

the class OpenIDConnectKeyService method sign.

/**
 * Get the private key for signing
 *
 * @return
 * @throws JOSEException
 */
public SignedJWT sign(JWTClaimsSet claims) throws JOSEException {
    JWSSigner signer = new RSASSASigner(privateJWK);
    JWSHeader.Builder head = new JWSHeader.Builder(defaultAlg);
    head.keyID(getDefaultKeyID());
    SignedJWT signedJWT = new SignedJWT(head.build(), claims);
    signedJWT.sign(signer);
    return signedJWT;
/* For HMAC we could do the following.  This may be useful for the implicit flow:
        ClientDetailsEntity clientEntity = clientDetailsEntityCacheManager.retrieve(authentication.getOAuth2Request().getClientId());
        JWSSigner signer = new MACSigner(StringUtils.rightPad(clientEntity.getDecryptedClientSecret(), 32, "#").getBytes());
        signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claims.build());
        signedJWT.sign(signer);     
         */
}
Also used : RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) SignedJWT(com.nimbusds.jwt.SignedJWT) JWSSigner(com.nimbusds.jose.JWSSigner) JWSHeader(com.nimbusds.jose.JWSHeader)

Example 4 with JWSHeader

use of com.nimbusds.jose.JWSHeader in project connect-android-sdk by telenordigital.

the class IdTokenValidatorTest method authorizedPartyNotEqualClientThrows.

@Test(expected = ConnectException.class)
public void authorizedPartyNotEqualClientThrows() throws Exception {
    BDDMockito.given(ConnectSdk.getConnectApiUrl()).willReturn(HttpUrl.parse("https://connect.telenordigital.com"));
    BDDMockito.given(ConnectSdk.getClientId()).willReturn("connect-tests");
    BDDMockito.given(ConnectSdk.getExpectedIssuer()).willReturn("https://connect.telenordigital.com/oauth");
    JWTClaimsSet claimsSet = new JWTClaimsSet();
    claimsSet.setIssuer("https://connect.telenordigital.com/oauth");
    claimsSet.setAudience("connect-tests");
    claimsSet.setExpirationTime(oneHourIntoFuture);
    claimsSet.setIssueTime(now);
    claimsSet.setCustomClaim("azp", "NOT connect-tests");
    SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.ES256), claimsSet);
    signedJWT.sign(new ECDSASigner(new BigInteger("123")));
    IdToken idToken = new IdToken(signedJWT.serialize());
    IdTokenValidator.validate(idToken, null);
}
Also used : IdToken(com.telenor.connect.id.IdToken) ECDSASigner(com.nimbusds.jose.crypto.ECDSASigner) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) BigInteger(java.math.BigInteger) SignedJWT(com.nimbusds.jwt.SignedJWT) JWSHeader(com.nimbusds.jose.JWSHeader) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 5 with JWSHeader

use of com.nimbusds.jose.JWSHeader in project connect-android-sdk by telenordigital.

the class IdTokenValidatorTest method missingIssueTimeThrows.

@Test(expected = ConnectException.class)
public void missingIssueTimeThrows() throws Exception {
    BDDMockito.given(ConnectSdk.getConnectApiUrl()).willReturn(HttpUrl.parse("https://connect.telenordigital.com"));
    BDDMockito.given(ConnectSdk.getClientId()).willReturn("connect-tests");
    BDDMockito.given(ConnectSdk.getExpectedIssuer()).willReturn("https://connect.telenordigital.com/oauth");
    JWTClaimsSet claimsSet = new JWTClaimsSet();
    claimsSet.setIssuer("https://connect.telenordigital.com/oauth");
    claimsSet.setAudience("connect-tests");
    claimsSet.setExpirationTime(oneHourIntoFuture);
    SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.ES256), claimsSet);
    signedJWT.sign(new ECDSASigner(new BigInteger("123")));
    IdToken idToken = new IdToken(signedJWT.serialize());
    IdTokenValidator.validate(idToken, null);
}
Also used : IdToken(com.telenor.connect.id.IdToken) ECDSASigner(com.nimbusds.jose.crypto.ECDSASigner) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) BigInteger(java.math.BigInteger) SignedJWT(com.nimbusds.jwt.SignedJWT) JWSHeader(com.nimbusds.jose.JWSHeader) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

JWSHeader (com.nimbusds.jose.JWSHeader)27 SignedJWT (com.nimbusds.jwt.SignedJWT)21 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)17 RSASSASigner (com.nimbusds.jose.crypto.RSASSASigner)12 JWSSigner (com.nimbusds.jose.JWSSigner)11 JOSEException (com.nimbusds.jose.JOSEException)8 Test (org.junit.jupiter.api.Test)8 MockWebServer (okhttp3.mockwebserver.MockWebServer)6 MACSigner (com.nimbusds.jose.crypto.MACSigner)5 Date (java.util.Date)5 JWSObject (com.nimbusds.jose.JWSObject)4 Payload (com.nimbusds.jose.Payload)4 JSONObject (net.minidev.json.JSONObject)4 MockResponse (okhttp3.mockwebserver.MockResponse)4 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)4 JOSEObjectType (com.nimbusds.jose.JOSEObjectType)3 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)3 ECDSASigner (com.nimbusds.jose.crypto.ECDSASigner)3 JWK (com.nimbusds.jose.jwk.JWK)3 BadJOSEException (com.nimbusds.jose.proc.BadJOSEException)3