use of org.gluu.oxauth.model.jwt.Jwt in project oxAuth by GluuFederation.
the class ProvidingIdTokenWithEssentialAuthTimeClaim method providingIdTokenWithEssentialAuthTimeClaim.
@Parameters({ "userId", "userSecret", "redirectUri", "redirectUris", "dnName", "keyStoreFile", "keyStoreSecret", "sectorIdentifierUri" })
@Test
public void providingIdTokenWithEssentialAuthTimeClaim(final String userId, final String userSecret, final String redirectUri, final String redirectUris, final String dnName, final String keyStoreFile, final String keyStoreSecret, final String sectorIdentifierUri) throws Exception {
showTitle("OC5:FeatureTest-Providing ID Token with Essential auth time Claim");
List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN, ResponseType.ID_TOKEN);
// 1. Register client
RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app", StringUtils.spaceSeparatedToList(redirectUris));
registerRequest.setResponseTypes(responseTypes);
registerRequest.setSectorIdentifierUri(sectorIdentifierUri);
RegisterClient registerClient = new RegisterClient(registrationEndpoint);
registerClient.setRequest(registerRequest);
RegisterResponse registerResponse = registerClient.exec();
showClient(registerClient);
assertEquals(registerResponse.getStatus(), 200, "Unexpected response code: " + registerResponse.getEntity());
assertNotNull(registerResponse.getClientId());
assertNotNull(registerResponse.getClientSecret());
assertNotNull(registerResponse.getRegistrationAccessToken());
assertNotNull(registerResponse.getClientIdIssuedAt());
assertNotNull(registerResponse.getClientSecretExpiresAt());
String clientId = registerResponse.getClientId();
String clientSecret = registerResponse.getClientSecret();
// 2. Request authorization
OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);
List<String> scopes = Arrays.asList("openid");
String nonce = UUID.randomUUID().toString();
String state = UUID.randomUUID().toString();
AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce);
authorizationRequest.setState(state);
JwtAuthorizationRequest jwtAuthorizationRequest = new JwtAuthorizationRequest(authorizationRequest, SignatureAlgorithm.HS256, clientSecret, cryptoProvider);
jwtAuthorizationRequest.addIdTokenClaim(new Claim(JwtClaimName.AUTHENTICATION_TIME, ClaimValue.createEssential(true)));
String authJwt = jwtAuthorizationRequest.getEncodedJwt();
authorizationRequest.setRequest(authJwt);
AuthorizeClient authorizeClient = new AuthorizeClient(authorizationEndpoint);
authorizeClient.setRequest(authorizationRequest);
AuthorizationResponse authorizationResponse = authenticateResourceOwnerAndGrantAccess(authorizationEndpoint, authorizationRequest, userId, userSecret);
assertNotNull(authorizationResponse.getLocation(), "The location is null");
assertNotNull(authorizationResponse.getAccessToken(), "The accessToken is null");
assertNotNull(authorizationResponse.getTokenType(), "The tokenType is null");
assertNotNull(authorizationResponse.getIdToken(), "The idToken is null");
assertNotNull(authorizationResponse.getState(), "The state is null");
String idToken = authorizationResponse.getIdToken();
String accessToken = authorizationResponse.getAccessToken();
// 3. Validate id_token
Jwt jwt = Jwt.parse(idToken);
assertNotNull(jwt.getHeader().getClaimAsString(JwtHeaderName.TYPE));
assertNotNull(jwt.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM));
assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.ISSUER));
assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.AUDIENCE));
assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.EXPIRATION_TIME));
assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.ISSUED_AT));
assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.SUBJECT_IDENTIFIER));
assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.ACCESS_TOKEN_HASH));
assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.AUTHENTICATION_TIME));
RSAPublicKey publicKey = JwkClient.getRSAPublicKey(jwksUri, jwt.getHeader().getClaimAsString(JwtHeaderName.KEY_ID));
RSASigner rsaSigner = new RSASigner(SignatureAlgorithm.RS256, publicKey);
assertTrue(rsaSigner.validate(jwt));
}
use of org.gluu.oxauth.model.jwt.Jwt in project oxAuth by GluuFederation.
the class UmaTokenService method requestRpt.
public Response requestRpt(String grantType, String ticket, String claimToken, String claimTokenFormat, String pctCode, String rptCode, String scope, HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
try {
log.trace("requestRpt grant_type: {}, ticket: {}, claim_token: {}, claim_token_format: {}, pct: {}, rpt: {}, scope: {}", grantType, ticket, claimToken, claimTokenFormat, pctCode, rptCode, scope);
umaValidationService.validateGrantType(grantType);
List<UmaPermission> permissions = umaValidationService.validateTicket(ticket);
Jwt idToken = umaValidationService.validateClaimToken(claimToken, claimTokenFormat);
UmaPCT pct = umaValidationService.validatePct(pctCode);
UmaRPT rpt = umaValidationService.validateRPT(rptCode);
Client client = umaValidationService.validate(identity.getSessionClient().getClient());
Map<Scope, Boolean> scopes = umaValidationService.validateScopes(scope, permissions, client);
// creates new pct if pct is null in request
pct = pctService.updateClaims(pct, idToken, client.getClientId(), permissions);
Claims claims = new Claims(idToken, pct, claimToken);
Map<UmaScriptByScope, UmaAuthorizationContext> scriptMap = umaNeedsInfoService.checkNeedsInfo(claims, scopes, permissions, pct, httpRequest, client);
if (!scriptMap.isEmpty()) {
expressionService.evaluate(scriptMap, permissions);
} else {
log.warn("There are no any policies that protects scopes. Scopes: " + UmaScopeService.asString(scopes.keySet()) + ". Configuration property umaGrantAccessIfNoPolicies: " + appConfiguration.getUmaGrantAccessIfNoPolicies());
if (appConfiguration.getUmaGrantAccessIfNoPolicies() != null && appConfiguration.getUmaGrantAccessIfNoPolicies()) {
log.warn("Access granted because there are no any protection. Make sure it is intentional behavior.");
} else {
log.warn("Access denied because there are no any protection. Make sure it is intentional behavior.");
throw errorResponseFactory.createWebApplicationException(Response.Status.FORBIDDEN, UmaErrorResponseType.FORBIDDEN_BY_POLICY, "Access denied because there are no any protection. Make sure it is intentional behavior.");
}
}
log.trace("Access granted.");
updatePermissionsWithClientRequestedScope(permissions, scopes);
addPctToPermissions(permissions, pct);
boolean upgraded = false;
if (rpt == null) {
ExecutionContext executionContext = new ExecutionContext(httpRequest, httpResponse);
executionContext.setClient(client);
rpt = rptService.createRPTAndPersist(executionContext, permissions);
rptCode = rpt.getNotHashedCode();
} else if (rptService.addPermissionToRPT(rpt, permissions)) {
upgraded = true;
}
UmaTokenResponse response = new UmaTokenResponse();
response.setAccessToken(rptCode);
response.setUpgraded(upgraded);
response.setTokenType("Bearer");
response.setPct(pct.getCode());
return Response.ok(ServerUtil.asJson(response)).build();
} catch (Exception ex) {
log.error("Exception happened", ex);
if (ex instanceof WebApplicationException) {
throw (WebApplicationException) ex;
}
}
log.error("Failed to handle request to UMA Token Endpoint.");
throw errorResponseFactory.createWebApplicationException(Response.Status.INTERNAL_SERVER_ERROR, UmaErrorResponseType.SERVER_ERROR, "Failed to handle request to UMA Token Endpoint.");
}
use of org.gluu.oxauth.model.jwt.Jwt in project oxAuth by GluuFederation.
the class UmaRptService method createRptJwt.
private String createRptJwt(ExecutionContext executionContext, List<UmaPermission> permissions, Date creationDate, Date expirationDate) throws Exception {
Client client = executionContext.getClient();
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.fromString(appConfiguration.getDefaultSignatureAlgorithm());
if (client.getAccessTokenSigningAlg() != null && SignatureAlgorithm.fromString(client.getAccessTokenSigningAlg()) != null) {
signatureAlgorithm = SignatureAlgorithm.fromString(client.getAccessTokenSigningAlg());
}
final JwtSigner jwtSigner = new JwtSigner(appConfiguration, webKeysConfiguration, signatureAlgorithm, client.getClientId(), clientService.decryptSecret(client.getClientSecret()));
final Jwt jwt = jwtSigner.newJwt();
jwt.getClaims().setClaim("client_id", client.getClientId());
jwt.getClaims().setExpirationTime(expirationDate);
jwt.getClaims().setIssuedAt(creationDate);
Audience.setAudience(jwt.getClaims(), client);
if (permissions != null && !permissions.isEmpty()) {
String pctCode = permissions.iterator().next().getAttributes().get(UmaPermission.PCT);
if (StringHelper.isNotEmpty(pctCode)) {
UmaPCT pct = pctService.getByCode(pctCode);
if (pct != null) {
jwt.getClaims().setClaim("pct_claims", pct.getClaims().toJsonObject());
} else {
log.error("Failed to find PCT with code: " + pctCode + " which is taken from permission object: " + permissions.iterator().next().getDn());
}
}
jwt.getClaims().setClaim("permissions", buildPermissionsJSONObject(permissions));
}
runScriptAndInjectValuesIntoJwt(jwt, executionContext);
return jwtSigner.sign().toString();
}
use of org.gluu.oxauth.model.jwt.Jwt in project oxAuth by GluuFederation.
the class UserInfoClient method exec.
/**
* Executes the call to the REST Service and processes the response.
*
* @return The service response.
*/
public UserInfoResponse exec() {
// Prepare request parameters
initClientRequest();
Builder clientRequest = null;
if (getRequest().getAuthorizationMethod() == null || getRequest().getAuthorizationMethod() == AuthorizationMethod.AUTHORIZATION_REQUEST_HEADER_FIELD) {
if (StringUtils.isNotBlank(getRequest().getAccessToken())) {
clientRequest = webTarget.request();
clientRequest.header("Authorization", "Bearer " + getRequest().getAccessToken());
}
} else if (getRequest().getAuthorizationMethod() == AuthorizationMethod.FORM_ENCODED_BODY_PARAMETER) {
if (StringUtils.isNotBlank(getRequest().getAccessToken())) {
requestForm.param("access_token", getRequest().getAccessToken());
}
} else if (getRequest().getAuthorizationMethod() == AuthorizationMethod.URL_QUERY_PARAMETER) {
if (StringUtils.isNotBlank(getRequest().getAccessToken())) {
addReqParam("access_token", getRequest().getAccessToken().toString());
}
}
if (clientRequest == null) {
clientRequest = webTarget.request();
}
clientRequest.header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
// Call REST Service and handle response
try {
if (getRequest().getAuthorizationMethod() == null || getRequest().getAuthorizationMethod() == AuthorizationMethod.AUTHORIZATION_REQUEST_HEADER_FIELD || getRequest().getAuthorizationMethod() == AuthorizationMethod.URL_QUERY_PARAMETER) {
clientResponse = clientRequest.buildGet().invoke();
} else if (getRequest().getAuthorizationMethod() == AuthorizationMethod.FORM_ENCODED_BODY_PARAMETER) {
clientResponse = clientRequest.buildPost(Entity.form(requestForm)).invoke();
}
int status = clientResponse.getStatus();
setResponse(new UserInfoResponse(status));
String entity = clientResponse.readEntity(String.class);
getResponse().setEntity(entity);
getResponse().setHeaders(clientResponse.getMetadata());
if (StringUtils.isNotBlank(entity)) {
List<Object> contentType = clientResponse.getHeaders().get("Content-Type");
if (contentType != null && contentType.contains("application/jwt")) {
String[] jwtParts = entity.split("\\.");
if (jwtParts.length == 5) {
byte[] sharedSymmetricKey = sharedKey != null ? sharedKey.getBytes(Util.UTF8_STRING_ENCODING) : null;
Jwe jwe = Jwe.parse(entity, privateKey, sharedSymmetricKey);
getResponse().setClaims(jwe.getClaims().toMap());
} else {
Jwt jwt = Jwt.parse(entity);
OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider();
boolean signatureVerified = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(), jwt.getHeader().getKeyId(), JwtUtil.getJSONWebKeys(jwksUri), sharedKey, jwt.getHeader().getSignatureAlgorithm());
if (signatureVerified) {
getResponse().setClaims(jwt.getClaims().toMap());
}
}
} else {
try {
JSONObject jsonObj = new JSONObject(entity);
if (jsonObj.has("error")) {
getResponse().setErrorType(UserInfoErrorResponseType.fromString(jsonObj.getString("error")));
jsonObj.remove("error");
}
if (jsonObj.has("error_description")) {
getResponse().setErrorDescription(jsonObj.getString("error_description"));
jsonObj.remove("error_description");
}
if (jsonObj.has("error_uri")) {
getResponse().setErrorUri(jsonObj.getString("error_uri"));
jsonObj.remove("error_uri");
}
for (Iterator<String> iterator = jsonObj.keys(); iterator.hasNext(); ) {
String key = iterator.next();
List<String> values = new ArrayList<String>();
JSONArray jsonArray = jsonObj.optJSONArray(key);
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
String value = jsonArray.optString(i);
if (value != null) {
values.add(value);
}
}
} else {
String value = jsonObj.optString(key);
if (value != null) {
values.add(value);
}
}
getResponse().getClaims().put(key, values);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection();
}
return getResponse();
}
use of org.gluu.oxauth.model.jwt.Jwt in project oxAuth by GluuFederation.
the class ClientAuthnRequest method getClientAssertion.
public String getClientAssertion() {
if (cryptoProvider == null) {
LOG.error("Crypto provider is not specified");
return null;
}
if (algorithm == null) {
algorithm = SignatureAlgorithm.HS256;
}
GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
Date issuedAt = calendar.getTime();
calendar.add(Calendar.MINUTE, 5);
Date expirationTime = calendar.getTime();
Jwt clientAssertion = new Jwt();
// Header
clientAssertion.getHeader().setType(JwtType.JWT);
clientAssertion.getHeader().setAlgorithm(algorithm);
if (StringUtils.isNotBlank(keyId)) {
clientAssertion.getHeader().setKeyId(keyId);
}
// Claims
clientAssertion.getClaims().setIssuer(getAuthUsername());
clientAssertion.getClaims().setSubjectIdentifier(getAuthUsername());
clientAssertion.getClaims().setAudience(audience);
clientAssertion.getClaims().setJwtId(UUID.randomUUID());
clientAssertion.getClaims().setExpirationTime(expirationTime);
clientAssertion.getClaims().setIssuedAt(issuedAt);
// Signature
try {
if (sharedKey == null) {
sharedKey = getAuthPassword();
}
String signature = cryptoProvider.sign(clientAssertion.getSigningInput(), keyId, sharedKey, algorithm);
clientAssertion.setEncodedSignature(signature);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
return clientAssertion.toString();
}
Aggregations