use of org.gluu.oxauth.model.exception.InvalidJwtException in project oxAuth by GluuFederation.
the class UserInfoRestWebServiceEmbeddedTest method requestUserInfoHS384Step3.
@Parameters({ "userInfoPath" })
@Test(dependsOnMethods = "requestUserInfoHS384Step2")
public void requestUserInfoHS384Step3(final String userInfoPath) throws Exception {
Builder request = ResteasyClientBuilder.newClient().target(url.toString() + userInfoPath).request();
request.header("Authorization", "Bearer " + accessToken6);
UserInfoRequest userInfoRequest = new UserInfoRequest(null);
Response response = request.post(Entity.form(new MultivaluedHashMap<String, String>(userInfoRequest.getParameters())));
String entity = response.readEntity(String.class);
showResponse("requestUserInfoHS384Step3", response, entity);
assertEquals(response.getStatus(), 200, "Unexpected response code.");
assertTrue(response.getHeaderString("Cache-Control") != null && response.getHeaderString("Cache-Control").equals("no-store, private"), "Unexpected result: " + response.getHeaderString("Cache-Control"));
assertTrue(response.getHeaderString("Pragma") != null && response.getHeaderString("Pragma").equals("no-cache"), "Unexpected result: " + response.getHeaderString("Pragma"));
assertNotNull(entity, "Unexpected result: " + entity);
try {
Jwt jwt = Jwt.parse(entity);
assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.SUBJECT_IDENTIFIER));
assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.NAME));
assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.EMAIL));
assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.PICTURE));
} catch (InvalidJwtException e) {
e.printStackTrace();
fail(e.getMessage() + "\nResponse was: " + entity);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
use of org.gluu.oxauth.model.exception.InvalidJwtException in project oxAuth by GluuFederation.
the class RegisterRestWebServiceImpl method validateSoftwareStatement.
private JSONObject validateSoftwareStatement(HttpServletRequest httpServletRequest, JSONObject requestObject) {
if (!requestObject.has(SOFTWARE_STATEMENT.toString())) {
return null;
}
try {
Jwt softwareStatement = Jwt.parse(requestObject.getString(SOFTWARE_STATEMENT.toString()));
final SignatureAlgorithm signatureAlgorithm = softwareStatement.getHeader().getSignatureAlgorithm();
final SoftwareStatementValidationType validationType = SoftwareStatementValidationType.fromString(appConfiguration.getSoftwareStatementValidationType());
if (validationType == SoftwareStatementValidationType.NONE) {
log.trace("software_statement validation was skipped due to `softwareStatementValidationType` configuration property set to none. (Not recommended.)");
return softwareStatement.getClaims().toJsonObject();
}
if (validationType == SoftwareStatementValidationType.SCRIPT) {
if (!externalDynamicClientRegistrationService.isEnabled()) {
log.error("Server is mis-configured. softwareStatementValidationType=script but there is no any Dynamic Client Registration script enabled.");
return null;
}
if (AlgorithmFamily.HMAC.equals(signatureAlgorithm.getFamily())) {
final String hmacSecret = externalDynamicClientRegistrationService.getSoftwareStatementHmacSecret(httpServletRequest, requestObject, softwareStatement);
if (StringUtils.isBlank(hmacSecret)) {
log.error("No hmacSecret provided in Dynamic Client Registration script (method getSoftwareStatementHmacSecret didn't return actual secret). ");
throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.INVALID_SOFTWARE_STATEMENT, "");
}
if (!cryptoProvider.verifySignature(softwareStatement.getSigningInput(), softwareStatement.getEncodedSignature(), null, null, hmacSecret, signatureAlgorithm)) {
throw new InvalidJwtException("Invalid signature in the software statement");
}
return softwareStatement.getClaims().toJsonObject();
}
final JSONObject softwareStatementJwks = externalDynamicClientRegistrationService.getSoftwareStatementJwks(httpServletRequest, requestObject, softwareStatement);
if (softwareStatementJwks == null) {
log.error("No jwks provided in Dynamic Client Registration script (method getSoftwareStatementJwks didn't return actual jwks). ");
throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.INVALID_SOFTWARE_STATEMENT, "");
}
if (!cryptoProvider.verifySignature(softwareStatement.getSigningInput(), softwareStatement.getEncodedSignature(), softwareStatement.getHeader().getKeyId(), softwareStatementJwks, null, signatureAlgorithm)) {
throw new InvalidJwtException("Invalid signature in the software statement");
}
return softwareStatement.getClaims().toJsonObject();
}
if ((validationType == SoftwareStatementValidationType.JWKS_URI || validationType == SoftwareStatementValidationType.JWKS) && StringUtils.isBlank(appConfiguration.getSoftwareStatementValidationClaimName())) {
log.error("softwareStatementValidationClaimName configuration property is not specified. Please specify claim name from software_statement which points to jwks (or jwks_uri).");
throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.INVALID_SOFTWARE_STATEMENT, "Failed to validate software statement");
}
String jwksUriClaim = null;
if (validationType == SoftwareStatementValidationType.JWKS_URI) {
jwksUriClaim = softwareStatement.getClaims().getClaimAsString(appConfiguration.getSoftwareStatementValidationClaimName());
}
String jwksClaim = null;
if (validationType == SoftwareStatementValidationType.JWKS) {
jwksClaim = softwareStatement.getClaims().getClaimAsString(appConfiguration.getSoftwareStatementValidationClaimName());
}
if (StringUtils.isBlank(jwksUriClaim) && StringUtils.isBlank(jwksClaim)) {
final String msg = String.format("software_statement does not contain `%s` claim and thus is considered as invalid.", appConfiguration.getSoftwareStatementValidationClaimName());
log.error(msg);
throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.INVALID_SOFTWARE_STATEMENT, msg);
}
JSONObject jwks = Strings.isNullOrEmpty(jwksUriClaim) ? new JSONObject(jwksClaim) : JwtUtil.getJSONWebKeys(jwksUriClaim);
boolean validSignature = cryptoProvider.verifySignature(softwareStatement.getSigningInput(), softwareStatement.getEncodedSignature(), softwareStatement.getHeader().getKeyId(), jwks, null, signatureAlgorithm);
if (!validSignature) {
throw new InvalidJwtException("Invalid cryptographic segment in the software statement");
}
return softwareStatement.getClaims().toJsonObject();
} catch (Exception e) {
final String msg = "Invalid software_statement.";
log.error(msg, e);
throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.INVALID_SOFTWARE_STATEMENT, msg);
}
}
use of org.gluu.oxauth.model.exception.InvalidJwtException in project oxAuth by GluuFederation.
the class ClientAssertion method load.
private boolean load(AppConfiguration appConfiguration, AbstractCryptoProvider cryptoProvider, String clientId, ClientAssertionType clientAssertionType, String encodedAssertion) throws Exception {
boolean result;
if (clientAssertionType == ClientAssertionType.JWT_BEARER) {
if (StringUtils.isNotBlank(encodedAssertion)) {
jwt = Jwt.parse(encodedAssertion);
// TODO: Store jti this value to check for duplicates
// Validate clientId
String issuer = jwt.getClaims().getClaimAsString(JwtClaimName.ISSUER);
String subject = jwt.getClaims().getClaimAsString(JwtClaimName.SUBJECT_IDENTIFIER);
List<String> audience = jwt.getClaims().getClaimAsStringList(JwtClaimName.AUDIENCE);
Date expirationTime = jwt.getClaims().getClaimAsDate(JwtClaimName.EXPIRATION_TIME);
// SignatureAlgorithm algorithm = SignatureAlgorithm.fromName(jwt.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM));
if ((clientId == null && StringUtils.isNotBlank(issuer) && StringUtils.isNotBlank(subject) && issuer.equals(subject)) || (StringUtils.isNotBlank(clientId) && StringUtils.isNotBlank(issuer) && StringUtils.isNotBlank(subject) && clientId.equals(issuer) && issuer.equals(subject))) {
// Validate audience
String tokenUrl = appConfiguration.getTokenEndpoint();
String cibaAuthUrl = appConfiguration.getBackchannelAuthenticationEndpoint();
if (audience != null && (audience.contains(appConfiguration.getIssuer()) || audience.contains(tokenUrl) || audience.contains(cibaAuthUrl))) {
// Validate expiration
if (expirationTime.after(new Date())) {
ClientService clientService = CdiUtil.bean(ClientService.class);
Client client = clientService.getClient(subject);
// Validate client
if (client != null) {
JwtType jwtType = JwtType.fromString(jwt.getHeader().getClaimAsString(JwtHeaderName.TYPE));
AuthenticationMethod authenticationMethod = client.getAuthenticationMethod();
SignatureAlgorithm signatureAlgorithm = jwt.getHeader().getSignatureAlgorithm();
if (jwtType == null && signatureAlgorithm != null) {
jwtType = signatureAlgorithm.getJwtType();
}
if (jwtType != null && signatureAlgorithm != null && signatureAlgorithm.getFamily() != null && ((authenticationMethod == AuthenticationMethod.CLIENT_SECRET_JWT && AlgorithmFamily.HMAC.equals(signatureAlgorithm.getFamily())) || (authenticationMethod == AuthenticationMethod.PRIVATE_KEY_JWT && (AlgorithmFamily.RSA.equals(signatureAlgorithm.getFamily()) || AlgorithmFamily.EC.equals(signatureAlgorithm.getFamily()))))) {
if (client.getTokenEndpointAuthSigningAlg() == null || SignatureAlgorithm.fromString(client.getTokenEndpointAuthSigningAlg()).equals(signatureAlgorithm)) {
clientSecret = clientService.decryptSecret(client.getClientSecret());
// Validate the crypto segment
String keyId = jwt.getHeader().getKeyId();
JSONObject jwks = Strings.isNullOrEmpty(client.getJwks()) ? JwtUtil.getJSONWebKeys(client.getJwksUri()) : new JSONObject(client.getJwks());
String sharedSecret = clientService.decryptSecret(client.getClientSecret());
boolean validSignature = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(), keyId, jwks, sharedSecret, signatureAlgorithm);
if (validSignature) {
result = true;
} else {
throw new InvalidJwtException("Invalid cryptographic segment");
}
} else {
throw new InvalidJwtException("Invalid signing algorithm");
}
} else {
throw new InvalidJwtException("Invalid authentication method");
}
} else {
throw new InvalidJwtException("Invalid client");
}
} else {
throw new InvalidJwtException("JWT has expired");
}
} else {
throw new InvalidJwtException("Invalid audience: " + audience);
}
} else {
throw new InvalidJwtException("Invalid clientId");
}
} else {
throw new InvalidJwtException("The Client Assertion is null or empty");
}
} else {
throw new InvalidJwtException("Invalid Client Assertion Type");
}
return result;
}
use of org.gluu.oxauth.model.exception.InvalidJwtException in project oxTrust by GluuFederation.
the class Authenticator method requestAccessToken.
private String requestAccessToken(String oxAuthHost, String authorizationCode, String sessionState, String scopes, String clientID, String clientPassword) {
OpenIdConfigurationResponse openIdConfiguration = openIdService.getOpenIdConfiguration();
// 1. Request access token using the authorization code.
TokenClient tokenClient1 = new TokenClient(openIdConfiguration.getTokenEndpoint());
TokenResponse tokenResponse = tokenClient1.execAuthorizationCode(authorizationCode, appConfiguration.getLoginRedirectUrl(), clientID, clientPassword);
log.debug(" tokenResponse : " + tokenResponse);
if (tokenResponse == null) {
log.error("Get empty token response. User rcan't log into application");
return OxTrustConstants.RESULT_NO_PERMISSIONS;
}
log.debug(" tokenResponse.getErrorType() : " + tokenResponse.getErrorType());
String accessToken = tokenResponse.getAccessToken();
log.debug(" accessToken : " + accessToken);
String idToken = tokenResponse.getIdToken();
log.debug(" idToken : " + idToken);
if (idToken == null) {
log.error("Failed to get id_token");
return OxTrustConstants.RESULT_NO_PERMISSIONS;
}
log.info("Session validation successful. User is logged in");
UserInfoClient userInfoClient = new UserInfoClient(openIdConfiguration.getUserInfoEndpoint());
UserInfoResponse userInfoResponse = userInfoClient.execUserInfo(accessToken);
if (userInfoResponse == null) {
log.error("Get empty token response. User can't log into application");
return OxTrustConstants.RESULT_NO_PERMISSIONS;
}
// Parse JWT
Jwt jwt;
try {
jwt = Jwt.parse(idToken);
} catch (InvalidJwtException ex) {
log.error("Failed to parse id_token");
return OxTrustConstants.RESULT_NO_PERMISSIONS;
}
// Check nonce
if (!StringHelper.equals((String) identity.getSessionMap().get(OxTrustConstants.OXAUTH_NONCE), (String) jwt.getClaims().getClaim(JwtClaimName.NONCE))) {
log.error("User info response : nonce is not matching.");
return OxTrustConstants.RESULT_NO_PERMISSIONS;
}
// Determine uid
List<String> uidValues = userInfoResponse.getClaims().get(JwtClaimName.USER_NAME);
if ((uidValues == null) || (uidValues.size() == 0)) {
log.error("User info response doesn't contains uid claim");
return OxTrustConstants.RESULT_NO_PERMISSIONS;
}
// Check requested authentication method
if (identity.getSessionMap().containsKey(OxTrustConstants.OXAUTH_ACR_VALUES)) {
String requestAcrValues = (String) identity.getSessionMap().get(OxTrustConstants.OXAUTH_ACR_VALUES);
String issuer = openIdConfiguration.getIssuer();
String responseIssuer = (String) jwt.getClaims().getClaim(JwtClaimName.ISSUER);
if (issuer == null || responseIssuer == null || !issuer.equals(responseIssuer)) {
log.error("User info response : Issuer.");
return OxTrustConstants.RESULT_NO_PERMISSIONS;
}
List<String> acrLevels = jwt.getClaims().getClaimAsStringList(JwtClaimName.AUTHENTICATION_METHOD_REFERENCES);
if ((acrLevels == null) || (acrLevels.size() == 0)) {
log.error("User info response doesn't contains acr claim");
return OxTrustConstants.RESULT_NO_PERMISSIONS;
}
int currentAcrLevel = 0;
if (requestAcrValues.equalsIgnoreCase(OxTrustConstants.SCRIPT_TYPE_INTERNAL_RESERVED_NAME)) {
currentAcrLevel = -1;
} else {
currentAcrLevel = customScriptService.getScriptLevel(customScriptService.getScriptByDisplayName(requestAcrValues));
}
if (currentAcrLevel > Integer.valueOf(acrLevels.get(0))) {
log.error("User info response doesn't contains acr claim");
return OxTrustConstants.RESULT_NO_PERMISSIONS;
}
}
OauthData oauthData = identity.getOauthData();
oauthData.setHost(oxAuthHost);
oauthData.setUserUid(uidValues.get(0));
oauthData.setAccessToken(accessToken);
oauthData.setAccessTokenExpirationInSeconds(tokenResponse.getExpiresIn());
oauthData.setScopes(scopes);
oauthData.setIdToken(idToken);
oauthData.setSessionState(sessionState);
identity.setWorkingParameter(OxTrustConstants.OXAUTH_SSO_SESSION_STATE, Boolean.FALSE);
log.info("user uid:" + oauthData.getUserUid());
return authenticate();
}
use of org.gluu.oxauth.model.exception.InvalidJwtException in project oxTrust by GluuFederation.
the class OpenIdClient method getUserProfile.
@Override
public UserProfile getUserProfile(final OpenIdCredentials credential, final WebContext context) {
init();
try {
// Request access token using the authorization code
logger.debug("Getting access token");
final TokenClient tokenClient = new TokenClient(this.openIdConfiguration.getTokenEndpoint());
final TokenResponse tokenResponse = tokenClient.execAuthorizationCode(credential.getAuthorizationCode(), this.appConfiguration.getOpenIdRedirectUrl(), this.clientId, this.clientSecret);
logger.trace("tokenResponse.getStatus(): '{}'", tokenResponse.getStatus());
logger.trace("tokenResponse.getErrorType(): '{}'", tokenResponse.getErrorType());
final String accessToken = tokenResponse.getAccessToken();
logger.trace("accessToken : " + accessToken);
final String idToken = tokenResponse.getIdToken();
logger.trace("idToken : " + idToken);
// Store id_token in session
context.setSessionAttribute(getName() + SESSION_ID_TOKEN_PARAMETER, idToken);
// Parse JWT
Jwt jwt;
try {
jwt = Jwt.parse(idToken);
} catch (InvalidJwtException ex) {
logger.error("Failed to parse id_token: {}", idToken);
throw new CommunicationException("Failed to parse id_token");
}
final UserInfoResponse userInfoResponse = getUserInfo(accessToken);
final UserProfile profile = retrieveUserProfileFromUserInfoResponse(context, jwt, userInfoResponse);
logger.debug("User profile: '{}'", profile);
return profile;
} catch (final Exception ex) {
throw new CommunicationException(ex);
}
}
Aggregations