use of org.forgerock.openidconnect.OpenIdConnectClientRegistration in project OpenAM by OpenRock.
the class OpenAMScopeValidator method getUserInfo.
/**
* {@inheritDoc}
*/
public UserInfoClaims getUserInfo(AccessToken token, OAuth2Request request) throws UnauthorizedClientException, NotFoundException {
Map<String, Object> response = new HashMap<>();
Bindings scriptVariables = new SimpleBindings();
SSOToken ssoToken = getUsersSession(request);
String realm;
Set<String> scopes;
AMIdentity id;
OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
Map<String, Set<String>> requestedClaimsValues = gatherRequestedClaims(providerSettings, request, token);
try {
if (token != null) {
OpenIdConnectClientRegistration clientRegistration;
try {
clientRegistration = clientRegistrationStore.get(token.getClientId(), request);
} catch (InvalidClientException e) {
logger.message("Unable to retrieve client from store.");
throw new NotFoundException("No valid client registration found.");
}
final String subId = clientRegistration.getSubValue(token.getResourceOwnerId(), providerSettings);
//data comes from token when we have one
realm = token.getRealm();
scopes = token.getScope();
id = identityManager.getResourceOwnerIdentity(token.getResourceOwnerId(), realm);
response.put(OAuth2Constants.JWTTokenParams.SUB, subId);
response.put(OAuth2Constants.JWTTokenParams.UPDATED_AT, getUpdatedAt(token.getResourceOwnerId(), token.getRealm(), request));
} else {
//otherwise we're simply reading claims into the id_token, so grab it from the request/ssoToken
realm = DNMapper.orgNameToRealmName(ssoToken.getProperty(ISAuthConstants.ORGANIZATION));
id = identityManager.getResourceOwnerIdentity(ssoToken.getProperty(ISAuthConstants.USER_ID), realm);
String scopeStr = request.getParameter(OAuth2Constants.Params.SCOPE);
scopes = splitScope(scopeStr);
}
scriptVariables.put(OAuth2Constants.ScriptParams.SCOPES, getScriptFriendlyScopes(scopes));
scriptVariables.put(OAuth2Constants.ScriptParams.IDENTITY, id);
scriptVariables.put(OAuth2Constants.ScriptParams.LOGGER, logger);
scriptVariables.put(OAuth2Constants.ScriptParams.CLAIMS, response);
scriptVariables.put(OAuth2Constants.ScriptParams.SESSION, ssoToken);
scriptVariables.put(OAuth2Constants.ScriptParams.REQUESTED_CLAIMS, requestedClaimsValues);
ScriptObject script = getOIDCClaimsExtensionScript(realm);
try {
return scriptEvaluator.evaluateScript(script, scriptVariables);
} catch (ScriptException e) {
logger.message("Error running OIDC claims script", e);
throw new ServerException("Error running OIDC claims script: " + e.getMessage());
}
} catch (ServerException e) {
//API does not allow ServerExceptions to be thrown!
throw new NotFoundException(e.getMessage());
} catch (SSOException e) {
throw new NotFoundException(e.getMessage());
}
}
use of org.forgerock.openidconnect.OpenIdConnectClientRegistration in project OpenAM by OpenRock.
the class OpenAMTokenStore method createAuthorizationCode.
/**
* {@inheritDoc}
*/
public AuthorizationCode createAuthorizationCode(Set<String> scope, ResourceOwner resourceOwner, String clientId, String redirectUri, String nonce, OAuth2Request request, String codeChallenge, String codeChallengeMethod) throws ServerException, NotFoundException {
logger.message("DefaultOAuthTokenStoreImpl::Creating Authorization code");
OpenIdConnectClientRegistration clientRegistration = getClientRegistration(clientId, request);
final OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
final String code = UUID.randomUUID().toString();
long expiryTime = 0;
if (clientRegistration == null) {
expiryTime = providerSettings.getAuthorizationCodeLifetime() + System.currentTimeMillis();
} else {
expiryTime = clientRegistration.getAuthorizationCodeLifeTime(providerSettings) + System.currentTimeMillis();
}
final String ssoTokenId = getSsoTokenId(request);
final OpenAMAuthorizationCode authorizationCode = new OpenAMAuthorizationCode(code, resourceOwner.getId(), clientId, redirectUri, scope, getClaimsFromRequest(request), expiryTime, nonce, realmNormaliser.normalise(request.<String>getParameter(REALM)), getAuthModulesFromSSOToken(request), getAuthenticationContextClassReferenceFromRequest(request), ssoTokenId, codeChallenge, codeChallengeMethod);
// Store in CTS
try {
tokenStore.create(authorizationCode);
if (auditLogger.isAuditLogEnabled()) {
String[] obs = { "CREATED_AUTHORIZATION_CODE", authorizationCode.toString() };
auditLogger.logAccessMessage("CREATED_AUTHORIZATION_CODE", obs, null);
}
} catch (CoreTokenException e) {
if (auditLogger.isAuditLogEnabled()) {
String[] obs = { "FAILED_CREATE_AUTHORIZATION_CODE", authorizationCode.toString() };
auditLogger.logErrorMessage("FAILED_CREATE_AUTHORIZATION_CODE", obs, null);
}
logger.error("Unable to create authorization code " + authorizationCode.getTokenInfo(), e);
throw new ServerException("Could not create token in CTS");
}
request.setToken(AuthorizationCode.class, authorizationCode);
return authorizationCode;
}
use of org.forgerock.openidconnect.OpenIdConnectClientRegistration in project OpenAM by OpenRock.
the class ClientCredentialsReader method extractCredentials.
/**
* Extracts the client's credentials from the OAuth2 request.
*
* @param request The OAuth2 request.
* @param endpoint The endpoint this request should be for, or null to disable audience verification.
* @return The client's credentials.
* @throws InvalidRequestException If the request contains multiple client credentials.
* @throws InvalidClientException If the request does not contain the client's id.
*/
public ClientCredentials extractCredentials(OAuth2Request request, String endpoint) throws InvalidRequestException, InvalidClientException, NotFoundException {
final Request req = request.getRequest();
boolean basicAuth = false;
if (req.getChallengeResponse() != null) {
basicAuth = true;
}
final ClientCredentials client;
Client.TokenEndpointAuthMethod method = CLIENT_SECRET_POST;
//jwt type first
if (JWT_PROFILE_CLIENT_ASSERTION_TYPE.equalsIgnoreCase(request.<String>getParameter(CLIENT_ASSERTION_TYPE))) {
client = verifyJwtBearer(request, basicAuth, endpoint);
method = PRIVATE_KEY_JWT;
} else {
String clientId = request.getParameter(OAuth2Constants.Params.CLIENT_ID);
String clientSecret = request.getParameter(OAuth2Constants.Params.CLIENT_SECRET);
if (basicAuth && clientId != null) {
logger.error("Client (" + clientId + ") using multiple authentication methods");
throw new InvalidRequestException("Client authentication failed");
}
if (req.getChallengeResponse() != null) {
final ChallengeResponse challengeResponse = req.getChallengeResponse();
clientId = challengeResponse.getIdentifier();
clientSecret = "";
if (challengeResponse.getSecret() != null && challengeResponse.getSecret().length > 0) {
clientSecret = String.valueOf(req.getChallengeResponse().getSecret());
}
method = CLIENT_SECRET_BASIC;
}
if (clientId == null || clientId.isEmpty()) {
logger.error("Client Id is not set");
throw failureFactory.getException(request, "Client authentication failed");
}
client = new ClientCredentials(clientId, clientSecret == null ? null : clientSecret.toCharArray(), false, basicAuth);
}
final OpenIdConnectClientRegistration cr = clientRegistrationStore.get(client.getClientId(), request);
final Set<String> scopes = cr.getAllowedScopes();
//if we're accessing the token endpoint, check we're authenticating using the appropriate method
if (scopes.contains(OAuth2Constants.Params.OPENID) && req.getResourceRef().getLastSegment().equals(OAuth2Constants.Params.ACCESS_TOKEN) && !cr.getTokenEndpointAuthMethod().equals(method.getType())) {
throw failureFactory.getException(request, "Invalid authentication method for accessing this endpoint.");
}
return client;
}
use of org.forgerock.openidconnect.OpenIdConnectClientRegistration in project OpenAM by OpenRock.
the class OpenAMTokenStore method createRefreshToken.
@Override
public RefreshToken createRefreshToken(String grantType, String clientId, String resourceOwnerId, String redirectUri, Set<String> scope, OAuth2Request request, String validatedClaims) throws ServerException, NotFoundException {
final String realm = realmNormaliser.normalise(request.<String>getParameter(REALM));
logger.message("Create refresh token");
OpenIdConnectClientRegistration clientRegistration = getClientRegistration(clientId, request);
final OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
final String id = UUID.randomUUID().toString();
final String auditId = UUID.randomUUID().toString();
final long lifeTime;
if (clientRegistration == null) {
lifeTime = providerSettings.getRefreshTokenLifetime();
} else {
lifeTime = clientRegistration.getRefreshTokenLifeTime(providerSettings);
}
long expiryTime = lifeTime < 0 ? -1 : lifeTime + System.currentTimeMillis();
AuthorizationCode token = request.getToken(AuthorizationCode.class);
String authModules = null;
String acr = null;
if (token != null) {
authModules = token.getAuthModules();
acr = token.getAuthenticationContextClassReference();
}
RefreshToken currentRefreshToken = request.getToken(RefreshToken.class);
if (currentRefreshToken != null) {
authModules = currentRefreshToken.getAuthModules();
acr = currentRefreshToken.getAuthenticationContextClassReference();
}
OpenAMRefreshToken refreshToken = new OpenAMRefreshToken(id, resourceOwnerId, clientId, redirectUri, scope, expiryTime, OAuth2Constants.Bearer.BEARER, OAuth2Constants.Token.OAUTH_REFRESH_TOKEN, grantType, realm, authModules, acr, auditId);
if (!StringUtils.isBlank(validatedClaims)) {
refreshToken.setClaims(validatedClaims);
}
try {
tokenStore.create(refreshToken);
if (auditLogger.isAuditLogEnabled()) {
String[] obs = { "CREATED_REFRESH_TOKEN", refreshToken.toString() };
auditLogger.logAccessMessage("CREATED_REFRESH_TOKEN", obs, null);
}
} catch (CoreTokenException e) {
if (auditLogger.isAuditLogEnabled()) {
String[] obs = { "FAILED_CREATE_REFRESH_TOKEN", refreshToken.toString() };
auditLogger.logErrorMessage("FAILED_CREATE_REFRESH_TOKEN", obs, null);
}
logger.error("Unable to create refresh token: " + refreshToken.getTokenInfo(), e);
throw new ServerException("Could not create token in CTS: " + e.getMessage());
}
request.setToken(RefreshToken.class, refreshToken);
return refreshToken;
}
use of org.forgerock.openidconnect.OpenIdConnectClientRegistration in project OpenAM by OpenRock.
the class OpenAMTokenStore method createAccessToken.
/**
* {@inheritDoc}
*/
public AccessToken createAccessToken(String grantType, String accessTokenType, String authorizationCode, String resourceOwnerId, String clientId, String redirectUri, Set<String> scope, RefreshToken refreshToken, String nonce, String claims, OAuth2Request request) throws ServerException, NotFoundException {
OpenIdConnectClientRegistration clientRegistration = getClientRegistration(clientId, request);
final OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
final String id = UUID.randomUUID().toString();
final String auditId = UUID.randomUUID().toString();
String realm = realmNormaliser.normalise(request.<String>getParameter(REALM));
long expiryTime = 0;
if (clientRegistration == null) {
expiryTime = providerSettings.getAccessTokenLifetime() + System.currentTimeMillis();
} else {
expiryTime = clientRegistration.getAccessTokenLifeTime(providerSettings) + System.currentTimeMillis();
}
final AccessToken accessToken;
if (refreshToken == null) {
accessToken = new OpenAMAccessToken(id, authorizationCode, resourceOwnerId, clientId, redirectUri, scope, expiryTime, null, OAuth2Constants.Token.OAUTH_ACCESS_TOKEN, grantType, nonce, realm, claims, auditId);
} else {
accessToken = new OpenAMAccessToken(id, authorizationCode, resourceOwnerId, clientId, redirectUri, scope, expiryTime, refreshToken.getTokenId(), OAuth2Constants.Token.OAUTH_ACCESS_TOKEN, grantType, nonce, realm, claims, auditId);
}
try {
tokenStore.create(accessToken);
if (auditLogger.isAuditLogEnabled()) {
String[] obs = { "CREATED_TOKEN", accessToken.toString() };
auditLogger.logAccessMessage("CREATED_TOKEN", obs, null);
}
} catch (CoreTokenException e) {
logger.error("Could not create token in CTS: " + e.getMessage());
if (auditLogger.isAuditLogEnabled()) {
String[] obs = { "FAILED_CREATE_TOKEN", accessToken.toString() };
auditLogger.logErrorMessage("FAILED_CREATE_TOKEN", obs, null);
}
throw new ServerException("Could not create token in CTS: " + e.getMessage());
}
request.setToken(AccessToken.class, accessToken);
return accessToken;
}
Aggregations