org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception Java Examples

The following examples show how to use org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception. 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: CellerySignedJWTGenerator.java    From cellery-security with Apache License 2.0 6 votes vote down vote up
private String getEndUserName(TokenValidationContext validationContext) throws APIManagementException {

        try {
            String accessToken = validationContext.getAccessToken();
            AccessTokenDO tokenInfo = OAuth2Util.getAccessTokenDOfromTokenIdentifier(accessToken);
            AuthenticatedUser authzUser = tokenInfo.getAuthzUser();
            String endUserName = validationContext.getValidationInfoDTO().getEndUserName();
            if (authzUser.isFederatedUser()) {
                return endUserName;
            } else {
                return MultitenantUtils.getTenantAwareUsername(endUserName);
            }
        } catch (IdentityOAuth2Exception e) {
            throw new APIManagementException("Error while retrieving authenticated user metadata.", e);
        }

    }
 
Example #2
Source File: OpenIDConnectUserRPStore.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * @param user
 * @param appName
 * @return
 * @throws OAuthSystemException
 */
public synchronized boolean hasUserApproved(AuthenticatedUser user, String appName, String clientId) throws
        OAuthSystemException {
    OpenIDUserRPDAO dao = new OpenIDUserRPDAO();
    OpenIDUserRPDO rpDO;
    int tenantId = -1;
    if (user.getUserName() != null) {
        tenantId = IdentityTenantUtil.getTenantId(user.getTenantDomain());
    } else {
        OAuthAppDAO oAuthAppDAO = new OAuthAppDAO();
        OAuthAppDO appDO;
        try {
            appDO = oAuthAppDAO.getAppInformation(clientId);
            tenantId = IdentityTenantUtil.getTenantId(appDO.getUser().getTenantDomain());
        } catch (IdentityOAuth2Exception | InvalidOAuthClientException e) {
            throw new OAuthSystemException("Error while retrieving app");
        }
    }

    rpDO = dao.getOpenIDUserRP(user.getAuthenticatedSubjectIdentifier(), appName, tenantId);
    if (rpDO != null && rpDO.isTrustedAlways()) {
        return true;
    }

    return false;
}
 
Example #3
Source File: ExtendedJWTGrantHandler.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Override
public boolean validateGrant(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception {

    RequestParameter[] requestParameters = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getRequestParameters();
    for (RequestParameter requestParameter : requestParameters) {
        if (TENANT_DOMAIN_KEY.equals(requestParameter.getKey())) {
            String[] values = requestParameter.getValue();
            if (values != null && values.length > 0) {
                tokReqMsgCtx.getOauth2AccessTokenReqDTO()
                        .setTenantDomain(values[0]);
            }
        }
    }

    return super.validateGrant(tokReqMsgCtx);
}
 
Example #4
Source File: DefaultClaimsRetriever.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
@Override
public String[] getDefaultClaims(String endUserName) throws IdentityOAuth2Exception {

    int tenantId = MultitenantConstants.SUPER_TENANT_ID;
    try {
        tenantId = OAuth2Util.getTenantIdFromUserName(endUserName);
        // if no claims were requested, return all
        if(log.isDebugEnabled()){
            log.debug("No claims set requested. Returning all claims in the dialect");
        }
        ClaimManager claimManager =
                OAuthComponentServiceHolder.getRealmService().getTenantUserRealm(tenantId).getClaimManager();
        ClaimMapping[] claims = claimManager.getAllClaimMappings(dialectURI);
        return claimToString(claims);
    } catch (UserStoreException e) {
        throw new IdentityOAuth2Exception("Error while reading default claims for user : " + endUserName, e);
    }
}
 
Example #5
Source File: TokenMgtDAO.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public String findScopeOfResource(String resourceUri) throws IdentityOAuth2Exception {

        Connection connection = IdentityDatabaseUtil.getDBConnection();;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            String sql = SQLQueries.RETRIEVE_IOS_SCOPE_KEY;

            ps = connection.prepareStatement(sql);
            ps.setString(1, resourceUri);
            rs = ps.executeQuery();

            if (rs.next()) {
                return rs.getString("SCOPE_KEY");
            }
            connection.commit();
            return null;
        } catch (SQLException e) {
            String errorMsg = "Error getting scopes for resource - " + resourceUri + " : " + e.getMessage();
            throw new IdentityOAuth2Exception(errorMsg, e);
        } finally {
            IdentityDatabaseUtil.closeAllConnections(connection, rs, ps);
        }
    }
 
