Java Code Examples for org.wso2.carbon.identity.core.util.IdentityUtil#isTokenLoggable()

The following examples show how to use org.wso2.carbon.identity.core.util.IdentityUtil#isTokenLoggable() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EntitlementEngine.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Evaluates the given XACML request and returns the Response
 *
 * @param requestCtx Balana Object model for request
 * @param xacmlRequest Balana Object model for request
 * @return ResponseCtx  Balana Object model for response
 */
public ResponseCtx evaluate(AbstractRequestCtx requestCtx, String xacmlRequest) {

    if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_REQUEST)) {
        log.debug("XACML Request : " + xacmlRequest);
    }

    ResponseCtx xacmlResponse;

    if ((xacmlResponse = (ResponseCtx) getFromCache(xacmlRequest, false)) != null) {
        if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_RESPONSE)) {
            log.debug("XACML Response : " + xacmlResponse);
        }
        return xacmlResponse;
    }

    xacmlResponse = pdp.evaluate(requestCtx);

    addToCache(xacmlRequest, xacmlResponse, false);

    if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_RESPONSE)) {
        log.debug("XACML Response : " + xacmlResponse);
    }
    return xacmlResponse;
}
 
Example 2
Source File: EntitlementEngine.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Test request for PDP
 *
 * @param xacmlRequest XACML request as String
 * @return response as String
 */
public String test(String xacmlRequest) {

    if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_REQUEST)) {
        log.debug("XACML Request : " + xacmlRequest);
    }

    String xacmlResponse = pdpTest.evaluate(xacmlRequest);

    if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_RESPONSE)) {
        log.debug("XACML Response : " + xacmlResponse);
    }

    return xacmlResponse;
}
 
Example 3
Source File: EntitlementEngine.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Evaluates the given XACML request and returns the Response that the EntitlementEngine will
 * hand back to the PEP. Here PEP does not need construct the XACML request before sending it to the
 * EntitlementEngine. Just can send the single attribute value. But here default attribute ids and data types
 * are used
 *
 * @param subject     subject
 * @param resource    resource
 * @param action      action
 * @param environment environment
 * @return XACML request as String object
 * @throws Exception throws, if fails
 */
public String evaluate(String subject, String resource, String action, String[] environment)
        throws Exception {

    String environmentValue = null;
    if (environment != null && environment.length > 0) {
        environmentValue = environment[0];
    }
    String response;
    String request = (subject != null ? subject : "") + (resource != null ? resource : "") +
            (action != null ? action : "") + (environmentValue != null ? environmentValue : "");

    if ((response = (String) getFromCache(request, true)) != null) {
        if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_REQUEST)) {
            log.debug("XACML Request : " + EntitlementUtil.
                    createSimpleXACMLRequest(subject, resource, action, environmentValue));
        }
        if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_RESPONSE)) {
            log.debug("XACML Response : " + response);
        }
        return response;
    }

    String requestAsString = EntitlementUtil.createSimpleXACMLRequest(subject, resource, action, environmentValue);

    if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_REQUEST)) {
        log.debug("XACML Request : " + requestAsString);
    }

    response = pdp.evaluate(requestAsString);

    addToCache(request, response, true);

    if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_RESPONSE)) {
        log.debug("XACML Response : " + response);
    }

    return response;
}
 
Example 4
Source File: EntitlementEngine.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Test request for PDP
 *
 * @param xacmlRequest XACML request as String
 * @return response as String
 */
public String test(String xacmlRequest) {

    if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_REQUEST)) {
        log.debug("XACML Request : " + xacmlRequest);
    }

    String xacmlResponse = pdpTest.evaluate(xacmlRequest);

    if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_RESPONSE)) {
        log.debug("XACML Response : " + xacmlResponse);
    }

    return xacmlResponse;
}
 
Example 5
Source File: EntitlementEngine.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Evaluates the given XACML request and returns the Response that the EntitlementEngine will
 * hand back to the PEP. Here PEP does not need construct the XACML request before sending it to the
 * EntitlementEngine. Just can send the single attribute value. But here default attribute ids and data types
 * are used
 *
 * @param subject     subject
 * @param resource    resource
 * @param action      action
 * @param environment environment
 * @return XACML request as String object
 * @throws Exception throws, if fails
 */
