Search in sources :

Example 36 with OAuth2AccessTokenRespDTO

use of org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2TokenEndpoint method issueAccessToken.

protected Response issueAccessToken(HttpServletRequest request, Map<String, List<String>> paramMap) throws OAuthSystemException, InvalidRequestParentException {
    try {
        startSuperTenantFlow();
        validateRepeatedParams(request, paramMap);
        HttpServletRequestWrapper httpRequest = new OAuthRequestWrapper(request, paramMap);
        CarbonOAuthTokenRequest oauthRequest = buildCarbonOAuthTokenRequest(httpRequest);
        validateOAuthApplication(oauthRequest.getoAuthClientAuthnContext());
        OAuth2AccessTokenRespDTO oauth2AccessTokenResp = issueAccessToken(oauthRequest, httpRequest);
        if (oauth2AccessTokenResp.getErrorMsg() != null) {
            return handleErrorResponse(oauth2AccessTokenResp);
        } else {
            return buildTokenResponse(oauth2AccessTokenResp);
        }
    } catch (TokenEndpointBadRequestException | OAuthSystemException | InvalidApplicationClientException e) {
        triggerOnTokenExceptionListeners(e, request, paramMap);
        throw e;
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
Also used : OAuthRequestWrapper(org.wso2.carbon.identity.oauth.endpoint.OAuthRequestWrapper) OAuth2AccessTokenRespDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO) TokenEndpointBadRequestException(org.wso2.carbon.identity.oauth.endpoint.exception.TokenEndpointBadRequestException) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) InvalidApplicationClientException(org.wso2.carbon.identity.oauth.endpoint.exception.InvalidApplicationClientException) CarbonOAuthTokenRequest(org.wso2.carbon.identity.oauth2.model.CarbonOAuthTokenRequest)

Example 37 with OAuth2AccessTokenRespDTO

use of org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2TokenEndpoint method buildTokenResponse.

private Response buildTokenResponse(OAuth2AccessTokenRespDTO oauth2AccessTokenResp) throws OAuthSystemException {
    if (StringUtils.isBlank(oauth2AccessTokenResp.getTokenType())) {
        oauth2AccessTokenResp.setTokenType(BEARER);
    }
    OAuthTokenResponseBuilder oAuthRespBuilder = OAuthASResponse.tokenResponse(HttpServletResponse.SC_OK).setAccessToken(oauth2AccessTokenResp.getAccessToken()).setRefreshToken(oauth2AccessTokenResp.getRefreshToken()).setExpiresIn(Long.toString(oauth2AccessTokenResp.getExpiresIn())).setTokenType(oauth2AccessTokenResp.getTokenType());
    oAuthRespBuilder.setScope(oauth2AccessTokenResp.getAuthorizedScopes());
    if (oauth2AccessTokenResp.getIDToken() != null) {
        oAuthRespBuilder.setParam(OAuthConstants.ID_TOKEN, oauth2AccessTokenResp.getIDToken());
    }
    // Set custom parameters in token response if supported
    if (MapUtils.isNotEmpty(oauth2AccessTokenResp.getParameters())) {
        oauth2AccessTokenResp.getParameters().forEach(oAuthRespBuilder::setParam);
    }
    OAuthResponse response = oAuthRespBuilder.buildJSONMessage();
    ResponseHeader[] headers = oauth2AccessTokenResp.getResponseHeaders();
    ResponseBuilder respBuilder = Response.status(response.getResponseStatus()).header(OAuthConstants.HTTP_RESP_HEADER_CACHE_CONTROL, OAuthConstants.HTTP_RESP_HEADER_VAL_CACHE_CONTROL_NO_STORE).header(OAuthConstants.HTTP_RESP_HEADER_PRAGMA, OAuthConstants.HTTP_RESP_HEADER_VAL_PRAGMA_NO_CACHE);
    if (headers != null) {
        for (ResponseHeader header : headers) {
            if (header != null) {
                respBuilder.header(header.getKey(), header.getValue());
            }
        }
    }
    return respBuilder.entity(response.getBody()).build();
}
Also used : ResponseHeader(org.wso2.carbon.identity.oauth2.ResponseHeader) OAuthTokenResponseBuilder(org.apache.oltu.oauth2.as.response.OAuthASResponse.OAuthTokenResponseBuilder) OAuthTokenResponseBuilder(org.apache.oltu.oauth2.as.response.OAuthASResponse.OAuthTokenResponseBuilder) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse)