Example #6
Source File: DefaultIDTokenBuilder.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Generic Signing function
 *
 * @param jwtClaimsSet contains JWT body
 * @param request
 * @return
 * @throws IdentityOAuth2Exception
 */
protected String signJWT(JWTClaimsSet jwtClaimsSet, OAuthTokenReqMessageContext request)
        throws IdentityOAuth2Exception {

    if (JWSAlgorithm.RS256.equals(signatureAlgorithm) || JWSAlgorithm.RS384.equals(signatureAlgorithm) ||
            JWSAlgorithm.RS512.equals(signatureAlgorithm)) {
        return signJWTWithRSA(jwtClaimsSet, request);
    } else if (JWSAlgorithm.HS256.equals(signatureAlgorithm) || JWSAlgorithm.HS384.equals(signatureAlgorithm) ||
            JWSAlgorithm.HS512.equals(signatureAlgorithm)) {
        // return signWithHMAC(jwtClaimsSet,jwsAlgorithm,request); implementation need to be done
        return null;
    } else {
        // return signWithEC(jwtClaimsSet,jwsAlgorithm,request); implementation need to be done
        return null;
    }
}
 
Example #7
Source File: JWTTokenGenerator.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Helper method to add public certificate to JWT_HEADER to signature verification.
 *
 * @param tenantDomain
 * @param tenantId
 * @throws IdentityOAuth2Exception
 */
private String getThumbPrint(String tenantDomain, int tenantId) throws IdentityOAuth2Exception {

    try {

        Certificate certificate = getCertificate(tenantDomain, tenantId);

        // TODO: maintain a hashmap with tenants' pubkey thumbprints after first initialization

        //generate the SHA-1 thumbprint of the certificate
        MessageDigest digestValue = MessageDigest.getInstance("SHA-1");
        byte[] der = certificate.getEncoded();
        digestValue.update(der);
        byte[] digestInBytes = digestValue.digest();

        String publicCertThumbprint = hexify(digestInBytes);
        String base64EncodedThumbPrint = new String(base64Url.encode(publicCertThumbprint.getBytes(Charsets.UTF_8)), Charsets.UTF_8);
        return base64EncodedThumbPrint;

    } catch (Exception e) {
        String error = "Error in obtaining certificate for tenant " + tenantDomain;
        throw new IdentityOAuth2Exception(error, e);
    }
}
 
Example #8
Source File: JWTAccessTokenBuilder.java    From msf4j with Apache License 2.0 6 votes vote down vote up
/**
 * Generic Signing function
 *
 * @param jwtClaimsSet contains JWT body
 * @param request
 * @return
 * @throws IdentityOAuth2Exception
 */
protected String signJWT(JWTClaimsSet jwtClaimsSet, OAuthTokenReqMessageContext request)
        throws IdentityOAuth2Exception {

    if (JWSAlgorithm.RS256.equals(signatureAlgorithm) || JWSAlgorithm.RS384.equals(signatureAlgorithm) ||
            JWSAlgorithm.RS512.equals(signatureAlgorithm)) {
        return signJWTWithRSA(jwtClaimsSet, request);
    } else if (JWSAlgorithm.HS256.equals(signatureAlgorithm) || JWSAlgorithm.HS384.equals(signatureAlgorithm) ||
            JWSAlgorithm.HS512.equals(signatureAlgorithm)) {
        // return signWithHMAC(jwtClaimsSet,jwsAlgorithm,request); implementation need to be done
        return null;
    } else {
        // return signWithEC(jwtClaimsSet,jwsAlgorithm,request); implementation need to be done
        return null;
    }
}
 
Example #9
Source File: JWTTokenGenerator.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Generic Signing function
 *
 * @param signedJWT
 * @param tenantDomain
 * @param tenantId
 * @return
 * @throws IdentityOAuth2Exception
 */