public String evaluate(String subject, String resource, String action, String[] environment)
        throws Exception {

    String environmentValue = null;
    if (environment != null && environment.length > 0) {
        environmentValue = environment[0];
    }
    String response;
    String request = (subject != null ? subject : "") + (resource != null ? resource : "") +
                     (action != null ? action : "") + (environmentValue != null ? environmentValue : "");

    if ((response = getFromCache(request, true)) != null) {
        if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_REQUEST)) {
            log.debug("XACML Request : " + EntitlementUtil.
                    createSimpleXACMLRequest(subject, resource, action, environmentValue));
        }
        if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_RESPONSE)) {
            log.debug("XACML Response : " + response);
        }
        return response;
    }

    String requestAsString = EntitlementUtil.createSimpleXACMLRequest(subject, resource, action, environmentValue);

    if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_REQUEST)) {
        log.debug("XACML Request : " + requestAsString);
    }

    response = pdp.evaluate(requestAsString);

    addToCache(request, response, true);

    if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_RESPONSE)) {
        log.debug("XACML Response : " + response);
    }

    return response;
}
 
Example 6
Source File: OpenIDConnectAuthenticator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
protected void buildClaimMappings(Map<ClaimMapping, String> claims, Map.Entry<String, Object> entry, String
        separator) {
    String claimValue = null;
    if (StringUtils.isBlank(separator)) {
        separator = IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR_DEFAULT;
    }
    try {
        JSONArray jsonArray = (JSONArray) JSONValue.parseWithException(entry.getValue().toString());
        if (jsonArray != null && jsonArray.size() > 0) {
            Iterator attributeIterator = jsonArray.iterator();
            while (attributeIterator.hasNext()) {
                if (claimValue == null) {
                    claimValue = attributeIterator.next().toString();
                } else {
                    claimValue = claimValue + separator + attributeIterator.next().toString();
                }
            }

        }
    } catch (Exception e) {
        claimValue = entry.getValue().toString();
    }

    claims.put(ClaimMapping.build(entry.getKey(), entry.getKey(), null, false), claimValue);
    if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.USER_CLAIMS)) {
        log.debug("Adding claim mapping : " + entry.getKey() + " <> " + entry.getKey() + " : " + claimValue);
    }

}
 
Example 7
Source File: FacebookAuthenticator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> getUserInfoJson(String fbAuthUserInfoUrl, String userInfoFields, String token)
        throws ApplicationAuthenticatorException {

    String userInfoString = getUserInfoString(fbAuthUserInfoUrl, userInfoFields, token);
    if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.USER_ID_TOKEN)) {
        log.debug("UserInfoString : " + userInfoString);
    }
    Map<String, Object> jsonObject = JSONUtils.parseJSON(userInfoString);
    return jsonObject;
}
 
Example 8
Source File: FacebookAuthenticator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public void buildClaims(AuthenticationContext context, Map<String, Object> jsonObject)
        throws ApplicationAuthenticatorException {
    if (jsonObject != null) {
        Map<ClaimMapping, String> claims = new HashMap<ClaimMapping, String>();

        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            claims.put(ClaimMapping.build(entry.getKey(), entry.getKey(), null,
                    false), entry.getValue().toString());
            if (log.isDebugEnabled() &&
                    IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.USER_CLAIMS)) {
                log.debug("Adding claim mapping : " + entry.getKey() + " <> " + entry.getKey() + " : "
                        + entry.getValue());
            }

        }
        if (StringUtils.isBlank(context.getExternalIdP().getIdentityProvider().getClaimConfig().getUserClaimURI())) {
            context.getExternalIdP().getIdentityProvider().getClaimConfig().setUserClaimURI
                    (FacebookAuthenticatorConstants.EMAIL);
        }
        String subjectFromClaims = FrameworkUtils.getFederatedSubjectFromClaims(
                context.getExternalIdP().getIdentityProvider(), claims);
        if (subjectFromClaims != null && !subjectFromClaims.isEmpty()) {
            AuthenticatedUser authenticatedUser =
                    AuthenticatedUser.createFederateAuthenticatedUserFromSubjectIdentifier(subjectFromClaims);
            context.setSubject(authenticatedUser);
        } else {
            setSubject(context, jsonObject);
        }

        context.getSubject().setUserAttributes(claims);

    } else {
        if (log.isDebugEnabled()) {
            log.debug("Decoded json object is null");
        }
        throw new ApplicationAuthenticatorException("Decoded json object is null");
    }
}
 
