Search in sources :

Example 6 with ClaimMapping

use of org.wso2.carbon.user.api.ClaimMapping in project carbon-apimgt by wso2.

the class SystemScopesIssuer method getScopes.

/**
 * This method is used to retrieve the authorized scopes with respect to a token.
 *
 * @param tokReqMsgCtx token message context
 * @return authorized scopes list
 */
public List<String> getScopes(OAuthTokenReqMessageContext tokReqMsgCtx) {
    List<String> authorizedScopes = null;
    List<String> requestedScopes = new ArrayList<>(Arrays.asList(tokReqMsgCtx.getScope()));
    String clientId = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId();
    AuthenticatedUser authenticatedUser = tokReqMsgCtx.getAuthorizedUser();
    Map<String, String> appScopes = getAppScopes(clientId, authenticatedUser, requestedScopes);
    if (appScopes != null) {
        // If no scopes can be found in the context of the application
        if (isAppScopesEmpty(appScopes, clientId)) {
            return getAllowedScopes(requestedScopes);
        }
        String grantType = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getGrantType();
        String[] userRoles = null;
        // If GrantType is SAML20_BEARER and CHECK_ROLES_FROM_SAML_ASSERTION is true, or if GrantType is
        // JWT_BEARER and retrieveRolesFromUserStoreForScopeValidation system property is true,
        // use user roles from assertion or jwt otherwise use roles from userstore.
        String isSAML2Enabled = System.getProperty(APIConstants.SystemScopeConstants.CHECK_ROLES_FROM_SAML_ASSERTION);
        String isRetrieveRolesFromUserStoreForScopeValidation = System.getProperty(APIConstants.SystemScopeConstants.RETRIEVE_ROLES_FROM_USERSTORE_FOR_SCOPE_VALIDATION);
        if (GrantType.SAML20_BEARER.toString().equals(grantType) && Boolean.parseBoolean(isSAML2Enabled)) {
            authenticatedUser.setUserStoreDomain("FEDERATED");
            tokReqMsgCtx.setAuthorizedUser(authenticatedUser);
            Assertion assertion = (Assertion) tokReqMsgCtx.getProperty(APIConstants.SystemScopeConstants.SAML2_ASSERTION);
            userRoles = getRolesFromAssertion(assertion);
        } else if (APIConstants.SystemScopeConstants.OAUTH_JWT_BEARER_GRANT_TYPE.equals(grantType) && !(Boolean.parseBoolean(isRetrieveRolesFromUserStoreForScopeValidation))) {
            configureForJWTGrant(tokReqMsgCtx);
            Map<ClaimMapping, String> userAttributes = authenticatedUser.getUserAttributes();
            if (tokReqMsgCtx.getProperty(APIConstants.SystemScopeConstants.ROLE_CLAIM) != null) {
                userRoles = getRolesFromUserAttribute(userAttributes, tokReqMsgCtx.getProperty(APIConstants.SystemScopeConstants.ROLE_CLAIM).toString());
            }
        } else {
            userRoles = getUserRoles(authenticatedUser);
        }
        authorizedScopes = getAuthorizedScopes(userRoles, requestedScopes, appScopes);
    }
    return authorizedScopes;
}
Also used : Assertion(org.opensaml.saml.saml2.core.Assertion) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)

Example 7 with ClaimMapping

use of org.wso2.carbon.user.api.ClaimMapping in project carbon-apimgt by wso2.

the class APIAdminImpl method updateClaims.