protected JWT signJWT(SignedJWT signedJWT, String tenantDomain, int tenantId)
        throws IdentityOAuth2Exception {

    if (JWSAlgorithm.RS256.equals(signatureAlgorithm) || JWSAlgorithm.RS384.equals(signatureAlgorithm) ||
            JWSAlgorithm.RS512.equals(signatureAlgorithm)) {
        return signJWTWithRSA(signedJWT, signatureAlgorithm, tenantDomain, tenantId);
    } else if (JWSAlgorithm.HS256.equals(signatureAlgorithm) ||
            JWSAlgorithm.HS384.equals(signatureAlgorithm) ||
            JWSAlgorithm.HS512.equals(signatureAlgorithm)) {
        // return signWithHMAC(payLoad,jwsAlgorithm,tenantDomain,tenantId); implementation
        // need to be done
    } else if (JWSAlgorithm.ES256.equals(signatureAlgorithm) ||
            JWSAlgorithm.ES384.equals(signatureAlgorithm) ||
            JWSAlgorithm.ES512.equals(signatureAlgorithm)) {
        // return signWithEC(payLoad,jwsAlgorithm,tenantDomain,tenantId); implementation
        // need to be done
    }
    log.error("UnSupported Signature Algorithm");
    throw new IdentityOAuth2Exception("UnSupported Signature Algorithm");
}
 
Example #10
Source File: CellerySignedJWTValidator.java    From cellery-security with Apache License 2.0 6 votes vote down vote up
private IdentityProvider getLocalIdpForIssuer(String jwtIssuer,
                                              String tenantDomain) throws IdentityOAuth2Exception {

    String residentIdpIssuer = null;
    IdentityProvider residentIdentityProvider;
    try {
        residentIdentityProvider = IdentityProviderManager.getInstance().getResidentIdP(tenantDomain);
    } catch (IdentityProviderManagementException e) {
        throw new IdentityOAuth2Exception("Error retrieving resident IDP information for issuer: " + jwtIssuer +
                " of tenantDomain: " + tenantDomain, e);
    }

    FederatedAuthenticatorConfig[] fedAuthnConfigs = residentIdentityProvider.getFederatedAuthenticatorConfigs();
    FederatedAuthenticatorConfig oauthAuthenticatorConfig =
            IdentityApplicationManagementUtil.getFederatedAuthenticator(fedAuthnConfigs,
                    IdentityApplicationConstants.Authenticator.OIDC.NAME);
    if (oauthAuthenticatorConfig != null) {
        residentIdpIssuer = IdentityApplicationManagementUtil.getProperty(oauthAuthenticatorConfig.getProperties(),
                Utils.OPENID_IDP_ENTITY_ID).getValue();
    }
    return StringUtils.equalsIgnoreCase(residentIdpIssuer, jwtIssuer) ? residentIdentityProvider : null;
}
 
Example #11
Source File: OAuth2Util.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public static Map<String, String> getAvailableUserStoreDomainMappings() throws
        IdentityOAuth2Exception {
    //TreeMap is used to ignore the case sensitivity of key. Because when user logged in, the case of the user name is ignored.
    Map<String, String> userStoreDomainMap = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
    String domainsStr = getAccessTokenPartitioningDomains();
    if (domainsStr != null) {
        String[] userStoreDomainsArr = domainsStr.split(",");
        for (String userStoreDomains : userStoreDomainsArr) {
            String[] mapping = userStoreDomains.trim().split(":"); //A:foo.com , B:bar.com
            if (mapping.length < 2) {
                throw new IdentityOAuth2Exception("Domain mapping has not defined correctly");
            }
            userStoreDomainMap.put(mapping[1].trim(), mapping[0].trim()); //key=domain & value=mapping
        }
    }
    return userStoreDomainMap;
}
 
Example #12
Source File: CellerySignedJWTValidator.java    From cellery-security with Apache License 2.0 6 votes vote down vote up
private void validateExpiryTime(JWTClaimsSet claimsSet) throws IdentityOAuth2Exception {

        long timeStampSkewMillis = OAuthServerConfiguration.getInstance().getTimeStampSkewInSeconds() * 1000;
        long expirationTimeInMillis = claimsSet.getExpirationTime().getTime();
        long currentTimeInMillis = System.currentTimeMillis();
        if ((currentTimeInMillis + timeStampSkewMillis) > expirationTimeInMillis) {
            if (log.isDebugEnabled()) {
                log.debug("Token is expired." +
                        ", Expiration Time(ms) : " + expirationTimeInMillis +
                        ", TimeStamp Skew : " + timeStampSkewMillis +
                        ", Current Time : " + currentTimeInMillis + ". Token Rejected and validation terminated.");
            }
            throw new IdentityOAuth2Exception("Token is expired.");
        }

        if (log.isDebugEnabled()) {
            log.debug("Expiration Time(exp) of Token was validated successfully.");
        }
    }
 