Example 9
Source File: EntitlementEngine.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
/**
 * Evaluates the given XACML request and returns the Response that the EntitlementEngine will
 * hand back to the PEP. PEP needs construct the XACML request before sending it to the
 * EntitlementEngine
 *
 * @param xacmlRequest XACML request as String
 * @return XACML response as String
 * @throws org.wso2.balana.ParsingException                          throws
 * @throws org.wso2.carbon.identity.entitlement.EntitlementException throws
 */

public String evaluate(String xacmlRequest) throws EntitlementException, ParsingException {

    if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_REQUEST)) {
        log.debug("XACML Request : " + xacmlRequest);
    }

    String xacmlResponse;

    if ((xacmlResponse = (String) getFromCache(xacmlRequest, false)) != null) {
        if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_RESPONSE)) {
            log.debug("XACML Response : " + xacmlResponse);
        }
        return xacmlResponse;
    }

    Map<PIPExtension, Properties> extensions = EntitlementServiceComponent.getEntitlementConfig()
            .getExtensions();

    if (extensions != null && !extensions.isEmpty()) {
        PolicyRequestBuilder policyRequestBuilder = new PolicyRequestBuilder();
        Element xacmlRequestElement = policyRequestBuilder.getXacmlRequest(xacmlRequest);
        AbstractRequestCtx requestCtx = RequestCtxFactory.getFactory().
                getRequestCtx(xacmlRequestElement);
        Set<PIPExtension> pipExtensions = extensions.keySet();
        for (PIPExtension pipExtension : pipExtensions) {
            pipExtension.update(requestCtx);
        }
        ResponseCtx responseCtx = pdp.evaluate(requestCtx);
        xacmlResponse = responseCtx.encode();
    } else {
        xacmlResponse = pdp.evaluate(xacmlRequest);
    }

    addToCache(xacmlRequest, xacmlResponse, false);

    if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_RESPONSE)) {
        log.debug("XACML Response : " + xacmlResponse);
    }

    return xacmlResponse;

}
 
Example 10
Source File: EntitlementEngine.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
/**
 * Evaluates the given XACML request and returns the ResponseCtx Response that the EntitlementEngine will
 * hand back to the PEP. PEP needs construct the XACML request before sending it to the
 * EntitlementEngine
 *
 * @param xacmlRequest XACML request as String
 * @return ResponseCtx response
 * @throws org.wso2.balana.ParsingException                          throws
 * @throws org.wso2.carbon.identity.entitlement.EntitlementException throws
 * @throws javax.xml.parsers.ParserConfigurationException            throws
 * @throws org.xml.sax.SAXException                                  throws
 * @throws java.io.IOException                                       throws
 */

public ResponseCtx evaluateReturnResponseCtx(String xacmlRequest) throws EntitlementException, ParsingException,
        ParserConfigurationException, SAXException, IOException {

    if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_REQUEST)) {
        log.debug("XACML Request : " + xacmlRequest);
    }

    String xacmlResponse;
    ResponseCtx responseCtx;

    if ((xacmlResponse = (String) getFromCache(xacmlRequest, false)) != null) {
        if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_RESPONSE)) {
            log.debug("XACML Response : " + xacmlResponse);
        }

        DocumentBuilderFactory documentBuilderFactory = IdentityUtil.getSecuredDocumentBuilderFactory();
        Element node = documentBuilderFactory.newDocumentBuilder().parse
                (new ByteArrayInputStream(xacmlResponse.getBytes())).getDocumentElement();


        return (ResponseCtx.getInstance(node));

    }

    Map<PIPExtension, Properties> extensions = EntitlementServiceComponent.getEntitlementConfig()
            .getExtensions();

    if (extensions != null && !extensions.isEmpty()) {
        PolicyRequestBuilder policyRequestBuilder = new PolicyRequestBuilder();
        Element xacmlRequestElement = policyRequestBuilder.getXacmlRequest(xacmlRequest);
        AbstractRequestCtx requestCtx = RequestCtxFactory.getFactory().
                getRequestCtx(xacmlRequestElement);
        Set<PIPExtension> pipExtensions = extensions.keySet();
        for (PIPExtension pipExtension : pipExtensions) {
            pipExtension.update(requestCtx);
        }
        responseCtx = pdp.evaluate(requestCtx);
    } else {
        responseCtx = pdp.evaluateReturnResponseCtx(xacmlRequest);
    }

    xacmlResponse = responseCtx.encode();

    addToCache(xacmlRequest, xacmlResponse, false);

    if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_RESPONSE)) {
        log.debug("XACML Response : " + xacmlResponse);
    }

    return responseCtx;

}
 