private void updateClaims(IdentityProvider idp, Object claims) {
    if (claims != null) {
        ClaimConfig claimConfig = new ClaimConfig();
        List<ClaimMapping> claimMappings = new ArrayList<>();
        List<org.wso2.carbon.identity.application.common.model.Claim> idpClaims = new ArrayList<>();
        JsonArray claimArray = (JsonArray) claims;
        claimConfig.setLocalClaimDialect(false);
        for (JsonElement claimMappingEntry : claimArray) {
            if (claimMappingEntry instanceof JsonObject) {
                JsonElement idpClaimUri = ((JsonObject) claimMappingEntry).get("remoteClaim");
                JsonElement localClaimUri = ((JsonObject) claimMappingEntry).get("localClaim");
                ClaimMapping internalMapping = new ClaimMapping();
                org.wso2.carbon.identity.application.common.model.Claim remoteClaim = new org.wso2.carbon.identity.application.common.model.Claim();
                remoteClaim.setClaimUri(idpClaimUri.getAsString());
                org.wso2.carbon.identity.application.common.model.Claim localClaim = new org.wso2.carbon.identity.application.common.model.Claim();
                localClaim.setClaimUri(localClaimUri.getAsString());
                internalMapping.setRemoteClaim(remoteClaim);
                internalMapping.setLocalClaim(localClaim);
                claimMappings.add(internalMapping);
                idpClaims.add(remoteClaim);
            }
        }
        claimConfig.setClaimMappings(claimMappings.toArray(new ClaimMapping[0]));
        claimConfig.setIdpClaims(idpClaims.toArray(new org.wso2.carbon.identity.application.common.model.Claim[0]));
        idp.setClaimConfig(claimConfig);
    }
}
Also used : ArrayList(java.util.ArrayList) JsonObject(com.google.gson.JsonObject) JsonArray(com.google.gson.JsonArray) ClaimMapping(org.wso2.carbon.identity.application.common.model.ClaimMapping) ClaimConfig(org.wso2.carbon.identity.application.common.model.ClaimConfig) JsonElement(com.google.gson.JsonElement)

Example 8 with ClaimMapping

use of org.wso2.carbon.user.api.ClaimMapping in project carbon-apimgt by wso2.

the class TokenGenTest method testJWTGeneration.

// TODO: Have to convert to work with new JWT generation and signing
@Test
@Ignore
public void testJWTGeneration() throws Exception {
    JWTGenerator jwtGen = new JWTGenerator() {

        @Override
        public Map<String, String> convertClaimMap(Map<ClaimMapping, String> userAttributes, String username) {
            return new HashMap<>();
        }
    };
    APIKeyValidationInfoDTO dto = new APIKeyValidationInfoDTO();
    dto.setSubscriber("sastry");
    dto.setApplicationName("hubapp");
    dto.setApplicationId("1");
    dto.setApplicationTier("UNLIMITED");
    dto.setEndUserName("denis");
    dto.setSubscriberTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    dto.setUserType(APIConstants.ACCESS_TOKEN_USER_TYPE_APPLICATION);
    TokenValidationContext validationContext = new TokenValidationContext();
    validationContext.setValidationInfoDTO(dto);
    validationContext.setContext("cricScore");
    validationContext.setVersion("1.9.0");
    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);
// we can not do assert eaquals because body includes expiration time.
/*String expectedHeader = "{\"typ\":\"JWT\"}";
        String expectedBody = "{\"iss\":\"wso2.org/products/am\", \"exp\":1349270811075, " +
                              "\"http://wso2.org/claims/subscriber\":\"sastry\", " +
                              "\"http://wso2.org/claims/applicationname\":\"hubapp\", " +
                              "\"http://wso2.org/claims/apicontext\":\"cricScore\", " +
                              "\"http://wso2.org/claims/version\":\"1.9.0\", " +
                              "\"http://wso2.org/claims/tier\":\"Bronze\", " +
                              "\"http://wso2.org/claims/enduser\":\"denis\"}";

        Assert.assertEquals(expectedHeader, decodedHeader);
        Assert.assertEquals(expectedBody, decodedBody);*/
// String decodedToken = new String(Base64Utils.decode(token));
// log.info(decodedToken);
// assertNotNull(decodedToken);
}
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 9 with ClaimMapping

use of org.wso2.carbon.user.api.ClaimMapping in project carbon-apimgt by wso2.

the class APIAdminImpl method mergeIdpWithKeyManagerConfiguration.

