Search in sources :

Example 1 with ClaimMapping

use of org.wso2.carbon.identity.application.common.model.xsd.ClaimMapping in project carbon-apimgt by wso2.

the class APIManagerConfiguration method setJWTTokenIssuers.

private void setJWTTokenIssuers(OMElement omElement) {
    Iterator tokenIssuersElement = omElement.getChildrenWithLocalName(APIConstants.TokenIssuer.TOKEN_ISSUER);
    while (tokenIssuersElement.hasNext()) {
        OMElement issuerElement = (OMElement) tokenIssuersElement.next();
        String issuer = issuerElement.getAttributeValue(new QName("issuer"));
        OMElement consumerKeyClaimElement = issuerElement.getFirstChildWithName(new QName(APIConstants.TokenIssuer.CONSUMER_KEY_CLAIM));
        OMElement scopesElement = issuerElement.getFirstChildWithName(new QName(APIConstants.TokenIssuer.SCOPES_CLAIM));
        TokenIssuerDto tokenIssuerDto = new TokenIssuerDto(issuer);
        if (consumerKeyClaimElement != null) {
            tokenIssuerDto.setConsumerKeyClaim(consumerKeyClaimElement.getText());
        }
        if (scopesElement != null) {
            tokenIssuerDto.setScopesClaim(scopesElement.getText());
        }
        OMElement jwksConfiguration = issuerElement.getFirstChildWithName(new QName(APIConstants.TokenIssuer.JWKS_CONFIGURATION));
        if (jwksConfiguration != null) {
            JWKSConfigurationDTO jwksConfigurationDTO = tokenIssuerDto.getJwksConfigurationDTO();
            jwksConfigurationDTO.setEnabled(true);
            jwksConfigurationDTO.setUrl(jwksConfiguration.getFirstChildWithName(new QName(APIConstants.TokenIssuer.JWKSConfiguration.URL)).getText());
        }
        OMElement claimMappingsElement = issuerElement.getFirstChildWithName(new QName(APIConstants.TokenIssuer.CLAIM_MAPPINGS));
        if (claimMappingsElement != null) {
            OMAttribute disableDefaultClaimMappingAttribute = claimMappingsElement.getAttribute(new QName("disable-default-claim-mapping"));
            if (disableDefaultClaimMappingAttribute != null) {
                String disableDefaultClaimMapping = disableDefaultClaimMappingAttribute.getAttributeValue();
                tokenIssuerDto.setDisableDefaultClaimMapping(Boolean.parseBoolean(disableDefaultClaimMapping));
            }
            Iterator claimMapping = claimMappingsElement.getChildrenWithName(new QName(APIConstants.TokenIssuer.CLAIM_MAPPING));
            while (claimMapping.hasNext()) {
                OMElement claim = (OMElement) claimMapping.next();
                OMElement remoteClaimElement = claim.getFirstChildWithName(new QName(APIConstants.TokenIssuer.ClaimMapping.REMOTE_CLAIM));
                OMElement localClaimElement = claim.getFirstChildWithName(new QName(APIConstants.TokenIssuer.ClaimMapping.LOCAL_CLAIM));
                if (remoteClaimElement != null && localClaimElement != null) {
                    String remoteClaim = remoteClaimElement.getText();
                    String localClaim = localClaimElement.getText();
                    if (StringUtils.isNotEmpty(remoteClaim) && StringUtils.isNotEmpty(localClaim)) {
                        tokenIssuerDto.getClaimConfigurations().put(remoteClaim, new ClaimMappingDto(remoteClaim, localClaim));
                    }
                }
            }
        }
        jwtConfigurationDto.getTokenIssuerDtoMap().put(tokenIssuerDto.getIssuer(), tokenIssuerDto);
    }
}
Also used : ClaimMappingDto(org.wso2.carbon.apimgt.common.gateway.dto.ClaimMappingDto) JWKSConfigurationDTO(org.wso2.carbon.apimgt.common.gateway.dto.JWKSConfigurationDTO) QName(javax.xml.namespace.QName) Iterator(java.util.Iterator) OMElement(org.apache.axiom.om.OMElement) TokenIssuerDto(org.wso2.carbon.apimgt.common.gateway.dto.TokenIssuerDto) OMAttribute(org.apache.axiom.om.OMAttribute)

Example 2 with ClaimMapping