Example 11
Source File: EntitlementEngine.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * Evaluates the given XACML request and returns the Response that the EntitlementEngine will
 * hand back to the PEP. PEP needs construct the XACML request before sending it to the
 * EntitlementEngine
 *
 * @param xacmlRequest XACML request as String
 * @return XACML response as String
 * @throws org.wso2.balana.ParsingException                          throws
 * @throws org.wso2.carbon.identity.entitlement.EntitlementException throws
 */

public String evaluate(String xacmlRequest) throws EntitlementException, ParsingException {

    if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_REQUEST)) {
        log.debug("XACML Request : " + xacmlRequest);
    }

    String xacmlResponse;

    if ((xacmlResponse = getFromCache(xacmlRequest, false)) != null) {
        if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_RESPONSE)) {
            log.debug("XACML Response : " + xacmlResponse);
        }
        return xacmlResponse;
    }

    Map<PIPExtension, Properties> extensions = EntitlementServiceComponent.getEntitlementConfig()
            .getExtensions();

    if (extensions != null && !extensions.isEmpty()) {
        PolicyRequestBuilder policyRequestBuilder = new PolicyRequestBuilder();
        Element xacmlRequestElement = policyRequestBuilder.getXacmlRequest(xacmlRequest);
        AbstractRequestCtx requestCtx = RequestCtxFactory.getFactory().
                getRequestCtx(xacmlRequestElement);
        Set<PIPExtension> pipExtensions = extensions.keySet();
        for (PIPExtension pipExtension : pipExtensions) {
            pipExtension.update(requestCtx);
        }
        ResponseCtx responseCtx = pdp.evaluate(requestCtx);
        xacmlResponse = responseCtx.encode();
    } else {
        xacmlResponse = pdp.evaluate(xacmlRequest);
    }

    addToCache(xacmlRequest, xacmlResponse, false);

    if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.XACML_RESPONSE)) {
        log.debug("XACML Response : " + xacmlResponse);
    }

    return xacmlResponse;

}
 
Example 12
Source File: OpenIDConnectAuthenticator.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * Get subject attributes.
 * @param token OAuthClientResponse
 * @param authenticatorProperties Map<String, String> (Authenticator property, Property value)
 * @return Map<ClaimMapping, String> Claim mappings.
 */
protected Map<ClaimMapping, String> getSubjectAttributes(OAuthClientResponse token,
                                                         Map<String, String> authenticatorProperties) {

    Map<ClaimMapping, String> claims = new HashMap<>();

    try {
        String accessToken = token.getParam(OIDCAuthenticatorConstants.ACCESS_TOKEN);
        String url = getUserInfoEndpoint(token, authenticatorProperties);
        String json = sendRequest(url, accessToken);

        if (StringUtils.isBlank(json)) {
            if(log.isDebugEnabled()) {
                log.debug("Empty JSON response from user info endpoint. Unable to fetch user claims." +
                        " Proceeding without user claims");
            }
            return claims;
        }

        Map<String, Object> jsonObject = JSONUtils.parseJSON(json);

        for (Map.Entry<String, Object> data : jsonObject.entrySet()) {
            String key = data.getKey();
            Object value = data.getValue();

            if (value != null) {
                claims.put(ClaimMapping.build(key, key, null, false), value.toString());
            }

            if (log.isDebugEnabled() &&
                    IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.USER_CLAIMS)) {
                log.debug("Adding claims from end-point data mapping : " + key + " - " +
                        jsonObject.get(key).toString());
            }
        }
    } catch (IOException e) {
        log.error("Communication error occurred while accessing user info endpoint", e);
    }

    return claims;
}
 
