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());
}
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();
}
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);
*/
}
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);
}
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);
}
Aggregations