Example 38 with OAuth2AccessTokenRespDTO

use of org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO in project identity-inbound-auth-oauth by wso2-extensions.

the class DefaultIDTokenBuilderTest method setUp.

@BeforeClass
public void setUp() throws Exception {
    user = getDefaultAuthenticatedLocalUser();
    messageContext = getTokenReqMessageContextForUser(user, CLIENT_ID);
    messageContext.addProperty(AUTHORIZATION_CODE, AUTHORIZATION_CODE_VALUE);
    tokenRespDTO = new OAuth2AccessTokenRespDTO();
    tokenRespDTO.setAccessToken(ACCESS_TOKEN);
    IdentityProvider idp = new IdentityProvider();
    idp.setIdentityProviderName("LOCAL");
    idp.setEnable(true);
    Map<String, Object> configuration = new HashMap<>();
    configuration.put("SSOService.EntityId", "LOCAL");
    configuration.put("SSOService.SAMLECPEndpoint", "https://localhost:9443/samlecp");
    configuration.put("SSOService.ArtifactResolutionEndpoint", "https://localhost:9443/samlartresolve");
    configuration.put("OAuth.OpenIDConnect.IDTokenIssuerID", "https://localhost:9443/oauth2/token");
    WhiteboxImpl.setInternalState(IdentityUtil.class, "configuration", configuration);
    IdentityProviderManager.getInstance().addResidentIdP(idp, SUPER_TENANT_DOMAIN_NAME);
    defaultIDTokenBuilder = new DefaultIDTokenBuilder();
    Map<ClaimMapping, String> userAttributes = new HashMap<>();
    userAttributes.put(SAML2BearerGrantHandlerTest.buildClaimMapping("username"), "username");
    userAttributes.put(SAML2BearerGrantHandlerTest.buildClaimMapping("email"), "email");
    userAttributes.put(SAML2BearerGrantHandlerTest.buildClaimMapping(PHONE_NUMBER_VERIFIED), "phone");
    LinkedHashSet acrValuesHashSet = new LinkedHashSet<>();
    acrValuesHashSet.add(new Object());
    AuthorizationGrantCacheEntry authorizationGrantCacheEntry = new AuthorizationGrantCacheEntry(userAttributes);
    authorizationGrantCacheEntry.setSubjectClaim(messageContext.getAuthorizedUser().getUserName());
    authorizationGrantCacheEntry.setNonceValue("nonce");
    authorizationGrantCacheEntry.addAmr("amr");
    authorizationGrantCacheEntry.setSessionContextIdentifier("idp");
    authorizationGrantCacheEntry.setAuthTime(1000);
    authorizationGrantCacheEntry.setSelectedAcrValue("acr");
    authorizationGrantCacheEntry.setSubjectClaim("user@carbon.super");
    authorizationGrantCacheEntry.setEssentialClaims(getEssentialClaims());
    AuthorizationGrantCacheKey authorizationGrantCacheKey = new AuthorizationGrantCacheKey(AUTHORIZATION_CODE_VALUE);
    AuthorizationGrantCacheKey authorizationGrantCacheKeyForAccessToken = new AuthorizationGrantCacheKey("2sa9a678f890877856y66e75f605d456");
    AuthorizationGrantCache.getInstance().addToCacheByToken(authorizationGrantCacheKey, authorizationGrantCacheEntry);
    AuthorizationGrantCache.getInstance().addToCacheByToken(authorizationGrantCacheKeyForAccessToken, authorizationGrantCacheEntry);
    ServiceProviderProperty serviceProviderProperty = new ServiceProviderProperty();
    ServiceProviderProperty[] serviceProviders = new ServiceProviderProperty[] { serviceProviderProperty };
    ServiceProvider serviceProvider = new ServiceProvider();
    serviceProvider.setSpProperties(serviceProviders);
    serviceProvider.setCertificateContent("MIIDWTCCAkGgAwIBAgIEcZgeVDANBgkqhkiG9w0BAQsFADBcMQswCQYDVQQGEwJG\n" + "UjEMMAoGA1UECBMDTVBMMQwwCgYDVQQHEwNNUEwxDTALBgNVBAoTBHRlc3QxDTAL\n" + "BgNVBAsTBHRlc3QxEzARBgNVBAMMCioudGVzdC5jb20wIBcNMjEwNTEwMTcwODU4\n" + "WhgPMjA1MTA1MDMxNzA4NThaMFwxCzAJBgNVBAYTAkZSMQwwCgYDVQQIEwNNUEwx\n" + "DDAKBgNVBAcTA01QTDENMAsGA1UEChMEdGVzdDENMAsGA1UECxMEdGVzdDETMBEG\n" + "A1UEAwwKKi50ZXN0LmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB\n" + "AIkuoEuR/or5oL4h6TZ7r90Qyb1xAK6qrAHGCGWz5k1dnmCdvM39zBZF5EDGVKKe\n" + "p+BQWNgG+FST19Z2l71YJllKxVsI0syw3r9PXcAfVLahs3fn8HEa5uJqIdHRsVzz\n" + "uO+rEWYn7kx4jmwwqtb8HBnhlVgn32OWQ6X4mLll/1n87cWGMsNouVP5TCySFNyD\n" + "BFPzC3+gYiVVy7Aj1NBw6Ft4i4r0UIOZ8BPGfHrd7zB4Zmnc9KwyRNj+S3bvJECm\n" + "D1/9hMiHcIj46qnvLJw69f/HmL3LTmp1oQJUnFlA0hykrUcwjVjUEptcBMu627j4\n" + "kfY2xsI613k5NLi6eHlwx7cCAwEAAaMhMB8wHQYDVR0OBBYEFIg+fWViskGrce5K\n" + "48Oy9x1Mh0GTMA0GCSqGSIb3DQEBCwUAA4IBAQB76yS+Wkt2RBh4XEihiMsrgn9L\n" + "2RkxAvDldfVEZTtQHm0uOkjT53AG8RSK5tedWdETJnEa0cq9SGLBjuTB5ojjP18g\n" + "R3fT2HXiP2QDfqnEhj7SYOEPp+QjcgW7rPBpMVOe9qKU6BWw0/ufEFq/SgSb9/xV\n" + "dZa4puEYDVEJ4pu6uJuh/oXgvwcIcL6xURDav1gqTDuMrLnJrKui+FsabnWeC+XB\n" + "1mRWtpZPay9xB5kVWAEVdMtGePP0/wz2zxQU9uCmjwvIsIfx307CpBI54sjomXPU\n" + "DldsCG6l8QRJ3NvijWa/0olA/7BpaOtbNS6S5dBSfPScpUvVQiBYFFvMXbmd\n");
    ApplicationManagementService applicationMgtService = mock(ApplicationManagementService.class);
    OAuth2ServiceComponentHolder.setApplicationMgtService(applicationMgtService);
    Map<String, ServiceProvider> fileBasedSPs = CommonTestUtils.getFileBasedSPs();
    setFinalStatic(ApplicationManagementServiceComponent.class.getDeclaredField("fileBasedSPs"), fileBasedSPs);
    when(applicationMgtService.getApplicationExcludingFileBasedSPs(TEST_APPLICATION_NAME, SUPER_TENANT_DOMAIN_NAME)).thenReturn(fileBasedSPs.get(TEST_APPLICATION_NAME));
    when(applicationMgtService.getServiceProviderNameByClientId(anyString(), anyString(), anyString())).thenReturn(TEST_APPLICATION_NAME);
    when(applicationMgtService.getServiceProviderByClientId(anyString(), anyString(), anyString())).thenReturn(serviceProvider);
    AuthenticationMethodNameTranslator authenticationMethodNameTranslator = new AuthenticationMethodNameTranslatorImpl();
    OAuth2ServiceComponentHolder.setAuthenticationMethodNameTranslator(authenticationMethodNameTranslator);
    RealmService realmService = IdentityTenantUtil.getRealmService();
    HashMap<String, String> claims = new HashMap<>();
    claims.put("http://wso2.org/claims/username", TestConstants.USER_NAME);
    realmService.getTenantUserRealm(SUPER_TENANT_ID).getUserStoreManager().addUser(TestConstants.USER_NAME, TestConstants.PASSWORD, new String[0], claims, TestConstants.DEFAULT_PROFILE);
    Map<Integer, Certificate> publicCerts = new ConcurrentHashMap<>();
    publicCerts.put(SUPER_TENANT_ID, ReadCertStoreSampleUtil.createKeyStore(getClass()).getCertificate("wso2carbon"));
    setFinalStatic(OAuth2Util.class.getDeclaredField("publicCerts"), publicCerts);
    Map<Integer, Key> privateKeys = new ConcurrentHashMap<>();
    privateKeys.put(SUPER_TENANT_ID, ReadCertStoreSampleUtil.createKeyStore(getClass()).getKey("wso2carbon", "wso2carbon".toCharArray()));
    setFinalStatic(OAuth2Util.class.getDeclaredField("privateKeys"), privateKeys);
    OpenIDConnectServiceComponentHolder.getInstance().getOpenIDConnectClaimFilters().add(new OpenIDConnectClaimFilterImpl());
    RequestObjectService requestObjectService = Mockito.mock(RequestObjectService.class);
    List<RequestedClaim> requestedClaims = Collections.EMPTY_LIST;
    when(requestObjectService.getRequestedClaimsForIDToken(anyString())).thenReturn(requestedClaims);
    when(requestObjectService.getRequestedClaimsForUserInfo(anyString())).thenReturn(requestedClaims);
    OpenIDConnectServiceComponentHolder.getInstance().getOpenIDConnectClaimFilters().add(new OpenIDConnectClaimFilterImpl());
    OpenIDConnectServiceComponentHolder.setRequestObjectService(requestObjectService);
    OAuth2ServiceComponentHolder.setKeyIDProvider(new DefaultKeyIDProviderImpl());
    ClaimProvider claimProvider = new OpenIDConnectSystemClaimImpl();
    List claimProviders = new ArrayList();
    claimProviders.add(claimProvider);
    WhiteboxImpl.setInternalState(OpenIDConnectServiceComponentHolder.getInstance(), "claimProviders", claimProviders);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) RequestedClaim(org.wso2.carbon.identity.openidconnect.model.RequestedClaim) AuthenticationMethodNameTranslatorImpl(org.wso2.carbon.identity.application.authentication.framework.internal.impl.AuthenticationMethodNameTranslatorImpl) ArrayList(java.util.ArrayList) ApplicationManagementServiceComponent(org.wso2.carbon.identity.application.mgt.internal.ApplicationManagementServiceComponent) Matchers.anyString(org.mockito.Matchers.anyString) OAuth2AccessTokenRespDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO) AuthorizationGrantCacheKey(org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheKey) List(java.util.List) ArrayList(java.util.ArrayList) ApplicationManagementService(org.wso2.carbon.identity.application.mgt.ApplicationManagementService) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ServiceProviderProperty(org.wso2.carbon.identity.application.common.model.ServiceProviderProperty) DefaultKeyIDProviderImpl(org.wso2.carbon.identity.oauth2.keyidprovider.DefaultKeyIDProviderImpl) AuthenticationMethodNameTranslator(org.wso2.carbon.identity.application.authentication.framework.AuthenticationMethodNameTranslator) IdentityProvider(org.wso2.carbon.identity.application.common.model.IdentityProvider) ClaimMapping(org.wso2.carbon.identity.application.common.model.ClaimMapping) AuthorizationGrantCacheEntry(org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheEntry) RealmService(org.wso2.carbon.user.core.service.RealmService) WithRealmService(org.wso2.carbon.identity.common.testng.WithRealmService) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) JSONObject(org.json.JSONObject) OAuth2Util(org.wso2.carbon.identity.oauth2.util.OAuth2Util) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) Key(java.security.Key) AuthorizationGrantCacheKey(org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheKey) Certificate(java.security.cert.Certificate) BeforeClass(org.testng.annotations.BeforeClass)