Example 13
Source File: YahooOAuth2Authenticator.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * Get subject attributes.
 *
 * @param token                   OAuthClientResponse
 * @param authenticatorProperties Map<String, String>
 * @return Map<ClaimMapping, String> Claim mappings.
 */
protected Map<ClaimMapping, String> getSubjectAttributes(OAuthClientResponse token,
                                                         Map<String, String> authenticatorProperties) {

    Map<ClaimMapping, String> claims = new HashMap<>();

    try {
        String accessToken = token.getParam(OIDCAuthenticatorConstants.ACCESS_TOKEN);
        String url = getUserInfoEndpoint(token, authenticatorProperties);
        String json = sendRequest(url, accessToken);

        if (StringUtils.isBlank(json)) {
            if (log.isDebugEnabled()) {
                log.debug("Unable to fetch user claims. Proceeding without user claims");
            }
            return claims;
        }

        Map<String, Object> jsonObject = JSONUtils.parseJSON(json);
        Map<String, Object> profile = null;

        if (!jsonObject.isEmpty()) {

            // Extract the inner profile JSON object.
            profile = JSONUtils.parseJSON(jsonObject.entrySet().iterator().next().getValue().toString());
        }

        if (profile == null) {
            if (log.isDebugEnabled()) {
                log.debug("Invalid user profile object. Proceeding without user claims");
            }
            return claims;
        }

        for (Map.Entry<String, Object> data : profile.entrySet()) {
            String key = data.getKey();
            claims.put(ClaimMapping.build(key, key, null, false), profile.get(key).toString());

            if (log.isDebugEnabled()
                    && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.USER_CLAIMS)) {
                log.debug("Adding claims from end-point data mapping : " + key + " - " +
                        profile.get(key).toString());
            }
        }
    } catch (IOException e) {
        log.error("Communication error occurred while accessing user info endpoint", e);
    }
    return claims;
}
 
Example 14
Source File: ClaimUtil.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public static Map<String, Object> getClaimsFromUserStore(OAuth2TokenValidationResponseDTO tokenResponse) throws
        UserInfoEndpointException {
    String username = tokenResponse.getAuthorizedUser();
    String tenantDomain = MultitenantUtils.getTenantDomain(tokenResponse.getAuthorizedUser());
    UserRealm realm;
    List<String> claimURIList = new ArrayList<>();
    Map<String, Object> mappedAppClaims = new HashMap<>();

    try {
        realm = IdentityTenantUtil.getRealm(tenantDomain, username);

        if (realm == null) {
            log.warn("No valid tenant domain provider. Empty claim returned back");
            return new HashMap<>();
        }

        Map<String, String> spToLocalClaimMappings;

        UserStoreManager userstore = realm.getUserStoreManager();

        // need to get all the requested claims
        Map<String, String> requestedLocalClaimMap = ClaimManagerHandler.getInstance()
                .getMappingsMapFromOtherDialectToCarbon(SP_DIALECT, null, tenantDomain, true);
        if (MapUtils.isNotEmpty(requestedLocalClaimMap)) {
            for (String s : requestedLocalClaimMap.keySet()) {
                claimURIList.add(s);

            }
            if (log.isDebugEnabled()) {
                log.debug("Requested number of local claims: " + claimURIList.size());
            }

            spToLocalClaimMappings = ClaimManagerHandler.getInstance().getMappingsMapFromOtherDialectToCarbon
                    (SP_DIALECT, null, tenantDomain, false);

            Map<String, String> userClaims = userstore.getUserClaimValues(MultitenantUtils.getTenantAwareUsername
                    (username), claimURIList.toArray(new String[claimURIList.size()]), null);
            if (log.isDebugEnabled()) {
                log.debug("User claims retrieved from user store: " + userClaims.size());
            }

            if (MapUtils.isEmpty(userClaims)) {
                return new HashMap<>();
            }

            for (Map.Entry<String, String> entry : spToLocalClaimMappings.entrySet()) {
                String value = userClaims.get(entry.getValue());
                if (value != null) {
                    mappedAppClaims.put(entry.getKey(), value);
                    if (log.isDebugEnabled() &&
                            IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.USER_CLAIMS)) {
                        log.debug("Mapped claim: key -  " + entry.getKey() + " value -" + value);
                    }
                }
            }
        }

    } catch (Exception e) {
        if(e instanceof UserStoreException){
            if (e.getMessage().contains("UserNotFound")) {
                if (log.isDebugEnabled()) {
                    log.debug("User " + username + " not found in user store");
                }
            }
        } else {
            log.error("Error while retrieving the claims from user store for " + username, e);
            throw new UserInfoEndpointException("Error while retrieving the claims from user store for " + username);
        }
    }
    return mappedAppClaims;
}
 
