use of org.forgerock.oauth2.core.OAuth2ProviderSettings in project OpenAM by OpenRock.
the class OpenAMTokenStore method createOpenIDToken.
/**
* {@inheritDoc}
*/
public OpenIdConnectToken createOpenIDToken(ResourceOwner resourceOwner, String clientId, String authorizationParty, String nonce, String ops, OAuth2Request request) throws ServerException, InvalidClientException, NotFoundException {
final OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
OAuth2Uris oAuth2Uris = oauth2UrisFactory.get(request);
final OpenIdConnectClientRegistration clientRegistration = clientRegistrationStore.get(clientId, request);
final String algorithm = clientRegistration.getIDTokenSignedResponseAlgorithm();
final long currentTimeInSeconds = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
final long exp = TimeUnit.MILLISECONDS.toSeconds(clientRegistration.getJwtTokenLifeTime(providerSettings)) + currentTimeInSeconds;
final String realm = realmNormaliser.normalise(request.<String>getParameter(REALM));
final String iss = oAuth2Uris.getIssuer();
final List<String> amr = getAMRFromAuthModules(request, providerSettings);
final byte[] clientSecret = clientRegistration.getClientSecret().getBytes(Utils.CHARSET);
final KeyPair keyPair = providerSettings.getServerKeyPair();
final String atHash = generateAtHash(algorithm, request, providerSettings);
final String cHash = generateCHash(algorithm, request, providerSettings);
final String acr = getAuthenticationContextClassReference(request);
final String kid = generateKid(providerSettings.getJWKSet(), algorithm);
final String opsId = UUID.randomUUID().toString();
final long authTime = resourceOwner.getAuthTime();
final String subId = clientRegistration.getSubValue(resourceOwner.getId(), providerSettings);
try {
tokenStore.create(json(object(field(OAuth2Constants.CoreTokenParams.ID, set(opsId)), field(OAuth2Constants.JWTTokenParams.LEGACY_OPS, set(ops)), field(OAuth2Constants.CoreTokenParams.EXPIRE_TIME, set(Long.toString(TimeUnit.SECONDS.toMillis(exp)))))));
} catch (CoreTokenException e) {
logger.error("Unable to create id_token user session token", e);
throw new ServerException("Could not create token in CTS");
}
final OpenAMOpenIdConnectToken oidcToken = new OpenAMOpenIdConnectToken(kid, clientSecret, keyPair, algorithm, iss, subId, clientId, authorizationParty, exp, currentTimeInSeconds, authTime, nonce, opsId, atHash, cHash, acr, amr, realm);
request.setSession(ops);
//See spec section 5.4. - add claims to id_token based on 'response_type' parameter
String responseType = request.getParameter(OAuth2Constants.Params.RESPONSE_TYPE);
if (providerSettings.isAlwaysAddClaimsToToken() || (responseType != null && responseType.trim().equals(OAuth2Constants.JWTTokenParams.ID_TOKEN))) {
appendIdTokenClaims(request, providerSettings, oidcToken);
} else if (providerSettings.getClaimsParameterSupported()) {
appendRequestedIdTokenClaims(request, providerSettings, oidcToken);
}
return oidcToken;
}
use of org.forgerock.oauth2.core.OAuth2ProviderSettings in project OpenAM by OpenRock.
the class OpenAMTokenStore method generateHash.
/**
* Generates hash values, by hashing the valueToEncode using the requests's "alg"
* parameter, then returning the base64url encoding of the
* leftmost half of the returned bytes. Used for both at_hash and c_hash claims.
*/
private String generateHash(String algorithm, String valueToEncode, OAuth2ProviderSettings providerSettings) throws ServerException {
if (!providerSettings.getSupportedIDTokenSigningAlgorithms().contains(algorithm)) {
logger.message("Unsupported signing algorithm requested for hash value.");
return null;
}
final JwsAlgorithm alg = JwsAlgorithm.valueOf(algorithm);
MessageDigest digest;
try {
digest = MessageDigest.getInstance(alg.getMdAlgorithm());
} catch (NoSuchAlgorithmException e) {
logger.message("Unsupported signing algorithm chosen for hashing.");
throw new ServerException("Algorithm not supported.");
}
final byte[] result = digest.digest(valueToEncode.getBytes(Utils.CHARSET));
final byte[] toEncode = Arrays.copyOfRange(result, 0, result.length / 2);
return Base64url.encode(toEncode);
}
use of org.forgerock.oauth2.core.OAuth2ProviderSettings in project OpenAM by OpenRock.
the class OpenAMTokenStore method appendRequestedIdTokenClaims.
//See spec section 5.5. - add claims to id_token based on 'claims' parameter in the access token
private void appendRequestedIdTokenClaims(OAuth2Request request, OAuth2ProviderSettings providerSettings, OpenAMOpenIdConnectToken oidcToken) throws ServerException, NotFoundException, InvalidClientException {
AccessToken accessToken = request.getToken(AccessToken.class);
String claims;
if (accessToken != null) {
claims = (String) accessToken.toMap().get(OAuth2Constants.Custom.CLAIMS);
} else {
claims = request.getParameter(OAuth2Constants.Custom.CLAIMS);
}
if (claims != null) {
try {
JSONObject claimsObject = new JSONObject(claims);
JSONObject idTokenClaimsRequest = claimsObject.getJSONObject(OAuth2Constants.JWTTokenParams.ID_TOKEN);
Map<String, Object> userInfo = providerSettings.getUserInfo(accessToken, request).getValues();
Iterator<String> it = idTokenClaimsRequest.keys();
while (it.hasNext()) {
String keyName = it.next();
if (userInfo.containsKey(keyName)) {
oidcToken.put(keyName, userInfo.get(keyName));
}
}
} catch (UnauthorizedClientException e) {
throw failureFactory.getException(request, e.getMessage());
} catch (JSONException e) {
//if claims object not found, fall through
}
}
}
use of org.forgerock.oauth2.core.OAuth2ProviderSettings in project OpenAM by OpenRock.
the class DeviceCodeResource method issueCode.
@Post
public Representation issueCode(Representation body) throws OAuth2RestletException {
final Request restletRequest = getRequest();
OAuth2Request request = requestFactory.create(restletRequest);
String state = request.getParameter(STATE);
// Client ID, Response Type and Scope are required, all other parameters are optional
String clientId = request.getParameter(CLIENT_ID);
String scope = request.getParameter(SCOPE);
String responseType = request.getParameter(RESPONSE_TYPE);
try {
if (isEmpty(clientId) || isEmpty(scope) || isEmpty(responseType)) {
throw new OAuth2RestletException(400, "bad_request", "client_id, scope and response_type are required parameters", state);
} else {
// check client_id exists
clientRegistrationStore.get(clientId, request);
}
if (scope == null) {
scope = "";
}
final String maxAge = request.getParameter(MAX_AGE);
DeviceCode code = tokenStore.createDeviceCode(oAuth2Utils.split(scope, " "), null, clientId, request.<String>getParameter(NONCE), request.<String>getParameter(RESPONSE_TYPE), request.<String>getParameter(STATE), request.<String>getParameter(ACR_VALUES), request.<String>getParameter(PROMPT), request.<String>getParameter(UI_LOCALES), request.<String>getParameter(LOGIN_HINT), maxAge == null ? null : Integer.valueOf(maxAge), request.<String>getParameter(CLAIMS), request, request.<String>getParameter(CODE_CHALLENGE), request.<String>getParameter(CODE_CHALLENGE_METHOD));
Map<String, Object> result = new HashMap<>();
OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
result.put(DEVICE_CODE, code.getDeviceCode());
result.put(USER_CODE, code.getUserCode());
result.put(EXPIRES_IN, providerSettings.getDeviceCodeLifetime());
result.put(INTERVAL, providerSettings.getDeviceCodePollInterval());
String verificationUrl = providerSettings.getVerificationUrl();
if (StringUtils.isBlank(verificationUrl)) {
final HttpServletRequest servletRequest = ServletUtils.getRequest(restletRequest);
final String realm = request.getParameter(OAuth2Constants.Custom.REALM);
verificationUrl = baseURLProviderFactory.get(realm).getRootURL(servletRequest) + "/oauth2/device/user";
}
result.put(VERIFICATION_URL, verificationUrl);
return jacksonRepresentationFactory.create(result);
} catch (OAuth2Exception e) {
throw new OAuth2RestletException(e.getStatusCode(), e.getError(), e.getMessage(), state);
}
}
use of org.forgerock.oauth2.core.OAuth2ProviderSettings in project OpenAM by OpenRock.
the class DeviceCodeVerificationResource method saveConsent.
private void saveConsent(OAuth2Request request) throws NotFoundException, ServerException, InvalidScopeException, AccessDeniedException, ResourceOwnerAuthenticationRequired, InteractionRequiredException, BadRequestException, LoginRequiredException, InvalidClientException {
OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
ResourceOwner resourceOwner = resourceOwnerSessionValidator.validate(request);
ClientRegistration clientRegistration = clientRegistrationStore.get(request.<String>getParameter(CLIENT_ID), request);
Set<String> scope = Utils.splitScope(request.<String>getParameter(SCOPE));
Set<String> validatedScope = providerSettings.validateAuthorizationScope(clientRegistration, scope, request);
providerSettings.saveConsent(resourceOwner, clientRegistration.getClientId(), validatedScope);
}
Aggregations