Example #13
Source File: OAuth2Util.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public static String getAccessTokenStoreTableFromUserId(String userId)
        throws IdentityOAuth2Exception {
    String accessTokenStoreTable = OAuthConstants.ACCESS_TOKEN_STORE_TABLE;
    String userStore;
    if (userId != null) {
        String[] strArr = userId.split("/");
        if (strArr != null && strArr.length > 1) {
            userStore = strArr[0];
            Map<String, String> availableDomainMappings = getAvailableUserStoreDomainMappings();
            if (availableDomainMappings != null &&
                    availableDomainMappings.containsKey(userStore)) {
                accessTokenStoreTable = accessTokenStoreTable + "_" +
                        availableDomainMappings.get(userStore);
            }
        }
    }
    return accessTokenStoreTable;
}
 
Example #14
Source File: AbstractAuthorizationGrantHandler.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
@Override
public boolean authorizeAccessDelegation(OAuthTokenReqMessageContext tokReqMsgCtx)
        throws IdentityOAuth2Exception {
    OAuthCallback authzCallback = new OAuthCallback(tokReqMsgCtx.getAuthorizedUser(),
            tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId(),
            OAuthCallback.OAuthCallbackType.ACCESS_DELEGATION_TOKEN);
    authzCallback.setRequestedScope(tokReqMsgCtx.getScope());
    if (tokReqMsgCtx.getOauth2AccessTokenReqDTO().getGrantType().equals(
            org.wso2.carbon.identity.oauth.common.GrantType.SAML20_BEARER.toString())) {
        authzCallback.setCarbonGrantType(org.wso2.carbon.identity.oauth.common.GrantType.valueOf(
                OAuthConstants.OAUTH_SAML2_BEARER_GRANT_ENUM.toString()));
    } else if (tokReqMsgCtx.getOauth2AccessTokenReqDTO().getGrantType().equals(
            org.wso2.carbon.identity.oauth.common.GrantType.IWA_NTLM.toString())) {
        authzCallback.setCarbonGrantType(org.wso2.carbon.identity.oauth.common.GrantType.valueOf(
                OAuthConstants.OAUTH_IWA_NTLM_GRANT_ENUM.toString()));
    } else {
        authzCallback.setGrantType(tokReqMsgCtx.getOauth2AccessTokenReqDTO().getGrantType());
    }
    callbackManager.handleCallback(authzCallback);
    tokReqMsgCtx.setValidityPeriod(authzCallback.getValidityPeriod());
    return authzCallback.isAuthorized();
}
 
Example #15
Source File: CellerySignedJWTValidator.java    From cellery-security with Apache License 2.0 6 votes vote down vote up
private boolean isSignedJWTValid(SignedJWT signedJWT) throws IdentityOAuth2Exception {

        try {
            JWTClaimsSet claimsSet = signedJWT.getJWTClaimsSet();

            if (claimsSet == null) {
                throw new IdentityOAuth2Exception("Claim values are empty in the validated JWT.");
            } else {
                validateMandatoryJWTClaims(claimsSet);
                validateConsumerKey(claimsSet);
                validateExpiryTime(claimsSet);
                validateNotBeforeTime(claimsSet);
                validateAudience(claimsSet);

                IdentityProvider trustedIdp = getTrustedIdp(claimsSet);
                return Utils.validateSignature(signedJWT, trustedIdp);
            }
        } catch (ParseException ex) {
            throw new IdentityOAuth2Exception("Error while validating JWT.", ex);
        }
    }
 
Example #16
Source File: ClientCredentialsGrantHandler.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
protected JWSAlgorithm mapSignatureAlgorithm(String signatureAlgorithm)
        throws IdentityOAuth2Exception {
    if ("SHA256withRSA".equals(signatureAlgorithm)) {
        return JWSAlgorithm.RS256;
    } else if ("SHA384withRSA".equals(signatureAlgorithm)) {
        return JWSAlgorithm.RS384;
    } else if ("SHA512withRSA".equals(signatureAlgorithm)) {
        return JWSAlgorithm.RS512;
    } else if ("SHA256withHMAC".equals(signatureAlgorithm)) {
        return JWSAlgorithm.HS256;
    } else if ("SHA384withHMAC".equals(signatureAlgorithm)) {
        return JWSAlgorithm.HS384;
    } else if ("SHA512withHMAC".equals(signatureAlgorithm)) {
        return JWSAlgorithm.HS512;
    } else if ("SHA256withEC".equals(signatureAlgorithm)) {
        return JWSAlgorithm.ES256;
    } else if ("SHA384withEC".equals(signatureAlgorithm)) {
        return JWSAlgorithm.ES384;
    } else if ("SHA512withEC".equals(signatureAlgorithm)) {
        return JWSAlgorithm.ES512;
    }
    log.error("Unsupported Signature Algorithm in identity.xml");
    throw new IdentityOAuth2Exception("Unsupported Signature Algorithm in identity.xml");
}
 