Example 15
Source File: SAMLAssertionClaimsCallback.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * Get claims from user store
 *
 * @param requestMsgCtx Token request message context
 * @return Users claim map
 * @throws Exception
 */
private static Map<String, Object> getClaimsFromUserStore(OAuthTokenReqMessageContext requestMsgCtx)
        throws UserStoreException, IdentityApplicationManagementException, IdentityException {

    String username = requestMsgCtx.getAuthorizedUser().toString();
    String tenantDomain = requestMsgCtx.getAuthorizedUser().getTenantDomain();

    UserRealm realm;
    List<String> claimURIList = new ArrayList<String>();
    Map<String, Object> mappedAppClaims = new HashMap<String, Object>();

    ApplicationManagementService applicationMgtService = OAuth2ServiceComponentHolder.getApplicationMgtService();
    String spName = applicationMgtService
            .getServiceProviderNameByClientId(requestMsgCtx.getOauth2AccessTokenReqDTO().getClientId(),
                                              INBOUND_AUTH2_TYPE, tenantDomain);
    ServiceProvider serviceProvider = applicationMgtService.getApplicationExcludingFileBasedSPs(spName,
                                                                                                tenantDomain);
    if (serviceProvider == null) {
        return mappedAppClaims;
    }

    realm = IdentityTenantUtil.getRealm(tenantDomain, username);
    if (realm == null) {
        log.warn("No valid tenant domain provider. Empty claim returned back for tenant " + tenantDomain
                 + " and user " + username);
        return new HashMap<>();
    }

    Map<String, String> spToLocalClaimMappings;
    UserStoreManager userStoreManager = realm.getUserStoreManager();
    ClaimMapping[] requestedLocalClaimMap = serviceProvider.getClaimConfig().getClaimMappings();

    if (requestedLocalClaimMap != null && requestedLocalClaimMap.length > 0) {

        for (ClaimMapping mapping : requestedLocalClaimMap) {
            if (mapping.isRequested()) {
                claimURIList.add(mapping.getLocalClaim().getClaimUri());
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("Requested number of local claims: " + claimURIList.size());
        }

        spToLocalClaimMappings = ClaimManagerHandler.getInstance().getMappingsMapFromOtherDialectToCarbon(
                SP_DIALECT, null, tenantDomain, false);

        Map<String, String> userClaims = null;
        try {
            userClaims = userStoreManager.getUserClaimValues(
                    MultitenantUtils.getTenantAwareUsername(username),
                    claimURIList.toArray(new String[claimURIList.size()]), null);
        } catch (UserStoreException e) {
            if (e.getMessage().contains("UserNotFound")) {
                if (log.isDebugEnabled()) {
                    log.debug("User " + username + " not found in user store");
                }
            } else {
                throw e;
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("Number of user claims retrieved from user store: " + userClaims.size());
        }

        if (MapUtils.isEmpty(userClaims)) {
            return new HashMap<>();
        }

        for (Iterator<Map.Entry<String, String>> iterator = spToLocalClaimMappings.entrySet().iterator(); iterator
                .hasNext(); ) {
            Map.Entry<String, String> entry = iterator.next();
            String value = userClaims.get(entry.getValue());
            if (value != null) {
                mappedAppClaims.put(entry.getKey(), value);
                if (log.isDebugEnabled() &&
                        IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.USER_CLAIMS)) {
                    log.debug("Mapped claim: key -  " + entry.getKey() + " value -" + value);
                }
            }
        }

        String domain = IdentityUtil.extractDomainFromName(username);
        RealmConfiguration realmConfiguration = userStoreManager.getSecondaryUserStoreManager(domain)
                .getRealmConfiguration();

        String claimSeparator = realmConfiguration.getUserStoreProperty(
                IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR);
        if (StringUtils.isNotBlank(claimSeparator)) {
            mappedAppClaims.put(IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR, claimSeparator);
        }
    }
    return mappedAppClaims;
}
 
Example 16
Source File: SAMLAssertionClaimsCallback.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
private static Map<String, Object> getClaimsFromUserStore(OAuthAuthzReqMessageContext requestMsgCtx)
        throws IdentityApplicationManagementException, IdentityException, UserStoreException,
        ClaimManagementException {

    AuthenticatedUser user = requestMsgCtx.getAuthorizationReqDTO().getUser();
    String tenantDomain = requestMsgCtx.getAuthorizationReqDTO().getUser().getTenantDomain();

    UserRealm realm;
    List<String> claimURIList = new ArrayList<String>();
    Map<String, Object> mappedAppClaims = new HashMap<String, Object>();

    ApplicationManagementService applicationMgtService = OAuth2ServiceComponentHolder.getApplicationMgtService();
    String spName = applicationMgtService
            .getServiceProviderNameByClientId(requestMsgCtx.getAuthorizationReqDTO().getConsumerKey(),
                    INBOUND_AUTH2_TYPE, tenantDomain);
    ServiceProvider serviceProvider = applicationMgtService.getApplicationExcludingFileBasedSPs(spName,
            tenantDomain);
    if (serviceProvider == null) {
        return mappedAppClaims;
    }

    realm = IdentityTenantUtil.getRealm(tenantDomain, user.toString());
    if (realm == null) {
        log.warn("No valid tenant domain provider. Empty claim returned back for tenant " + tenantDomain
                + " and user " + user);
        return new HashMap<>();
    }

    Map<String, String> spToLocalClaimMappings;
    UserStoreManager userStoreManager = realm.getUserStoreManager();
    ClaimMapping[] requestedLocalClaimMap = serviceProvider.getClaimConfig().getClaimMappings();

    if (requestedLocalClaimMap != null && requestedLocalClaimMap.length > 0) {

        for (ClaimMapping mapping : requestedLocalClaimMap) {
            if (mapping.isRequested()) {
                claimURIList.add(mapping.getLocalClaim().getClaimUri());
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("Requested number of local claims: " + claimURIList.size());
        }

        spToLocalClaimMappings = ClaimManagerHandler.getInstance().getMappingsMapFromOtherDialectToCarbon(
                SP_DIALECT, null, tenantDomain, false);

        Map<String, String> userClaims = null;
        try {
            userClaims = userStoreManager.getUserClaimValues(UserCoreUtil.addDomainToName(user.getUserName(),
                    user.getUserStoreDomain()), claimURIList.toArray(new String[claimURIList.size()]),null);
        } catch (UserStoreException e) {
            if (e.getMessage().contains("UserNotFound")) {
                if (log.isDebugEnabled()) {
                    log.debug("User " + user + " not found in user store");
                }
            } else {
                throw e;
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("Number of user claims retrieved from user store: " + userClaims.size());
        }

        if (MapUtils.isEmpty(userClaims)) {
            return new HashMap<>();
        }

        for (Iterator<Map.Entry<String, String>> iterator = spToLocalClaimMappings.entrySet().iterator(); iterator
                .hasNext(); ) {
            Map.Entry<String, String> entry = iterator.next();
            String value = userClaims.get(entry.getValue());
            if (value != null) {
                mappedAppClaims.put(entry.getKey(), value);
                if (log.isDebugEnabled() &&
                        IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.USER_CLAIMS)) {
                    log.debug("Mapped claim: key -  " + entry.getKey() + " value -" + value);
                }
            }
        }

        RealmConfiguration realmConfiguration = userStoreManager.getSecondaryUserStoreManager(user.getUserStoreDomain())
                .getRealmConfiguration();

        String claimSeparator = realmConfiguration.getUserStoreProperty(
                IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR);
        if (StringUtils.isNotBlank(claimSeparator)) {
            mappedAppClaims.put(IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR, claimSeparator);
        }
    }
    return mappedAppClaims;
}