use of org.wso2.carbon.identity.application.common.model.xsd.ClaimMapping in project carbon-apimgt by wso2.

the class TokenGenTest method testAbstractJWTGenerator.

@Test
@Ignore
public void testAbstractJWTGenerator() throws Exception {
    JWTGenerator jwtGen = new JWTGenerator() {

        @Override
        protected Map<String, String> convertClaimMap(Map<ClaimMapping, String> userAttributes, String username) {
            return new HashMap<>();
        }
    };
    APIKeyValidationInfoDTO dto = new APIKeyValidationInfoDTO();
    TokenValidationContext validationContext = new TokenValidationContext();
    validationContext.setValidationInfoDTO(dto);
    validationContext.setContext("testAPI");
    validationContext.setVersion("1.5.0");
    validationContext.setAccessToken("DUMMY_TOKEN_STRING");
    dto.setSubscriber("sanjeewa");
    dto.setApplicationName("sanjeewa-app");
    dto.setApplicationId("1");
    dto.setApplicationTier("UNLIMITED");
    dto.setEndUserName("malalgoda");
    dto.setSubscriberTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    dto.setUserType(APIConstants.ACCESS_TOKEN_USER_TYPE_APPLICATION);
    // Here we will call generate token method with 4 argument.
    String token = jwtGen.generateToken(validationContext);
    System.out.println("Generated Token: " + token);
    String header = token.split("\\.")[0];
    String decodedHeader = new String(Base64Utils.decode(header));
    System.out.println("Header: " + decodedHeader);
    String body = token.split("\\.")[1];
    String decodedBody = new String(Base64Utils.decode(body));
    System.out.println("Body: " + decodedBody);
    // With end user name not included
    token = jwtGen.generateToken(validationContext);
    System.out.println("Generated Token: " + token);
    header = token.split("\\.")[0];
    decodedHeader = new String(Base64Utils.decode(header));
    System.out.println("Header: " + decodedHeader);
    body = token.split("\\.")[1];
    decodedBody = new String(Base64Utils.decode(body));
    System.out.println("Body: " + decodedBody);
    dto.setUserType(APIConstants.SUBSCRIPTION_USER_TYPE);
    token = jwtGen.generateToken(validationContext);
    System.out.println("Generated Token: " + token);
    header = token.split("\\.")[0];
    decodedHeader = new String(Base64Utils.decode(header));
    System.out.println("Header: " + decodedHeader);
    body = token.split("\\.")[1];
    decodedBody = new String(Base64Utils.decode(body));
    System.out.println("Body: " + decodedBody);
    token = jwtGen.generateToken(validationContext);
    System.out.println("Generated Token: " + token);
    header = token.split("\\.")[0];
    decodedHeader = new String(Base64Utils.decode(header));
    System.out.println("Header: " + decodedHeader);
    body = token.split("\\.")[1];
    decodedBody = new String(Base64Utils.decode(body));
    System.out.println("Body: " + decodedBody);
}
Also used : TokenValidationContext(org.wso2.carbon.apimgt.keymgt.service.TokenValidationContext) HashMap(java.util.HashMap) HashMap(java.util.HashMap) Map(java.util.Map) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO) Ignore(org.junit.Ignore) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 3 with ClaimMapping

use of org.wso2.carbon.identity.application.common.model.xsd.ClaimMapping in project carbon-apimgt by wso2.

the class JWTGenerator method convertClaimMap.