Example #17
Source File: CellerySignedJWTValidator.java    From cellery-security with Apache License 2.0 5 votes vote down vote up
private IdentityProvider getTrustedIdp(JWTClaimsSet claimsSet) throws IdentityOAuth2Exception {

        String jwtIssuer = claimsSet.getIssuer();
        String tenantDomain = getTenantDomain(claimsSet);

        IdentityProvider identityProvider;
        try {
            identityProvider = IdentityProviderManager.getInstance().getIdPByName(jwtIssuer, tenantDomain);
            if (identityProvider != null) {
                // if no IDPs were found for a given name, the IdentityProviderManager returns a dummy IDP with the
                // name "default". We need to handle this case.
                if (StringUtils.equalsIgnoreCase(identityProvider.getIdentityProviderName(), "default")) {
                    // Check whether this jwt was issued by our local idp
                    identityProvider = getLocalIdpForIssuer(jwtIssuer, tenantDomain);
                }
            }

            if (identityProvider == null) {
                throw new IdentityOAuth2Exception("No trusted IDP registered with the issuer: " + jwtIssuer
                        + " in tenantDomain: " + tenantDomain);
            } else {
                return identityProvider;
            }
        } catch (IdentityProviderManagementException e) {
            throw new IdentityOAuth2Exception("Error while retrieving trusted IDP information for issuer: " + jwtIssuer
                    + " in tenantDomain: " + tenantDomain);
        }
    }
 
Example #18
Source File: EncryptionDecryptionPersistenceProcessor.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public String getProcessedRefreshToken(String refreshToken)
        throws IdentityOAuth2Exception {
    try {
        return encrypt(refreshToken);
    } catch (CryptoException e) {
        throw new IdentityOAuth2Exception("Error while retrieving processed refresh token", e);
    }
}
 
Example #19
Source File: ExtendedClientCredentialsGrantHandler.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Override
public boolean validateGrant(OAuthTokenReqMessageContext tokReqMsgCtx)
        throws IdentityOAuth2Exception {

    boolean validateResult = super.validateGrant(tokReqMsgCtx);
    AuthenticatedUser user = tokReqMsgCtx.getAuthorizedUser();
    String username = user.getUserName();
    user.setUserName(username);
    tokReqMsgCtx.setAuthorizedUser(user);

    return validateResult;
}
 
Example #20
Source File: JWTAccessTokenBuilder.java    From msf4j with Apache License 2.0 5 votes vote down vote up
protected String signJWT(JWTClaimsSet jwtClaimsSet, OAuthAuthzReqMessageContext request)
        throws IdentityOAuth2Exception {

    if (JWSAlgorithm.RS256.equals(signatureAlgorithm) || JWSAlgorithm.RS384.equals(signatureAlgorithm) ||
            JWSAlgorithm.RS512.equals(signatureAlgorithm)) {
        return signJWTWithRSA(jwtClaimsSet, request);
    } else if (JWSAlgorithm.HS256.equals(signatureAlgorithm) || JWSAlgorithm.HS384.equals(signatureAlgorithm) ||
            JWSAlgorithm.HS512.equals(signatureAlgorithm)) {
        // return signWithHMAC(jwtClaimsSet,jwsAlgorithm,request); implementation need to be done
        return null;
    } else {
        // return signWithEC(jwtClaimsSet,jwsAlgorithm,request); implementation need to be done
        return null;
    }
}
 
Example #21
Source File: EncryptionDecryptionPersistenceProcessor.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public String getPreprocessedRefreshToken(String processedRefreshToken)
        throws IdentityOAuth2Exception {
    try {
        return decrypt(processedRefreshToken);
    } catch (CryptoException e) {
        throw new IdentityOAuth2Exception("Error while retrieving preprocessed refresh token", e);
    }
}
 