Example 39 with OAuth2AccessTokenRespDTO

use of org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2TokenEndpointTest method testTokenErrorResponse.

@Test(dataProvider = "testTokenErrorResponseDataProvider", groups = "testWithConnection")
public void testTokenErrorResponse(String errorCode, Object headerObj, int expectedStatus, String expectedErrorCode) throws Exception {
    ResponseHeader[] responseHeaders = (ResponseHeader[]) headerObj;
    Map<String, String[]> requestParams = new HashMap<>();
    requestParams.put(OAuth.OAUTH_GRANT_TYPE, new String[] { GrantType.PASSWORD.toString() });
    requestParams.put(OAuth.OAUTH_USERNAME, new String[] { USERNAME });
    requestParams.put(OAuth.OAUTH_PASSWORD, new String[] { "password" });
    mockStatic(LoggerUtils.class);
    when(LoggerUtils.isDiagnosticLogsEnabled()).thenReturn(true);
    mockStatic(IdentityTenantUtil.class);
    when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(-1234);
    HttpServletRequest request = mockHttpRequest(requestParams, new HashMap<String, Object>());
    when(request.getHeader(OAuthConstants.HTTP_REQ_HEADER_AUTHZ)).thenReturn(AUTHORIZATION_HEADER);
    when(request.getHeaderNames()).thenReturn(Collections.enumeration(new ArrayList<String>() {

        {
            add(OAuthConstants.HTTP_REQ_HEADER_AUTHZ);
        }
    }));
    spy(EndpointUtil.class);
    doReturn(REALM).when(EndpointUtil.class, "getRealmInfo");
    doReturn(oAuth2Service).when(EndpointUtil.class, "getOAuth2Service");
    when(oAuth2Service.issueAccessToken(any(OAuth2AccessTokenReqDTO.class))).thenReturn(oAuth2AccessTokenRespDTO);
    when(oAuth2AccessTokenRespDTO.getErrorMsg()).thenReturn("Token Response error");
    when(oAuth2AccessTokenRespDTO.getErrorCode()).thenReturn(errorCode);
    when(oAuth2AccessTokenRespDTO.getResponseHeaders()).thenReturn(responseHeaders);
    mockOAuthServerConfiguration();
    mockStatic(IdentityDatabaseUtil.class);
    when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection);
    Map<String, Class<? extends OAuthValidator<HttpServletRequest>>> grantTypeValidators = new Hashtable<>();
    grantTypeValidators.put(GrantType.PASSWORD.toString(), PasswordValidator.class);
    when(oAuthServerConfiguration.getSupportedGrantTypeValidators()).thenReturn(grantTypeValidators);
    when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE");
    Response response;
    try {
        response = oAuth2TokenEndpoint.issueAccessToken(request, new MultivaluedHashMap<String, String>());
    } catch (InvalidRequestParentException ire) {
        InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper();
        response = invalidRequestExceptionMapper.toResponse(ire);
    }
    assertNotNull(response, "Token response is null");
    assertEquals(response.getStatus(), expectedStatus, "Unexpected HTTP response status");
    assertNotNull(response.getEntity(), "Response entity is null");
    assertTrue(response.getEntity().toString().contains(expectedErrorCode), "Expected error code not found");
}
Also used : ResponseHeader(org.wso2.carbon.identity.oauth2.ResponseHeader) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) Hashtable(java.util.Hashtable) ArrayList(java.util.ArrayList) Matchers.anyString(org.mockito.Matchers.anyString) OAuth2AccessTokenReqDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenReqDTO) HttpServletRequest(javax.servlet.http.HttpServletRequest) Response(javax.ws.rs.core.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) InvalidRequestParentException(org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException) InvalidRequestExceptionMapper(org.wso2.carbon.identity.oauth.endpoint.expmapper.InvalidRequestExceptionMapper) OAuthValidator(org.apache.oltu.oauth2.common.validators.OAuthValidator) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 40 with OAuth2AccessTokenRespDTO

