use of org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException in project carbon-identity-framework by wso2.
the class PostAuthenticatedSubjectIdentifierHandler method handle.
@Override
public PostAuthnHandlerFlowStatus handle(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) {
if (!FrameworkUtils.isStepBasedSequenceHandlerExecuted(context)) {
return SUCCESS_COMPLETED;
}
SequenceConfig sequenceConfig = context.getSequenceConfig();
String subjectClaimURI = sequenceConfig.getApplicationConfig().getSubjectClaimUri();
String subjectValue = (String) context.getProperty(FrameworkConstants.SERVICE_PROVIDER_SUBJECT_CLAIM_VALUE);
try {
if (StringUtils.isNotBlank(subjectClaimURI)) {
if (subjectValue != null) {
handleUserStoreAndTenantDomain(sequenceConfig, subjectValue);
} else {
log.warn("Subject claim could not be found. Defaulting to Name Identifier.");
setAuthenticatedSubjectIdentifierBasedOnUserId(sequenceConfig);
}
} else {
setAuthenticatedSubjectIdentifierBasedOnUserId(sequenceConfig);
}
} catch (UserIdNotFoundException e) {
return UNSUCCESS_COMPLETED;
}
return SUCCESS_COMPLETED;
}
use of org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException in project carbon-identity-framework by wso2.
the class PostAuthnMissingClaimHandler method handlePostAuthenticationForMissingClaimsResponse.
protected void handlePostAuthenticationForMissingClaimsResponse(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws PostAuthenticationFailedException {
if (log.isDebugEnabled()) {
log.debug("Starting to process the response with missing claims");
}
Map<String, String> claims = new HashMap<String, String>();
Map<String, String> claimsForContext = new HashMap<String, String>();
Map<String, String[]> requestParams = request.getParameterMap();
boolean persistClaims = false;
AuthenticatedUser user = context.getSequenceConfig().getAuthenticatedUser();
Map<String, String> carbonToSPClaimMapping = new HashMap<>();
Object spToCarbonClaimMappingObject = context.getProperty(FrameworkConstants.SP_TO_CARBON_CLAIM_MAPPING);
if (spToCarbonClaimMappingObject instanceof Map) {
Map<String, String> spToCarbonClaimMapping = (Map<String, String>) spToCarbonClaimMappingObject;
for (Map.Entry<String, String> entry : spToCarbonClaimMapping.entrySet()) {
carbonToSPClaimMapping.put(entry.getValue(), entry.getKey());
}
}
boolean doMandatoryClaimsExist = false;
for (Map.Entry<String, String[]> entry : requestParams.entrySet()) {
if (entry.getKey().startsWith(FrameworkConstants.RequestParams.MANDOTARY_CLAIM_PREFIX)) {
doMandatoryClaimsExist = true;
break;
}
}
if (!doMandatoryClaimsExist) {
// Check whether mandatory claims exist in the request. If not throw error.
throw new PostAuthenticationFailedException("Mandatory missing claims are not found", "Mandatory missing " + "claims are not found in the request for the session with context identifier: " + context.getContextIdentifier());
}
List<String> missingClaims = new ArrayList<>();
for (Map.Entry<String, String[]> entry : requestParams.entrySet()) {
if (entry.getKey().startsWith(FrameworkConstants.RequestParams.MANDOTARY_CLAIM_PREFIX)) {
String localClaimURI = entry.getKey().substring(FrameworkConstants.RequestParams.MANDOTARY_CLAIM_PREFIX.length());
if (StringUtils.isBlank(entry.getValue()[0])) {
missingClaims.add(localClaimURI);
continue;
}
claims.put(localClaimURI, entry.getValue()[0]);
if (spToCarbonClaimMappingObject != null) {
String spClaimURI = carbonToSPClaimMapping.get(localClaimURI);
claimsForContext.put(spClaimURI, entry.getValue()[0]);
} else {
claimsForContext.put(localClaimURI, entry.getValue()[0]);
}
}
}
if (CollectionUtils.isNotEmpty(missingClaims)) {
String missingClaimURIs = StringUtils.join(missingClaims, ",");
if (log.isDebugEnabled()) {
log.debug("Claim values for the mandatory claims: " + missingClaimURIs + " are empty");
}
throw new PostAuthenticationFailedException("Mandatory claim is not found", "Claim " + "values for the claim URIs: " + missingClaimURIs + " are empty");
}
Map<ClaimMapping, String> authenticatedUserAttributes = FrameworkUtils.buildClaimMappings(claimsForContext);
authenticatedUserAttributes.putAll(user.getUserAttributes());
for (Map.Entry<Integer, StepConfig> entry : context.getSequenceConfig().getStepMap().entrySet()) {
StepConfig stepConfig = entry.getValue();
if (stepConfig.isSubjectAttributeStep()) {
if (stepConfig.getAuthenticatedUser() != null) {
user = stepConfig.getAuthenticatedUser();
}
if (!user.isFederatedUser()) {
persistClaims = true;
} else {
String associatedID;
String subject = user.getAuthenticatedSubjectIdentifier();
try {
FederatedAssociationManager federatedAssociationManager = FrameworkUtils.getFederatedAssociationManager();
associatedID = federatedAssociationManager.getUserForFederatedAssociation(context.getTenantDomain(), stepConfig.getAuthenticatedIdP(), subject);
if (StringUtils.isNotBlank(associatedID)) {
String fullQualifiedAssociatedUserId = FrameworkUtils.prependUserStoreDomainToName(associatedID + UserCoreConstants.TENANT_DOMAIN_COMBINER + context.getTenantDomain());
UserCoreUtil.setDomainInThreadLocal(UserCoreUtil.extractDomainFromName(associatedID));
user = AuthenticatedUser.createLocalAuthenticatedUserFromSubjectIdentifier(fullQualifiedAssociatedUserId);
persistClaims = true;
}
} catch (FederatedAssociationManagerException | FrameworkException e) {
throw new PostAuthenticationFailedException("Error while handling missing mandatory claims", "Error while getting association for " + subject, e);
}
}
break;
}
}
if (persistClaims) {
if (log.isDebugEnabled()) {
log.debug("Local user mapping found. Claims will be persisted");
}
try {
Map<String, String> claimMapping = context.getSequenceConfig().getApplicationConfig().getClaimMappings();
Map<String, String> localIdpClaims = new HashMap<>();
for (Map.Entry<String, String> entry : claims.entrySet()) {
String localClaim = claimMapping.get(entry.getKey());
localIdpClaims.put(localClaim, entry.getValue());
}
if (log.isDebugEnabled()) {
log.debug("Updating user profile of user : " + user.getLoggableUserId());
}
UserRealm realm = getUserRealm(user.getTenantDomain());
AbstractUserStoreManager userStoreManager = (AbstractUserStoreManager) realm.getUserStoreManager();
userStoreManager.setUserClaimValuesWithID(user.getUserId(), localIdpClaims, null);
} catch (UserStoreException e) {
if (e instanceof UserStoreClientException) {
context.setProperty(POST_AUTH_MISSING_CLAIMS_ERROR, e.getMessage());
if (StringUtils.isNotBlank(e.getErrorCode())) {
context.setProperty(POST_AUTH_MISSING_CLAIMS_ERROR_CODE, e.getErrorCode());
}
/*
When the attribute update is disabled for JIT provisioned users, the mandatory claim update
request will be identified through the error code and handled it.
*/
if (ERROR_CODE_INVALID_ATTRIBUTE_UPDATE.equals(e.getErrorCode())) {
context.getSequenceConfig().getAuthenticatedUser().setUserAttributes(authenticatedUserAttributes);
return;
}
}
if (ErrorMessages.ERROR_CODE_READONLY_USER_STORE.getCode().equals(e.getErrorCode())) {
context.getSequenceConfig().getAuthenticatedUser().setUserAttributes(authenticatedUserAttributes);
return;
}
throw new PostAuthenticationFailedException(e.getMessage(), "Error while updating claims for local user. Could not update profile", e);
} catch (UserIdNotFoundException e) {
throw new PostAuthenticationFailedException("User id not found", "User id not found for local user. Could not update profile", e);
}
}
context.getSequenceConfig().getAuthenticatedUser().setUserAttributes(authenticatedUserAttributes);
}
use of org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException in project carbon-identity-framework by wso2.
the class DefaultClaimHandler method retrieveAllNunNullUserClaimValues.
private Map<String, String> retrieveAllNunNullUserClaimValues(AuthenticatedUser authenticatedUser, ClaimManager claimManager, ApplicationConfig appConfig, AbstractUserStoreManager userStore) throws FrameworkException {
String tenantDomain = authenticatedUser.getTenantDomain();
Map<String, String> allLocalClaims = new HashMap<>();
try {
org.wso2.carbon.user.api.ClaimMapping[] claimMappings = claimManager.getAllClaimMappings(ApplicationConstants.LOCAL_IDP_DEFAULT_CLAIM_DIALECT);
List<String> localClaimURIs = new ArrayList<>();
for (org.wso2.carbon.user.api.ClaimMapping mapping : claimMappings) {
String claimURI = mapping.getClaim().getClaimUri();
localClaimURIs.add(claimURI);
}
allLocalClaims = userStore.getUserClaimValuesWithID(authenticatedUser.getUserId(), localClaimURIs.toArray(new String[0]), null);
if (allLocalClaims == null) {
return new HashMap<>();
}
} catch (UserStoreException e) {
if (e.getMessage().contains("UserNotFound")) {
if (log.isDebugEnabled()) {
log.debug("User " + authenticatedUser.getLoggableUserId() + " not found in user store");
}
} else {
throw new FrameworkException("Error occurred while getting all user claims for " + authenticatedUser.getLoggableUserId() + " in " + tenantDomain, e);
}
} catch (UserIdNotFoundException e) {
throw new FrameworkException("User id is not available for user: " + authenticatedUser.getLoggableUserId(), e);
}
return allLocalClaims;
}
use of org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException in project identity-inbound-auth-oauth by wso2-extensions.
the class ResponseTypeHandlerUtil method generateAccessToken.
/**
* Generates access token for the given oauth issuer.
*
* @param oauthAuthzMsgCtx
* @param cacheEnabled
* @param oauthIssuerImpl
* @return
* @throws IdentityOAuth2Exception
*/
public static AccessTokenDO generateAccessToken(OAuthAuthzReqMessageContext oauthAuthzMsgCtx, boolean cacheEnabled, OauthTokenIssuer oauthIssuerImpl) throws IdentityOAuth2Exception {
OAuth2AuthorizeReqDTO authorizationReqDTO = oauthAuthzMsgCtx.getAuthorizationReqDTO();
String scope = OAuth2Util.buildScopeString(oauthAuthzMsgCtx.getApprovedScope());
String consumerKey = authorizationReqDTO.getConsumerKey();
String authorizedUserId;
try {
authorizedUserId = authorizationReqDTO.getUser().getUserId();
} catch (UserIdNotFoundException e) {
throw new IdentityOAuth2Exception("Error occurred while retrieving the user id for user: " + authorizationReqDTO.getUser().getLoggableUserId());
}
synchronized ((consumerKey + ":" + authorizedUserId + ":" + scope).intern()) {
AccessTokenDO existingTokenBean = getExistingToken(oauthAuthzMsgCtx, authorizedUserId, cacheEnabled);
// Return a new access token in each request when JWTTokenIssuer is used.
if (isNotRenewAccessTokenPerRequest(oauthIssuerImpl, oauthAuthzMsgCtx)) {
if (existingTokenBean != null) {
// Revoke token if RenewTokenPerRequest configuration is enabled.
if (OAuthServerConfiguration.getInstance().isTokenRenewalPerRequestEnabled()) {
if (log.isDebugEnabled()) {
log.debug("RenewTokenPerRequest configuration active. " + "Proceeding to revoke any existing active tokens for client Id: " + consumerKey + ", user: " + authorizationReqDTO.getUser().getLoggableUserId() + " and scope: " + scope + ".");
}
revokeExistingToken(existingTokenBean.getConsumerKey(), existingTokenBean.getAccessToken());
// When revoking the token state will be set as REVOKED.
// existingTokenBean.setTokenState(TOKEN_STATE_REVOKED) can be used instead of 'null' but
// then the token state will again be updated to EXPIRED when a new token is generated.
existingTokenBean = null;
}
// Return existing token if it is still valid.
if (isAccessTokenValid(existingTokenBean)) {
return existingTokenBean;
}
}
if (log.isDebugEnabled()) {
log.debug("No active access token found for client Id: " + consumerKey + ", user: " + authorizationReqDTO.getUser().getLoggableUserId() + " and scope: " + scope + ". Therefore issuing new token");
}
}
// Issue a new access token.
return generateNewAccessToken(oauthAuthzMsgCtx, existingTokenBean, oauthIssuerImpl, authorizedUserId, cacheEnabled);
}
}
use of org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException in project identity-inbound-auth-oauth by wso2-extensions.
the class ResponseTypeHandlerUtil method generateAuthorizationCode.
public static AuthzCodeDO generateAuthorizationCode(OAuthAuthzReqMessageContext oauthAuthzMsgCtx, boolean cacheEnabled, OauthTokenIssuer oauthIssuerImpl) throws IdentityOAuth2Exception {
OAuth2AuthorizeReqDTO authorizationReqDTO = oauthAuthzMsgCtx.getAuthorizationReqDTO();
String authorizationCode;
String codeId = UUID.randomUUID().toString();
Timestamp timestamp = new Timestamp(new Date().getTime());
long validityPeriod = OAuthServerConfiguration.getInstance().getAuthorizationCodeValidityPeriodInSeconds();
// if a VALID callback is set through the callback handler, use
// it instead of the default one
long callbackValidityPeriod = oauthAuthzMsgCtx.getValidityPeriod();
if ((callbackValidityPeriod != OAuthConstants.UNASSIGNED_VALIDITY_PERIOD) && callbackValidityPeriod > 0) {
validityPeriod = callbackValidityPeriod;
}
// convert to milliseconds
validityPeriod = validityPeriod * 1000;
// set the validity period. this is needed by downstream handlers.
// if this is set before - then this will override it by the calculated new value.
oauthAuthzMsgCtx.setValidityPeriod(validityPeriod);
oauthAuthzMsgCtx.setAuthorizationCodeValidityPeriod(validityPeriod);
// set code issued time.this is needed by downstream handlers.
oauthAuthzMsgCtx.setCodeIssuedTime(timestamp.getTime());
if (authorizationReqDTO.getUser() != null && authorizationReqDTO.getUser().isFederatedUser()) {
// if a federated user, treat the tenant domain as similar to application domain.
authorizationReqDTO.getUser().setTenantDomain(authorizationReqDTO.getTenantDomain());
}
try {
authorizationCode = oauthIssuerImpl.authorizationCode(oauthAuthzMsgCtx);
} catch (OAuthSystemException e) {
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.FAILED, "System error occurred.", "issue-authz-code", null);
throw new IdentityOAuth2Exception(e.getMessage(), e);
}
AuthzCodeDO authzCodeDO = new AuthzCodeDO(authorizationReqDTO.getUser(), oauthAuthzMsgCtx.getApprovedScope(), timestamp, validityPeriod, authorizationReqDTO.getCallbackUrl(), authorizationReqDTO.getConsumerKey(), authorizationCode, codeId, authorizationReqDTO.getPkceCodeChallenge(), authorizationReqDTO.getPkceCodeChallengeMethod());
OAuthTokenPersistenceFactory.getInstance().getAuthorizationCodeDAO().insertAuthorizationCode(authorizationCode, authorizationReqDTO.getConsumerKey(), authorizationReqDTO.getCallbackUrl(), authzCodeDO);
if (cacheEnabled) {
// Cache the authz Code, here we prepend the client_key to avoid collisions with
// AccessTokenDO instances. In database level, these are in two databases. But access
// tokens and authorization codes are in a single cache.
String cacheKeyString = OAuth2Util.buildCacheKeyStringForAuthzCode(authorizationReqDTO.getConsumerKey(), authorizationCode);
OAuthCache.getInstance().addToCache(new OAuthCacheKey(cacheKeyString), authzCodeDO);
if (log.isDebugEnabled()) {
log.debug("Authorization Code info was added to the cache for client id : " + authorizationReqDTO.getConsumerKey());
}
}
if (log.isDebugEnabled()) {
log.debug("Issued Authorization Code to user : " + authorizationReqDTO.getUser() + ", Using the redirect url : " + authorizationReqDTO.getCallbackUrl() + ", Scope : " + OAuth2Util.buildScopeString(oauthAuthzMsgCtx.getApprovedScope()) + ", validity period : " + validityPeriod);
}
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> params = new HashMap<>();
params.put("clientId", authorizationReqDTO.getConsumerKey());
if (authorizationReqDTO.getUser() != null) {
try {
params.put("user", authorizationReqDTO.getUser().getUserId());
} catch (UserIdNotFoundException e) {
if (StringUtils.isNotBlank(authorizationReqDTO.getUser().getAuthenticatedSubjectIdentifier())) {
params.put("user", authorizationReqDTO.getUser().getAuthenticatedSubjectIdentifier().replaceAll(".", "*"));
}
}
}
params.put("requestedScopes", OAuth2Util.buildScopeString(authorizationReqDTO.getScopes()));
params.put("redirectUri", authorizationReqDTO.getCallbackUrl());
Map<String, Object> configs = new HashMap<>();
configs.put("authzCodeValidityPeriod", String.valueOf(validityPeriod));
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "Issued Authorization Code to user.", "issue-authz-code", configs);
}
return authzCodeDO;
}
Aggregations