Example #22
Source File: TokenMgtDAO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public boolean persistAccessToken(String accessToken, String consumerKey,
                                  AccessTokenDO newAccessTokenDO, AccessTokenDO existingAccessTokenDO,
                                  String userStoreDomain) throws IdentityOAuth2Exception {
    if (!enablePersist) {
        return false;
    }
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    try {
        if (existingAccessTokenDO != null) {
            //  Mark the existing access token as expired on database if a token exist for the user
            setAccessTokenState(connection, existingAccessTokenDO.getTokenId(), OAuthConstants.TokenStates
                    .TOKEN_STATE_EXPIRED, UUID.randomUUID().toString(), userStoreDomain);
        }

        if (newAccessTokenDO.getAuthorizationCode() != null) {
            storeAccessToken(accessToken, consumerKey, newAccessTokenDO, connection, userStoreDomain);
            // expire authz code and insert issued access token against authz code
            AuthzCodeDO authzCodeDO = new AuthzCodeDO();
            authzCodeDO.setAuthorizationCode(newAccessTokenDO.getAuthorizationCode());
            authzCodeDO.setOauthTokenId(newAccessTokenDO.getTokenId());
            List<AuthzCodeDO> authzCodeDOList = new ArrayList<>(Arrays.asList(authzCodeDO));
            deactivateAuthorizationCode(authzCodeDOList);
        } else {
            storeAccessToken(accessToken, consumerKey, newAccessTokenDO, connection, userStoreDomain);
        }
        connection.commit();
        return true;
    } catch (SQLException e) {
        throw new IdentityOAuth2Exception("Error occurred while persisting access token", e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, null);
    }
}
 
Example #23
Source File: ClientCredentialsGrantHandler.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public boolean validateGrant(OAuthTokenReqMessageContext tokReqMsgCtx)
        throws IdentityOAuth2Exception {

    if(!super.validateGrant(tokReqMsgCtx)){
        return false;
    }

    // By this time, we have already validated client credentials.
    tokReqMsgCtx.setScope(tokReqMsgCtx.getOauth2AccessTokenReqDTO().getScope());
    return true;
}
 
Example #24
Source File: TokenMgtDAO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public TokenMgtDAO() {
    try {
        persistenceProcessor = OAuthServerConfiguration.getInstance().getPersistenceProcessor();
    } catch (IdentityOAuth2Exception e) {
        log.error("Error retrieving TokenPersistenceProcessor. Defaulting to PlainTextProcessor", e);
        persistenceProcessor = new PlainTextPersistenceProcessor();
    }

    if (IdentityUtil.getProperty("JDBCPersistenceManager.TokenPersist.Enable") != null) {
        enablePersist = Boolean.parseBoolean(IdentityUtil.getProperty("JDBCPersistenceManager.TokenPersist.Enable"));
    }
}
 
Example #25
Source File: DefaultIDTokenBuilder.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
protected String signJWT(JWTClaimsSet jwtClaimsSet, OAuthAuthzReqMessageContext request)
        throws IdentityOAuth2Exception {

    if (JWSAlgorithm.RS256.equals(signatureAlgorithm) || JWSAlgorithm.RS384.equals(signatureAlgorithm) ||
            JWSAlgorithm.RS512.equals(signatureAlgorithm)) {
        return signJWTWithRSA(jwtClaimsSet, request);
    } else if (JWSAlgorithm.HS256.equals(signatureAlgorithm) || JWSAlgorithm.HS384.equals(signatureAlgorithm) ||
            JWSAlgorithm.HS512.equals(signatureAlgorithm)) {
        // return signWithHMAC(jwtClaimsSet,jwsAlgorithm,request); implementation need to be done
        return null;
    } else {
        // return signWithEC(jwtClaimsSet,jwsAlgorithm,request); implementation need to be done
        return null;
    }
}
 
Example #26
Source File: DefaultIDTokenBuilder.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * This method maps signature algorithm define in identity.xml to digest algorithms to generate the at_hash
 *
 * @param signatureAlgorithm
 * @return
 * @throws IdentityOAuth2Exception
 */