use of org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO in project identity-inbound-auth-oauth by wso2-extensions.

the class SAML2BearerGrantHandler method handleClaimsInAssertion.

protected void handleClaimsInAssertion(OAuthTokenReqMessageContext tokenReqMsgCtx, OAuth2AccessTokenRespDTO responseDTO, Assertion assertion) throws IdentityOAuth2Exception {
    Map<String, String> attributes = ClaimsUtil.extractClaimsFromAssertion(tokenReqMsgCtx, responseDTO, assertion, FrameworkUtils.getMultiAttributeSeparator());
    if (attributes != null && attributes.size() > 0) {
        String tenantDomain = tokenReqMsgCtx.getOauth2AccessTokenReqDTO().getTenantDomain();
        if (StringUtils.isBlank(tenantDomain)) {
            tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
        }
        if (OAuthServerConfiguration.getInstance().isConvertOriginalClaimsFromAssertionsToOIDCDialect()) {
            IdentityProvider identityProvider = getIdentityProvider(assertion, tenantDomain);
            boolean localClaimDialect = identityProvider.getClaimConfig().isLocalClaimDialect();
            ClaimMapping[] idPClaimMappings = identityProvider.getClaimConfig().getClaimMappings();
            Map<String, String> localClaims;
            if (ClaimsUtil.isResidentIdp(identityProvider)) {
                localClaims = handleClaimsForResidentIDP(attributes, identityProvider);
            } else {
                localClaims = handleClaimsForIDP(attributes, tenantDomain, identityProvider, localClaimDialect, idPClaimMappings);
            }
            // Handle IdP Role Mappings, for all the claims that contain roles, groups, or both.
            for (String roleGroupClaim : IdentityUtil.getRoleGroupClaims()) {
                handleIdPRoleMapping(tokenReqMsgCtx, responseDTO, identityProvider, localClaims, roleGroupClaim);
            }
            if (localClaims != null && localClaims.size() > 0) {
                Map<String, String> oidcClaims;
                try {
                    oidcClaims = ClaimsUtil.convertClaimsToOIDCDialect(tokenReqMsgCtx, localClaims);
                } catch (IdentityApplicationManagementException | IdentityException e) {
                    throw new IdentityOAuth2Exception("Error while converting user claims to OIDC dialect from idp " + identityProvider.getIdentityProviderName(), e);
                }
                Map<ClaimMapping, String> claimMappings = FrameworkUtils.buildClaimMappings(oidcClaims);
                addUserAttributesToCache(responseDTO, tokenReqMsgCtx, claimMappings);
            }
        } else {
            // Not converting claims. Sending the claim uris in original format.
            Map<ClaimMapping, String> claimMappings = FrameworkUtils.buildClaimMappings(attributes);
            // Handle IdP Role Mappings
            for (Iterator<Map.Entry<ClaimMapping, String>> iterator = claimMappings.entrySet().iterator(); iterator.hasNext(); ) {
                Map.Entry<ClaimMapping, String> entry = iterator.next();
                if (IdentityUtil.getRoleGroupClaims().stream().anyMatch(roleGroupClaim -> roleGroupClaim.equals(entry.getKey().getLocalClaim().getClaimUri())) && StringUtils.isNotBlank(entry.getValue())) {
                    IdentityProvider identityProvider = getIdentityProvider(assertion, tenantDomain);
                    String updatedRoleClaimValue = getUpdatedRoleClaimValue(identityProvider, entry.getValue());
                    if (updatedRoleClaimValue != null) {
                        entry.setValue(updatedRoleClaimValue);
                    } else {
                        iterator.remove();
                    }
                    break;
                }
            }
            addUserAttributesToCache(responseDTO, tokenReqMsgCtx, claimMappings);
        }
    }
}
Also used : X509Certificate(java.security.cert.X509Certificate) StringUtils(org.apache.commons.lang.StringUtils) OAuthServerConfiguration(org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration) X509Credential(org.opensaml.security.x509.X509Credential) SignatureValidator(org.opensaml.xmlsec.signature.support.SignatureValidator) SAMLInitializer(org.wso2.carbon.identity.saml.common.util.SAMLInitializer) OAuthComponentServiceHolder(org.wso2.carbon.identity.oauth.internal.OAuthComponentServiceHolder) KeyStoreException(java.security.KeyStoreException) AbstractAuthorizationGrantHandler(org.wso2.carbon.identity.oauth2.token.handlers.grant.AbstractAuthorizationGrantHandler) Base64(org.apache.commons.codec.binary.Base64) RealmService(org.wso2.carbon.user.core.service.RealmService) IdentityPersistenceManager(org.wso2.carbon.identity.core.persistence.IdentityPersistenceManager) SignatureException(org.opensaml.xmlsec.signature.support.SignatureException) Map(java.util.Map) SAMLSSOServiceProviderDO(org.wso2.carbon.identity.core.model.SAMLSSOServiceProviderDO) UnmarshallUtils(org.wso2.carbon.identity.saml.common.util.UnmarshallUtils) IdentityApplicationManagementException(org.wso2.carbon.identity.application.common.IdentityApplicationManagementException) OAuth2Util(org.wso2.carbon.identity.oauth2.util.OAuth2Util) RoleMapping(org.wso2.carbon.identity.application.common.model.RoleMapping) CertificateInfo(org.wso2.carbon.identity.application.common.model.CertificateInfo) Audience(org.opensaml.saml.saml2.core.Audience) KeyStore(java.security.KeyStore) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) FileNotFoundException(java.io.FileNotFoundException) StandardCharsets(java.nio.charset.StandardCharsets) SubjectConfirmationData(org.opensaml.saml.saml2.core.SubjectConfirmationData) ClaimsUtil(org.wso2.carbon.identity.oauth2.util.ClaimsUtil) OAuthTokenReqMessageContext(org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext) List(java.util.List) IdentityConstants(org.wso2.carbon.identity.base.IdentityConstants) MultitenantUtils(org.wso2.carbon.utils.multitenancy.MultitenantUtils) RegistryType(org.wso2.carbon.context.RegistryType) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) LogFactory(org.apache.commons.logging.LogFactory) FrameworkUtils(org.wso2.carbon.identity.application.authentication.framework.util.FrameworkUtils) IdentityException(org.wso2.carbon.identity.base.IdentityException) SubjectConfirmation(org.opensaml.saml.saml2.core.SubjectConfirmation) AudienceRestriction(org.opensaml.saml.saml2.core.AudienceRestriction) UserStoreException(org.wso2.carbon.user.api.UserStoreException) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) HashMap(java.util.HashMap) Conditions(org.opensaml.saml.saml2.core.Conditions) ArrayList(java.util.ArrayList) Property(org.wso2.carbon.identity.application.common.model.Property) IdentityUnmarshallingException(org.wso2.carbon.identity.saml.common.util.exception.IdentityUnmarshallingException) Calendar(java.util.Calendar) ClaimMapping(org.wso2.carbon.identity.application.common.model.ClaimMapping) OAuth2AccessTokenRespDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO) CollectionUtils(org.apache.commons.collections.CollectionUtils) InitializationException(org.opensaml.core.config.InitializationException) SAMLSignatureProfileValidator(org.opensaml.saml.security.impl.SAMLSignatureProfileValidator) IdentityApplicationConstants(org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants) Assertion(org.opensaml.saml.saml2.core.Assertion) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) PermissionsAndRoleConfig(org.wso2.carbon.identity.application.common.model.PermissionsAndRoleConfig) UserCoreUtil(org.wso2.carbon.user.core.util.UserCoreUtil) MultitenantConstants(org.wso2.carbon.base.MultitenantConstants) XMLObject(org.opensaml.core.xml.XMLObject) SAMLConstants(org.opensaml.saml.common.xml.SAMLConstants) IdentityTenantUtil(org.wso2.carbon.identity.core.util.IdentityTenantUtil) NodeList(org.w3c.dom.NodeList) UserStoreManager(org.wso2.carbon.user.api.UserStoreManager) Iterator(java.util.Iterator) OAuthConstants(org.wso2.carbon.identity.oauth.common.OAuthConstants) SignatureValidationProvider(org.opensaml.xmlsec.signature.support.SignatureValidationProvider) DateTime(org.joda.time.DateTime) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) CertificateException(java.security.cert.CertificateException) IdentityProviderManager(org.wso2.carbon.idp.mgt.IdentityProviderManager) FederatedAuthenticatorConfig(org.wso2.carbon.identity.application.common.model.FederatedAuthenticatorConfig) IdentityApplicationManagementUtil(org.wso2.carbon.identity.application.common.util.IdentityApplicationManagementUtil) ServerConfiguration(org.wso2.carbon.base.ServerConfiguration) X509CredentialImpl(org.wso2.carbon.identity.oauth2.util.X509CredentialImpl) IdentityProvider(org.wso2.carbon.identity.application.common.model.IdentityProvider) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) Registry(org.wso2.carbon.registry.core.Registry) IdentityUtil(org.wso2.carbon.identity.core.util.IdentityUtil) OAuth2ServiceComponentHolder(org.wso2.carbon.identity.oauth2.internal.OAuth2ServiceComponentHolder) IdentityProviderManagementException(org.wso2.carbon.idp.mgt.IdentityProviderManagementException) Log(org.apache.commons.logging.Log) ArrayUtils(org.apache.commons.lang.ArrayUtils) IdentityApplicationManagementException(org.wso2.carbon.identity.application.common.IdentityApplicationManagementException) IdentityProvider(org.wso2.carbon.identity.application.common.model.IdentityProvider) IdentityException(org.wso2.carbon.identity.base.IdentityException) ClaimMapping(org.wso2.carbon.identity.application.common.model.ClaimMapping) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

OAuth2AccessTokenRespDTO (org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO)30 OAuth2AccessTokenReqDTO (org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenReqDTO)19 Test (org.testng.annotations.Test)18 HashMap (java.util.HashMap)16 Matchers.anyString (org.mockito.Matchers.anyString)15 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)15 PowerMockIdentityBaseTest (org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest)12 OAuthClientAuthnContext (org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext)10 AuthorizationGrantHandler (org.wso2.carbon.identity.oauth2.token.handlers.grant.AuthorizationGrantHandler)10 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)9 ArrayList (java.util.ArrayList)7 ResponseHeader (org.wso2.carbon.identity.oauth2.ResponseHeader)6 AuthorizationGrantCacheEntry (org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheEntry)5 OAuthAppDO (org.wso2.carbon.identity.oauth.dao.OAuthAppDO)5 OAuthTokenReqMessageContext (org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext)5 Hashtable (java.util.Hashtable)4 InvocationOnMock (org.mockito.invocation.InvocationOnMock)4 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)4 Date (java.util.Date)3 Map (java.util.Map)3