private void mergeIdpWithKeyManagerConfiguration(IdentityProvider identityProvider, KeyManagerConfigurationDTO keyManagerDTO) {
    keyManagerDTO.setDisplayName(identityProvider.getDisplayName());
    keyManagerDTO.setDescription(identityProvider.getIdentityProviderDescription());
    IdentityProviderProperty[] identityProviderProperties = identityProvider.getIdpProperties();
    if (identityProviderProperties.length > 0) {
        for (IdentityProviderProperty identityProviderProperty : identityProviderProperties) {
            if (StringUtils.equals(identityProviderProperty.getName(), APIConstants.JWKS_URI)) {
                keyManagerDTO.addProperty(APIConstants.KeyManager.CERTIFICATE_TYPE, APIConstants.KeyManager.CERTIFICATE_TYPE_JWKS_ENDPOINT);
                keyManagerDTO.addProperty(APIConstants.KeyManager.CERTIFICATE_VALUE, identityProviderProperty.getValue());
            }
            if (StringUtils.equals(identityProviderProperty.getName(), IdentityApplicationConstants.IDP_ISSUER_NAME)) {
                keyManagerDTO.addProperty(APIConstants.KeyManager.ISSUER, identityProviderProperty.getValue());
            }
        }
    } else if (StringUtils.isNotBlank(identityProvider.getCertificate())) {
        keyManagerDTO.addProperty(APIConstants.KeyManager.CERTIFICATE_TYPE, APIConstants.KeyManager.CERTIFICATE_TYPE_PEM_FILE);
        keyManagerDTO.addProperty(APIConstants.KeyManager.CERTIFICATE_VALUE, identityProvider.getCertificate());
    }
    keyManagerDTO.setEnabled(identityProvider.isEnable());
    keyManagerDTO.setAlias(identityProvider.getAlias());
    ClaimConfig claimConfig = identityProvider.getClaimConfig();
    JsonArray claimArray = new JsonArray();
    for (ClaimMapping claimMapping : claimConfig.getClaimMappings()) {
        JsonObject claimMappingEntryDTO = new JsonObject();
        claimMappingEntryDTO.addProperty("localClaim", claimMapping.getLocalClaim().getClaimUri());
        claimMappingEntryDTO.addProperty("remoteClaim", claimMapping.getRemoteClaim().getClaimUri());
        claimArray.add(claimMappingEntryDTO);
    }
    keyManagerDTO.addProperty(APIConstants.KeyManager.CLAIM_MAPPING, claimArray);
}
Also used : JsonArray(com.google.gson.JsonArray) ClaimMapping(org.wso2.carbon.identity.application.common.model.ClaimMapping) IdentityProviderProperty(org.wso2.carbon.identity.application.common.model.IdentityProviderProperty) ClaimConfig(org.wso2.carbon.identity.application.common.model.ClaimConfig) JsonObject(com.google.gson.JsonObject)

Example 10 with ClaimMapping

use of org.wso2.carbon.user.api.ClaimMapping in project carbon-apimgt by wso2.

the class APIUtil method getClaims.

/**
 * Returns the user claims for the given user.
 *
 * @param endUserName name of the user whose claims needs to be returned
 * @param tenantId    tenant id of the user
 * @param dialectURI  claim dialect URI
 * @return claims map
 * @throws APIManagementException
 */
public static SortedMap<String, String> getClaims(String endUserName, int tenantId, String dialectURI) throws APIManagementException {
    SortedMap<String, String> claimValues;
    try {
        ClaimManager claimManager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId).getClaimManager();
        ClaimMapping[] claims = claimManager.getAllClaimMappings(dialectURI);
        String[] claimURIs = claimMappingtoClaimURIString(claims);
        UserStoreManager userStoreManager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId).getUserStoreManager();
        String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(endUserName);
        claimValues = new TreeMap(userStoreManager.getUserClaimValues(tenantAwareUserName, claimURIs, null));
        return claimValues;
    } catch (UserStoreException e) {
        throw new APIManagementException("Error while retrieving user claim values from user store", e);
    }
}
Also used : ClaimManager(org.wso2.carbon.user.api.ClaimManager) ClaimMapping(org.wso2.carbon.user.api.ClaimMapping) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) UserStoreManager(org.wso2.carbon.user.api.UserStoreManager) AbstractUserStoreManager(org.wso2.carbon.user.core.common.AbstractUserStoreManager) TreeMap(java.util.TreeMap)

Aggregations

HashMap (java.util.HashMap)4 Map (java.util.Map)4 JsonObject (com.google.gson.JsonObject)3 ClaimMapping (org.wso2.carbon.identity.application.common.model.ClaimMapping)3 Gson (com.google.gson.Gson)2 JsonArray (com.google.gson.JsonArray)2 ArrayList (java.util.ArrayList)2 Ignore (org.junit.Ignore)2 Test (org.junit.Test)2 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)2 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)2 ClaimMappingDto (org.wso2.carbon.apimgt.common.gateway.dto.ClaimMappingDto)2 APIKeyValidationInfoDTO (org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)2 TokenValidationContext (org.wso2.carbon.apimgt.keymgt.service.TokenValidationContext)2 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)2 ClaimConfig (org.wso2.carbon.identity.application.common.model.ClaimConfig)2 JsonElement (com.google.gson.JsonElement)1 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)1 SignedJWT (com.nimbusds.jwt.SignedJWT)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1