protected String mapDigestAlgorithm(Algorithm signatureAlgorithm) throws IdentityOAuth2Exception {

    if (JWSAlgorithm.RS256.equals(signatureAlgorithm) || JWSAlgorithm.HS256.equals(signatureAlgorithm) ||
        JWSAlgorithm.ES256.equals(signatureAlgorithm)) {
        return SHA256;
    } else if (JWSAlgorithm.RS384.equals(signatureAlgorithm) || JWSAlgorithm.HS384.equals(signatureAlgorithm) ||
               JWSAlgorithm.ES384.equals(signatureAlgorithm)) {
        return SHA384;
    } else if (JWSAlgorithm.RS512.equals(signatureAlgorithm) || JWSAlgorithm.HS512.equals(signatureAlgorithm) ||
               JWSAlgorithm.ES512.equals(signatureAlgorithm)) {
        return SHA512;
    }
    throw new RuntimeException("Cannot map Signature Algorithm in identity.xml to hashing algorithm");
}
 
Example #27
Source File: TokenResponseTypeHandler.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private void buildIdToken(OAuthAuthzReqMessageContext msgCtx, OAuth2AuthorizeRespDTO authzRespDTO)
        throws IdentityOAuth2Exception{

    if (StringUtils.contains(msgCtx.getAuthorizationReqDTO().getResponseType(), "id_token") &&
            msgCtx.getApprovedScope() != null && OAuth2Util.isOIDCAuthzRequest(msgCtx.getApprovedScope())) {
        IDTokenBuilder builder = OAuthServerConfiguration.getInstance().getOpenIDConnectIDTokenBuilder();
        authzRespDTO.setIdToken(builder.buildIDToken(msgCtx, authzRespDTO));
    }
}
 
Example #28
Source File: AbstractClientAuthHandler.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public boolean canAuthenticate(OAuthTokenReqMessageContext tokReqMsgCtx)
        throws IdentityOAuth2Exception {

    OAuth2AccessTokenReqDTO oAuth2AccessTokenReqDTO = tokReqMsgCtx.getOauth2AccessTokenReqDTO();

    if (StringUtils.isNotEmpty(oAuth2AccessTokenReqDTO.getClientId()) &&
            StringUtils.isNotEmpty(oAuth2AccessTokenReqDTO.getClientSecret())) {
        if (log.isDebugEnabled()) {
            log.debug("Can authenticate with client ID and Secret." +
                    " Client ID: "+ oAuth2AccessTokenReqDTO.getClientId());
        }
        return true;

    } else {
        if (org.wso2.carbon.identity.oauth.common.GrantType.SAML20_BEARER.toString().equals(
                oAuth2AccessTokenReqDTO.getGrantType())) {

            //Getting configured value for client credential validation requirements
            authConfig = properties.getProperty(
                    OAuthConstants.CLIENT_AUTH_CREDENTIAL_VALIDATION);

            if (log.isDebugEnabled()) {
                log.debug("Grant type : " + oAuth2AccessTokenReqDTO.getGrantType());
            }

            //If user has set strict validation to false, can authenticate without credentials
            if (StringUtils.isNotEmpty(authConfig) && JavaUtils.isFalseExplicitly(authConfig)) {
                if (log.isDebugEnabled()) {
                    log.debug("Client auth credential validation set to : " + authConfig + ". " +
                            "can authenticate without client secret");
                }
                return true;
            }
        }
    }
    return false;
}
 
Example #29
Source File: DefaultOAuth2TokenValidator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public boolean validateAccessToken(OAuth2TokenValidationMessageContext validationReqDTO)
        throws IdentityOAuth2Exception {

    // With bearer token we don't validate anything apart from access delegation and scopes
    return true;
}
 
Example #30
Source File: AuthorizationCodeGrantHandler.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public OAuth2AccessTokenRespDTO issue(OAuthTokenReqMessageContext tokReqMsgCtx)
        throws IdentityOAuth2Exception {
    OAuth2AccessTokenRespDTO tokenRespDTO = super.issue(tokReqMsgCtx);

    // get the token from the OAuthTokenReqMessageContext which is stored while validating
    // the authorization code.
    String authzCode = (String) tokReqMsgCtx.getProperty(AUTHZ_CODE);
    // if it's not there (which is unlikely), recalculate it.
    if (authzCode == null) {
        authzCode = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getAuthorizationCode();
    }

    // Clear the cache entry
    if (cacheEnabled) {
        String clientId = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId();
        OAuthCacheKey cacheKey = new OAuthCacheKey(OAuth2Util.buildCacheKeyStringForAuthzCode(
                clientId, authzCode));
        oauthCache.clearCacheEntry(cacheKey);

        if (log.isDebugEnabled()) {
            log.debug("Cache was cleared for authorization code info for client id : " + clientId);
        }
    }

    return tokenRespDTO;
}