protected Map<String, String> convertClaimMap(Map<ClaimMapping, String> userAttributes, String username) throws APIManagementException {
    Map<String, String> userClaims = new HashMap<>();
    Map<String, String> userClaimsCopy = new HashMap<>();
    for (Map.Entry<ClaimMapping, String> entry : userAttributes.entrySet()) {
        Claim claimObject = entry.getKey().getLocalClaim();
        if (claimObject == null) {
            claimObject = entry.getKey().getRemoteClaim();
        }
        userClaims.put(claimObject.getClaimUri(), entry.getValue());
        userClaimsCopy.put(claimObject.getClaimUri(), entry.getValue());
    }
    String convertClaimsFromOIDCtoConsumerDialect = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration().getFirstProperty(APIConstants.CONVERT_CLAIMS_TO_CONSUMER_DIALECT);
    if (convertClaimsFromOIDCtoConsumerDialect != null && !Boolean.parseBoolean(convertClaimsFromOIDCtoConsumerDialect)) {
        return userClaims;
    }
    int tenantId = APIUtil.getTenantId(username);
    String tenantDomain = APIUtil.getTenantDomainFromTenantId(tenantId);
    String dialect;
    ClaimsRetriever claimsRetriever = getClaimsRetriever();
    if (claimsRetriever != null) {
        dialect = claimsRetriever.getDialectURI(username);
    } else {
        dialect = getDialectURI();
    }
    // (key) configuredDialectClaimURI -> (value)
    Map<String, String> configuredDialectToCarbonClaimMapping = null;
    // carbonClaimURI
    // (key) carbonClaimURI ->  value (oidcClaimURI)
    Map<String, String> carbonToOIDCclaimMapping = null;
    Set<String> claimUris = new HashSet<String>(userClaims.keySet());
    try {
        carbonToOIDCclaimMapping = new ClaimMetadataHandler().getMappingsMapFromOtherDialectToCarbon(OIDC_DIALECT_URI, claimUris, tenantDomain, true);
        configuredDialectToCarbonClaimMapping = ClaimManagerHandler.getInstance().getMappingsMapFromCarbonDialectToOther(dialect, carbonToOIDCclaimMapping.keySet(), tenantDomain);
    } catch (ClaimMetadataException e) {
        String error = "Error while mapping claims from Carbon dialect to " + OIDC_DIALECT_URI + " dialect";
        throw new APIManagementException(error, e);
    } catch (ClaimManagementException e) {
        String error = "Error while mapping claims from configured dialect to Carbon dialect";
        throw new APIManagementException(error, e);
    }
    for (Map.Entry<String, String> oidcClaimValEntry : userClaims.entrySet()) {
        for (Map.Entry<String, String> carbonToOIDCEntry : carbonToOIDCclaimMapping.entrySet()) {
            if (oidcClaimValEntry.getKey().equals(carbonToOIDCEntry.getValue())) {
                for (Map.Entry<String, String> configuredToCarbonEntry : configuredDialectToCarbonClaimMapping.entrySet()) {
                    if (configuredToCarbonEntry.getValue().equals(carbonToOIDCEntry.getKey())) {
                        userClaimsCopy.remove(oidcClaimValEntry.getKey());
                        userClaimsCopy.put(configuredToCarbonEntry.getKey(), oidcClaimValEntry.getValue());
                    }
                }
            }
        }
    }
    return userClaimsCopy;
}
Also used : ClaimMetadataException(org.wso2.carbon.identity.claim.metadata.mgt.exception.ClaimMetadataException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ClaimMetadataHandler(org.wso2.carbon.identity.claim.metadata.mgt.ClaimMetadataHandler) ClaimsRetriever(org.wso2.carbon.apimgt.impl.token.ClaimsRetriever) ClaimMapping(org.wso2.carbon.identity.application.common.model.ClaimMapping) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ClaimManagementException(org.wso2.carbon.claim.mgt.ClaimManagementException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) Claim(org.wso2.carbon.identity.application.common.model.Claim) HashSet(java.util.HashSet)

Example 4 with ClaimMapping

use of org.wso2.carbon.identity.application.common.model.xsd.ClaimMapping in project carbon-apimgt by wso2.

the class APIUtil method getDefaultClaimMappings.

public static List<ClaimMappingDto> getDefaultClaimMappings() {
    List<ClaimMappingDto> claimMappingDtoList = new ArrayList<>();
    try (InputStream resourceAsStream = APIUtil.class.getClassLoader().getResourceAsStream("claimMappings/default-claim-mapping.json")) {
        String content = IOUtils.toString(resourceAsStream);
        Map<String, String> claimMapping = new Gson().fromJson(content, Map.class);
        claimMapping.forEach((remoteClaim, localClaim) -> {
            claimMappingDtoList.add(new ClaimMappingDto(remoteClaim, localClaim));
        });
    } catch (IOException e) {
        log.error("Error while reading default-claim-mapping.json", e);
    }
    return claimMappingDtoList;
}
Also used : ClaimMappingDto(org.wso2.carbon.apimgt.common.gateway.dto.ClaimMappingDto) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) IOException(java.io.IOException)

Example 5 with ClaimMapping

use of org.wso2.carbon.identity.application.common.model.xsd.ClaimMapping in project carbon-apimgt by wso2.

the class SystemScopesIssuer method configureForJWTGrant.

