use of org.forgerock.oauth2.core.ResourceOwner in project OpenAM by OpenRock.
the class LegacyResponseTypeHandler method handle.
public Map.Entry<String, org.forgerock.oauth2.core.Token> handle(String tokenType, Set<String> scope, ResourceOwner resourceOwner, String clientId, String redirectUri, String nonce, OAuth2Request request, String codeChallenge, String codeChallengeMethod) throws NotFoundException {
final Map<String, Object> data = new HashMap<String, Object>();
data.put(TOKEN_TYPE, tokenType);
data.put(SCOPE, scope);
data.put(USERNAME, resourceOwner.getId());
data.put(CLIENT_ID, clientId);
data.put(REDIRECT_URI, redirectUri);
data.put(OAuth2Constants.Custom.NONCE, nonce);
data.put(REALM, realm);
data.put(OAuth2Constants.Custom.CODE_CHALLENGE, codeChallenge);
data.put(OAuth2Constants.Custom.CODE_CHALLENGE_METHOD, codeChallengeMethod);
final HttpServletRequest req = ServletUtils.getRequest(request.<Request>getRequest());
data.put(OAuth2Constants.Custom.SSO_TOKEN_ID, cookieExtractor.extract(req, ssoCookieName));
final CoreToken token = responseType.createToken(request.getToken(AccessToken.class), data);
return new AbstractMap.SimpleEntry<String, org.forgerock.oauth2.core.Token>(responseType.URIParamValue(), new LegacyToken(token));
}
use of org.forgerock.oauth2.core.ResourceOwner in project OpenAM by OpenRock.
the class ScopeImpl method evaluateScope.
/**
* {@inheritDoc}
*/
public Map<String, Object> evaluateScope(CoreToken token) {
final Map<String, Object> map = new HashMap<String, Object>();
final Set<String> scopes = token.getScope();
final String clientId = token.getClientID();
final String resourceOwner = token.getUserID();
final String grantType = token.getGrantType();
AMIdentity id = null;
try {
if (clientId != null && OAuth2Constants.TokenEndpoint.CLIENT_CREDENTIALS.equals(grantType)) {
id = identityManager.getClientIdentity(clientId, token.getRealm());
} else if (resourceOwner != null) {
id = identityManager.getResourceOwnerIdentity(resourceOwner, token.getRealm());
}
} catch (UnauthorizedClientException e) {
logger.error("Unable to get user identity", e);
}
if (id == null || scopes.isEmpty()) {
return map;
}
try {
for (final String scope : scopes) {
final Set<String> attributes = id.getAttribute(scope);
if (attributes != null) {
final Iterator<String> iter = attributes.iterator();
final StringBuilder builder = new StringBuilder();
while (iter.hasNext()) {
builder.append(iter.next());
if (iter.hasNext()) {
builder.append(MULTI_ATTRIBUTE_SEPARATOR);
}
}
map.put(scope, builder.toString());
}
}
} catch (SSOException e) {
logger.error("Unable to get attribute", e);
} catch (IdRepoException e) {
logger.error("Unable to get attribute", e);
}
return map;
}
use of org.forgerock.oauth2.core.ResourceOwner 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.ResourceOwner in project OpenAM by OpenRock.
the class DeviceCodeVerificationResource method verify.
/**
* Handles POST requests to the OAuth2 device/user endpoint.
*/
@Post
public Representation verify(Representation body) throws ServerException, NotFoundException, InvalidGrantException, OAuth2RestletException {
final Request restletRequest = getRequest();
OAuth2Request request = requestFactory.create(restletRequest);
DeviceCode deviceCode;
try {
deviceCode = tokenStore.readDeviceCode(request.<String>getParameter(OAuth2Constants.DeviceCode.USER_CODE), request);
} catch (InvalidGrantException e) {
return getTemplateRepresentation(FORM, request, "not_found");
}
if (deviceCode == null || deviceCode.isIssued()) {
return getTemplateRepresentation(FORM, request, "not_found");
}
addRequestParamsFromDeviceCode(restletRequest, deviceCode);
try {
final String decision = request.getParameter("decision");
if (StringUtils.isNotEmpty(decision)) {
final boolean consentGiven = "allow".equalsIgnoreCase(decision);
final boolean saveConsent = "on".equalsIgnoreCase(request.<String>getParameter("save_consent"));
if (saveConsent) {
saveConsent(request);
}
if (consentGiven) {
ResourceOwner resourceOwner = resourceOwnerSessionValidator.validate(request);
deviceCode.setResourceOwnerId(resourceOwner.getId());
deviceCode.setAuthorized(true);
tokenStore.updateDeviceCode(deviceCode, request);
} else {
tokenStore.deleteDeviceCode(deviceCode.getClientId(), deviceCode.getDeviceCode(), request);
}
} else {
authorizationService.authorize(request);
}
} catch (IllegalArgumentException e) {
if (e.getMessage().contains("client_id")) {
throw new OAuth2RestletException(400, "invalid_request", e.getMessage(), request.<String>getParameter("state"));
}
throw new OAuth2RestletException(400, "invalid_request", e.getMessage(), request.<String>getParameter("redirect_uri"), request.<String>getParameter("state"));
} catch (ResourceOwnerAuthenticationRequired e) {
throw new OAuth2RestletException(e.getStatusCode(), e.getError(), e.getMessage(), e.getRedirectUri().toString(), null);
} catch (ResourceOwnerConsentRequired e) {
return representation.getRepresentation(getContext(), request, "authorize.ftl", getDataModel(e, request));
} catch (InvalidClientException | RedirectUriMismatchException e) {
throw new OAuth2RestletException(e.getStatusCode(), e.getError(), e.getMessage(), request.<String>getParameter("state"));
} catch (OAuth2Exception e) {
throw new OAuth2RestletException(e.getStatusCode(), e.getError(), e.getMessage(), request.<String>getParameter("redirect_uri"), request.<String>getParameter("state"), e.getParameterLocation());
}
return getTemplateRepresentation(THANKS_PAGE, request, null);
}
use of org.forgerock.oauth2.core.ResourceOwner 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