use of org.wso2.carbon.identity.api.server.authenticators.v1.model.Authenticator in project carbon-identity-framework by wso2.
the class DefaultClaimHandler method handleFederatedClaims.
/**
* @param spStandardDialect
* @param remoteClaims
* @param stepConfig
* @param context
* @return
* @throws FrameworkException
*/
protected Map<String, String> handleFederatedClaims(Map<String, String> remoteClaims, String spStandardDialect, StepConfig stepConfig, AuthenticationContext context) throws FrameworkException {
ClaimMapping[] idPClaimMappings = context.getExternalIdP().getClaimMappings();
if (idPClaimMappings == null) {
idPClaimMappings = new ClaimMapping[0];
}
Map<String, String> spClaimMappings = context.getSequenceConfig().getApplicationConfig().getClaimMappings();
if (spClaimMappings == null) {
spClaimMappings = new HashMap<>();
}
Map<String, String> carbonToStandardClaimMapping;
Map<String, String> spRequestedClaimMappings = context.getSequenceConfig().getApplicationConfig().getRequestedClaimMappings();
if (StringUtils.isNotBlank(spStandardDialect) && !StringUtils.equals(spStandardDialect, ApplicationConstants.LOCAL_IDP_DEFAULT_CLAIM_DIALECT)) {
carbonToStandardClaimMapping = getCarbonToStandardDialectMapping(spStandardDialect, context, spRequestedClaimMappings, context.getTenantDomain());
spRequestedClaimMappings = mapRequestClaimsInStandardDialect(spRequestedClaimMappings, carbonToStandardClaimMapping);
context.setProperty(FrameworkConstants.SP_TO_CARBON_CLAIM_MAPPING, spRequestedClaimMappings);
}
ApplicationAuthenticator authenticator = stepConfig.getAuthenticatedAutenticator().getApplicationAuthenticator();
boolean useDefaultIdpDialect = context.getExternalIdP().useDefaultLocalIdpDialect();
// When null the local claim dialect will be used.
String idPStandardDialect = null;
if (useDefaultIdpDialect || !useLocalClaimDialectForClaimMappings()) {
idPStandardDialect = authenticator.getClaimDialectURI();
}
// Insert the runtime claims from the context. The priority is for runtime claims.
remoteClaims.putAll(context.getRuntimeClaims());
Map<String, String> localUnfilteredClaims = new HashMap<>();
Map<String, String> spUnfilteredClaims = new HashMap<>();
Map<String, String> spFilteredClaims = new HashMap<>();
Map<String, String> localUnfilteredClaimsForNullValues = new HashMap<>();
// claim mapping from local IDP to remote IDP : local-claim-uri / idp-claim-uri
Map<String, String> localToIdPClaimMap = null;
Map<String, String> defaultValuesForClaims = new HashMap<>();
loadDefaultValuesForClaims(idPClaimMappings, defaultValuesForClaims);
if (idPStandardDialect != null || useDefaultIdpDialect) {
localToIdPClaimMap = getLocalToIdpClaimMappingWithStandardDialect(remoteClaims, idPClaimMappings, context, idPStandardDialect);
} else if (idPClaimMappings.length > 0) {
localToIdPClaimMap = FrameworkUtils.getClaimMappings(idPClaimMappings, true);
} else {
log.warn("Authenticator : " + authenticator.getFriendlyName() + " does not have " + "a standard dialect and IdP : " + context.getExternalIdP().getIdPName() + " does not have custom claim mappings. Cannot proceed with claim mappings");
return spFilteredClaims;
}
// Loop remote claims and map to local claims
mapRemoteClaimsToLocalClaims(remoteClaims, localUnfilteredClaims, localToIdPClaimMap, defaultValuesForClaims, localUnfilteredClaimsForNullValues);
// claim mapping from local service provider to remote service provider.
Map<String, String> localToSPClaimMappings = mapLocalSpClaimsToRemoteSPClaims(spStandardDialect, context, spClaimMappings);
// Loop through <code>localToSPClaimMappings</code> and filter
// <code>spUnfilteredClaims</code> and <code>spFilteredClaims</code>
filterSPClaims(spRequestedClaimMappings, localUnfilteredClaims, spUnfilteredClaims, spFilteredClaims, localToSPClaimMappings);
if (stepConfig.isSubjectAttributeStep()) {
if (MapUtils.isNotEmpty(localUnfilteredClaimsForNullValues)) {
/*
Set all locally mapped unfiltered null remote claims as a property.
This property will used to retrieve unfiltered null value claims.
*/
context.setProperty(FrameworkConstants.UNFILTERED_LOCAL_CLAIMS_FOR_NULL_VALUES, localUnfilteredClaimsForNullValues);
}
// set unfiltered remote claims as a property
context.setProperty(FrameworkConstants.UNFILTERED_IDP_CLAIM_VALUES, remoteClaims);
// set all locally mapped unfiltered remote claims as a property
context.setProperty(FrameworkConstants.UNFILTERED_LOCAL_CLAIM_VALUES, localUnfilteredClaims);
// set all service provider mapped unfiltered remote claims as a property
context.setProperty(FrameworkConstants.UNFILTERED_SP_CLAIM_VALUES, spUnfilteredClaims);
}
if (FrameworkConstants.RequestType.CLAIM_TYPE_OPENID.equals(context.getRequestType())) {
spFilteredClaims = spUnfilteredClaims;
}
// set the subject claim URI as a property
if (stepConfig.isSubjectIdentifierStep()) {
if (spStandardDialect != null) {
setSubjectClaimForFederatedClaims(localUnfilteredClaims, spStandardDialect, context);
} else {
setSubjectClaimForFederatedClaims(spUnfilteredClaims, null, context);
}
}
// Add multi Attributes separator with claims.it can be defined in user-mgt.xml file
UserRealm realm = getUserRealm(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
UserStoreManager userStore = getUserStoreManager(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, realm);
addMultiAttributeSeparatorToRequestedClaims(null, userStore, spFilteredClaims, realm);
return spFilteredClaims;
}
use of org.wso2.carbon.identity.api.server.authenticators.v1.model.Authenticator in project carbon-identity-framework by wso2.
the class DefaultRequestCoordinator method handle.
@Override
public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {
CommonAuthResponseWrapper responseWrapper = null;
if (response instanceof CommonAuthResponseWrapper) {
responseWrapper = (CommonAuthResponseWrapper) response;
} else {
responseWrapper = new CommonAuthResponseWrapper(response);
responseWrapper.setWrappedByFramework(true);
}
AuthenticationContext context = null;
String sessionDataKey = request.getParameter("sessionDataKey");
try {
AuthenticationRequestCacheEntry authRequest = null;
boolean returning = false;
// TODO: use a different mechanism to determine the flow start.
if (request.getParameter("type") != null) {
// handles common auth logout request.
if (sessionDataKey != null) {
if (log.isDebugEnabled()) {
log.debug("Retrieving authentication request from cache for the sessionDataKey: " + sessionDataKey);
}
authRequest = getAuthenticationRequest(request, sessionDataKey);
if (authRequest == null) {
// authRequest is not retrieved from the cache.
if (log.isDebugEnabled()) {
log.debug("No authentication request found in the cache for sessionDataKey: " + sessionDataKey);
}
if (isCommonAuthLogoutRequest(request)) {
if (log.isDebugEnabled()) {
log.debug("Ignoring the invalid sessionDataKey: " + sessionDataKey + " in the " + "CommonAuthLogout request.");
}
} else {
throw new FrameworkException("Invalid authentication request with sessionDataKey: " + sessionDataKey);
}
}
} else if (!isCommonAuthLogoutRequest(request)) {
// sessionDataKey is null and not a common auth logout request
if (log.isDebugEnabled()) {
log.debug("Session data key is null in the request and not a logout request.");
}
FrameworkUtils.sendToRetryPage(request, response, context);
}
// if there is a cache entry, wrap the original request with params in cache entry
if (authRequest != null) {
request = FrameworkUtils.getCommonAuthReqWithParams(request, authRequest);
}
context = initializeFlow(request, responseWrapper);
context.initializeAnalyticsData();
} else {
returning = true;
context = FrameworkUtils.getContextData(request);
associateTransientRequestData(request, responseWrapper, context);
}
if (context != null) {
if (StringUtils.isNotBlank(context.getServiceProviderName())) {
MDC.put(SERVICE_PROVIDER_QUERY_KEY, context.getServiceProviderName());
}
// different threads.
synchronized (context) {
if (!context.isActiveInAThread()) {
// Marks this context is active in a thread. We only allow at a single instance, a context
// to be active in only a single thread. In other words, same context cannot active in two
// different threads at the same time.
context.setActiveInAThread(true);
if (log.isDebugEnabled()) {
log.debug("Context id: " + context.getContextIdentifier() + " is active in the thread " + "with id: " + Thread.currentThread().getId());
}
} else {
log.error("Same context is currently in used by a different thread. Possible double submit.");
if (log.isDebugEnabled()) {
log.debug("Same context is currently in used by a different thread. Possible double submit." + "\n" + "Context id: " + context.getContextIdentifier() + "\n" + "Originating address: " + request.getRemoteAddr() + "\n" + "Request Headers: " + getHeaderString(request) + "\n" + "Thread Id: " + Thread.currentThread().getId());
}
FrameworkUtils.sendToRetryPage(request, responseWrapper, context);
return;
}
}
/*
If
Request specify to restart the flow again from first step by passing `restart_flow`.
OR
Identifier first request received and current step does not contains any flow handler.
(To handle browser back with only with identifier-first and basic)
*/
if (isBackToFirstStepRequest(request) || (isIdentifierFirstRequest(request) && !isFlowHandlerInCurrentStepCanHandleRequest(context, request))) {
if (isCompletedStepsAreFlowHandlersOnly(context)) {
// authenticated authenticator, then we reset the current step to 1.
if (log.isDebugEnabled()) {
log.debug("Restarting the authentication flow from step 1 for " + context.getContextIdentifier());
}
context.setCurrentStep(0);
context.setProperty(BACK_TO_FIRST_STEP, true);
Map<String, String> runtimeParams = context.getAuthenticatorParams(FrameworkConstants.JSAttributes.JS_COMMON_OPTIONS);
runtimeParams.put(FrameworkConstants.JSAttributes.JS_OPTIONS_USERNAME, null);
FrameworkUtils.resetAuthenticationContext(context);
returning = false;
// IDF should be the first step.
context.getCurrentAuthenticatedIdPs().clear();
} else {
// If the incoming request is restart and the completed steps have authenticators as the
// authenticated authenticator, then we redirect to retry page.
String msg = "Restarting the authentication flow failed because there is/are authenticator/s " + "available in the completed steps for " + context.getContextIdentifier();
if (log.isDebugEnabled()) {
log.debug(msg);
}
throw new MisconfigurationException(msg);
}
}
setSPAttributeToRequest(request, context);
context.setReturning(returning);
// if this is the flow start, store the original request in the context
if (!context.isReturning() && authRequest != null) {
context.setAuthenticationRequest(authRequest.getAuthenticationRequest());
}
if (!context.isLogoutRequest()) {
FrameworkUtils.getAuthenticationRequestHandler().handle(request, responseWrapper, context);
} else {
FrameworkUtils.getLogoutRequestHandler().handle(request, responseWrapper, context);
}
} else {
if (log.isDebugEnabled()) {
String key = request.getParameter("sessionDataKey");
if (key == null) {
log.debug("Session data key is null in the request");
} else {
log.debug("Session data key : " + key);
}
}
String userAgent = request.getHeader("User-Agent");
String referer = request.getHeader("Referer");
String message = "Requested client: " + request.getRemoteAddr() + ", URI :" + request.getMethod() + ":" + request.getRequestURI() + ", User-Agent: " + userAgent + " , Referer: " + referer;
log.error("Context does not exist. Probably due to invalidated cache. " + message);
FrameworkUtils.sendToRetryPage(request, responseWrapper, context);
}
} catch (JsFailureException e) {
if (log.isDebugEnabled()) {
log.debug("Script initiated Exception occured.", e);
}
publishAuthenticationFailure(request, context, context.getSequenceConfig().getAuthenticatedUser(), e.getErrorCode());
if (log.isDebugEnabled()) {
log.debug("User will be redirected to retry page or the error page provided by script.");
}
} catch (MisconfigurationException e) {
FrameworkUtils.sendToRetryPage(request, responseWrapper, context, "misconfiguration.error", "something.went.wrong.contact.admin");
} catch (PostAuthenticationFailedException e) {
if (log.isDebugEnabled()) {
log.debug("Error occurred while evaluating post authentication", e);
}
FrameworkUtils.removeCookie(request, responseWrapper, FrameworkUtils.getPASTRCookieName(context.getContextIdentifier()));
publishAuthenticationFailure(request, context, context.getSequenceConfig().getAuthenticatedUser(), e.getErrorCode());
FrameworkUtils.sendToRetryPage(request, responseWrapper, context, "authentication.attempt.failed", "authorization.failed");
} catch (Throwable e) {
if ((e instanceof FrameworkException) && (NONCE_ERROR_CODE.equals(((FrameworkException) e).getErrorCode()))) {
if (log.isDebugEnabled()) {
log.debug(e.getMessage(), e);
}
FrameworkUtils.sendToRetryPage(request, response, context, "suspicious.authentication.attempts", "suspicious.authentication.attempts.description");
} else {
log.error("Exception in Authentication Framework", e);
FrameworkUtils.sendToRetryPage(request, responseWrapper, context);
}
} finally {
UserCoreUtil.setDomainInThreadLocal(null);
if (context != null) {
// Mark this context left the thread. Now another thread can use this context.
context.setActiveInAThread(false);
if (log.isDebugEnabled()) {
log.debug("Context id: " + context.getContextIdentifier() + " left the thread with id: " + Thread.currentThread().getId());
}
// If flow is not about to conclude.
if (!LoginContextManagementUtil.isPostAuthenticationExtensionCompleted(context) || context.isLogoutRequest()) {
// Persist the context.
FrameworkUtils.addAuthenticationContextToCache(context.getContextIdentifier(), context);
if (log.isDebugEnabled()) {
log.debug("Context with id: " + context.getContextIdentifier() + " added to the cache.");
}
}
// Clear the auto login related cookies only during none passive authentication flow.
if (!context.isPassiveAuthenticate()) {
FrameworkUtils.removeALORCookie(request, response);
}
}
unwrapResponse(responseWrapper, sessionDataKey, response, context);
}
}
use of org.wso2.carbon.identity.api.server.authenticators.v1.model.Authenticator in project carbon-identity-framework by wso2.
the class JITProvisioningPostAuthenticationHandler method callDefaultProvisioningHandler.
/**
* To call the default provisioning handler.
*
* @param username Name of the user to be provisioning.
* @param context Authentication Context.
* @param externalIdPConfig Relevant external IDP Config.
* @param localClaimValues Local Claim Values.
* @param stepConfig Step Config.
* @throws PostAuthenticationFailedException Post Authentication Failed Exception.
*/
private void callDefaultProvisioningHandler(String username, AuthenticationContext context, ExternalIdPConfig externalIdPConfig, Map<String, String> localClaimValues, StepConfig stepConfig) throws PostAuthenticationFailedException {
boolean useDefaultIdpDialect = externalIdPConfig.useDefaultLocalIdpDialect();
ApplicationAuthenticator authenticator = stepConfig.getAuthenticatedAutenticator().getApplicationAuthenticator();
String idPStandardDialect = authenticator.getClaimDialectURI();
String idpRoleClaimUri = FrameworkUtils.getIdpRoleClaimUri(externalIdPConfig);
Map<ClaimMapping, String> extAttrs = stepConfig.getAuthenticatedUser().getUserAttributes();
Map<String, String> originalExternalAttributeValueMap = FrameworkUtils.getClaimMappings(extAttrs, false);
Map<String, String> claimMapping = null;
boolean excludeUnmappedRoles = false;
if (useDefaultIdpDialect && StringUtils.isNotBlank(idPStandardDialect)) {
try {
claimMapping = ClaimMetadataHandler.getInstance().getMappingsMapFromOtherDialectToCarbon(idPStandardDialect, originalExternalAttributeValueMap.keySet(), context.getTenantDomain(), true);
} catch (ClaimMetadataException e) {
throw new PostAuthenticationFailedException(ErrorMessages.ERROR_WHILE_HANDLING_CLAIM_MAPPINGS.getCode(), ErrorMessages.ERROR_WHILE_HANDLING_CLAIM_MAPPINGS.getMessage(), e);
}
}
if (claimMapping != null) {
// Ex. Standard dialects like OIDC.
idpRoleClaimUri = claimMapping.get(IdentityUtil.getLocalGroupsClaimURI());
} else if (idPStandardDialect == null && !useDefaultIdpDialect) {
// Ex. SAML custom claims.
idpRoleClaimUri = FrameworkUtils.getIdpRoleClaimUri(externalIdPConfig);
}
/* Get the mapped user roles according to the mapping in the IDP configuration. Exclude the unmapped from the
returned list.
*/
if (StringUtils.isNotEmpty(IdentityUtil.getProperty(SEND_ONLY_LOCALLY_MAPPED_ROLES_OF_IDP))) {
excludeUnmappedRoles = Boolean.parseBoolean(IdentityUtil.getProperty(SEND_ONLY_LOCALLY_MAPPED_ROLES_OF_IDP));
}
List<String> identityProviderMappedUserRolesUnmappedExclusive = FrameworkUtils.getIdentityProvideMappedUserRoles(externalIdPConfig, originalExternalAttributeValueMap, idpRoleClaimUri, excludeUnmappedRoles);
localClaimValues.put(FrameworkConstants.ASSOCIATED_ID, stepConfig.getAuthenticatedUser().getAuthenticatedSubjectIdentifier());
localClaimValues.put(FrameworkConstants.IDP_ID, stepConfig.getAuthenticatedIdP());
/*
If TOTP is enabled for federated users, the initial federated user login will be identified with the following
check and will set the secret key claim for the federated user who is going to be provisioned.
*/
if (context.getProperty(FrameworkConstants.SECRET_KEY_CLAIM_URL) != null) {
localClaimValues.put(FrameworkConstants.SECRET_KEY_CLAIM_URL, context.getProperty(FrameworkConstants.SECRET_KEY_CLAIM_URL).toString());
}
// Remove role claim from local claims as roles are specifically handled.
localClaimValues.remove(FrameworkUtils.getLocalClaimUriMappedForIdPRoleClaim(externalIdPConfig));
localClaimValues.remove(UserCoreConstants.USER_STORE_GROUPS_CLAIM);
try {
FrameworkUtils.getStepBasedSequenceHandler().callJitProvisioning(username, context, identityProviderMappedUserRolesUnmappedExclusive, localClaimValues);
} catch (FrameworkException e) {
handleExceptions(String.format(ERROR_WHILE_TRYING_TO_PROVISION_USER_WITHOUT_PASSWORD_PROVISIONING.getMessage(), username, externalIdPConfig.getName()), ERROR_WHILE_TRYING_TO_PROVISION_USER_WITHOUT_PASSWORD_PROVISIONING.getCode(), e);
}
}
use of org.wso2.carbon.identity.api.server.authenticators.v1.model.Authenticator in project carbon-identity-framework by wso2.
the class ThriftAuthenticationServiceComponent method startThriftHttpAuthenticatorService.
private void startThriftHttpAuthenticatorService(ThriftAuthenticatorService thriftAuthenticatorService) {
// servlet based authenticator service for authentication for now.
try {
AuthenticatorService.Processor authServiceProcessor = new AuthenticatorService.Processor(new AuthenticatorServiceImpl(thriftAuthenticatorService));
TCompactProtocol.Factory inProtFactory = new TCompactProtocol.Factory();
TCompactProtocol.Factory outProtFactory = new TCompactProtocol.Factory();
getHttpServiceInstance().registerServlet("/thriftAuthenticator", new AuthenticatorServlet(authServiceProcessor, inProtFactory, outProtFactory), new Hashtable(), getHttpServiceInstance().createDefaultHttpContext());
} catch (ServletException e) {
log.error("Unable to start Thrift Authenticator Service.", e);
} catch (NamespaceException e) {
log.error("Unable to start Thrift Authenticator Service", e);
}
}
use of org.wso2.carbon.identity.api.server.authenticators.v1.model.Authenticator in project carbon-identity-framework by wso2.
the class IdPManagementUIUtil method buildFacebookAuthenticationConfiguration.
/**
* @param fedIdp
* @param paramMap
* @throws IdentityApplicationManagementException
*/
private static void buildFacebookAuthenticationConfiguration(IdentityProvider fedIdp, Map<String, String> paramMap) throws IdentityApplicationManagementException {
FederatedAuthenticatorConfig facebookAuthnConfig = new FederatedAuthenticatorConfig();
facebookAuthnConfig.setName("FacebookAuthenticator");
facebookAuthnConfig.setDisplayName("facebook");
if ("on".equals(paramMap.get("fbAuthEnabled"))) {
facebookAuthnConfig.setEnabled(true);
}
if ("on".equals(paramMap.get("fbAuthDefault"))) {
fedIdp.setDefaultAuthenticatorConfig(facebookAuthnConfig);
}
Property[] properties = new Property[8];
Property property = new Property();
property.setName(IdentityApplicationConstants.Authenticator.Facebook.CLIENT_ID);
property.setValue(paramMap.get("fbClientId"));
properties[0] = property;
property = new Property();
property.setName(IdentityApplicationConstants.Authenticator.Facebook.CLIENT_SECRET);
property.setValue(paramMap.get("fbClientSecret"));
property.setConfidential(true);
properties[1] = property;
property = new Property();
property.setName(IdentityApplicationConstants.Authenticator.Facebook.SCOPE);
property.setValue(paramMap.get("fbScope"));
properties[2] = property;
property = new Property();
property.setName(IdentityApplicationConstants.Authenticator.Facebook.USER_INFO_FIELDS);
String fbUserInfoFields = paramMap.get("fbUserInfoFields");
if (fbUserInfoFields != null && fbUserInfoFields.endsWith(",")) {
fbUserInfoFields = fbUserInfoFields.substring(0, fbUserInfoFields.length() - 1);
}
property.setValue(fbUserInfoFields);
properties[3] = property;
property = new Property();
property.setName(IdentityApplicationConstants.Authenticator.Facebook.AUTH_ENDPOINT);
property.setValue(paramMap.get("fbAuthnEndpoint"));
properties[4] = property;
property = new Property();
property.setName(IdentityApplicationConstants.Authenticator.Facebook.AUTH_TOKEN_ENDPOINT);
property.setValue(paramMap.get("fbOauth2TokenEndpoint"));
properties[5] = property;
property = new Property();
property.setName(IdentityApplicationConstants.Authenticator.Facebook.USER_INFO_ENDPOINT);
property.setValue(paramMap.get("fbUserInfoEndpoint"));
properties[6] = property;
property = new Property();
property.setName(IdentityApplicationConstants.Authenticator.Facebook.CALLBACK_URL);
property.setValue(paramMap.get("fbCallBackUrl"));
properties[7] = property;
facebookAuthnConfig.setProperties(properties);
FederatedAuthenticatorConfig[] authenticators = fedIdp.getFederatedAuthenticatorConfigs();
if (paramMap.get("fbClientId") != null && !"".equals(paramMap.get("fbClientId")) && paramMap.get("fbClientSecret") != null && !"".equals(paramMap.get("fbClientSecret"))) {
// facebook authenticator cannot exist without client id and client secret.
if (authenticators == null || authenticators.length == 0) {
fedIdp.setFederatedAuthenticatorConfigs(new FederatedAuthenticatorConfig[] { facebookAuthnConfig });
} else {
fedIdp.setFederatedAuthenticatorConfigs(concatArrays(new FederatedAuthenticatorConfig[] { facebookAuthnConfig }, authenticators));
}
}
}
Aggregations