protected void configureForJWTGrant(OAuthTokenReqMessageContext tokReqMsgCtx) {
    SignedJWT signedJWT = null;
    JWTClaimsSet claimsSet = null;
    String[] roles = null;
    try {
        signedJWT = getSignedJWT(tokReqMsgCtx);
    } catch (IdentityOAuth2Exception e) {
        log.error("Couldn't retrieve signed JWT", e);
    }
    if (signedJWT != null) {
        claimsSet = getClaimSet(signedJWT);
    }
    String jwtIssuer = claimsSet != null ? claimsSet.getIssuer() : null;
    String tenantDomain = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getTenantDomain();
    try {
        identityProvider = IdentityProviderManager.getInstance().getIdPByName(jwtIssuer, tenantDomain);
        if (identityProvider != null) {
            if (StringUtils.equalsIgnoreCase(identityProvider.getIdentityProviderName(), "default")) {
                identityProvider = this.getResidentIDPForIssuer(tenantDomain, jwtIssuer);
                if (identityProvider == null) {
                    log.error("No Registered IDP found for the JWT with issuer name : " + jwtIssuer);
                }
            }
        } else {
            log.error("No Registered IDP found for the JWT with issuer name : " + jwtIssuer);
        }
    } catch (IdentityProviderManagementException | IdentityOAuth2Exception e) {
        log.error("Couldn't initiate identity provider instance", e);
    }
    try {
        roles = claimsSet != null ? claimsSet.getStringArrayClaim(identityProvider.getClaimConfig().getRoleClaimURI()) : null;
    } catch (ParseException e) {
        log.error("Couldn't retrieve roles:", e);
    }
    List<String> updatedRoles = new ArrayList<>();
    if (roles != null) {
        for (String role : roles) {
            String updatedRoleClaimValue = getUpdatedRoleClaimValue(identityProvider, role);
            if (updatedRoleClaimValue != null) {
                updatedRoles.add(updatedRoleClaimValue);
            } else {
                updatedRoles.add(role);
            }
        }
    }
    AuthenticatedUser user = tokReqMsgCtx.getAuthorizedUser();
    Map<ClaimMapping, String> userAttributes = user.getUserAttributes();
    String roleClaim = identityProvider.getClaimConfig().getRoleClaimURI();
    if (roleClaim != null) {
        userAttributes.put(ClaimMapping.build(roleClaim, roleClaim, null, false), updatedRoles.toString().replace(" ", ""));
        tokReqMsgCtx.addProperty(APIConstants.SystemScopeConstants.ROLE_CLAIM, roleClaim);
    }
    user.setUserAttributes(userAttributes);
    tokReqMsgCtx.setAuthorizedUser(user);
}
Also used : SignedJWT(com.nimbusds.jwt.SignedJWT) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) ParseException(java.text.ParseException) IdentityProviderManagementException(org.wso2.carbon.idp.mgt.IdentityProviderManagementException)

Aggregations

ClaimMapping (org.wso2.carbon.identity.application.common.model.ClaimMapping)108 HashMap (java.util.HashMap)60 ArrayList (java.util.ArrayList)52 ClaimConfig (org.wso2.carbon.identity.application.common.model.ClaimConfig)27 Map (java.util.Map)26 ServiceProvider (org.wso2.carbon.identity.application.common.model.ServiceProvider)24 ClaimMapping (org.wso2.carbon.identity.application.common.model.xsd.ClaimMapping)24 ClaimMapping (org.wso2.carbon.user.api.ClaimMapping)24 Claim (org.wso2.carbon.identity.application.common.model.Claim)23 Test (org.testng.annotations.Test)22 Claim (org.wso2.carbon.identity.application.common.model.xsd.Claim)21 LocalClaim (org.wso2.carbon.identity.claim.metadata.mgt.model.LocalClaim)21 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)20 IdentityApplicationManagementException (org.wso2.carbon.identity.application.common.IdentityApplicationManagementException)20 List (java.util.List)17 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)17 UserStoreException (org.wso2.carbon.user.api.UserStoreException)17 Matchers.anyString (org.mockito.Matchers.anyString)16 IdentityProvider (org.wso2.carbon.identity.application.common.model.IdentityProvider)13 ClaimMetadataException (org.wso2.carbon.identity.claim.metadata.mgt.exception.ClaimMetadataException)13