org.wso2.carbon.identity.oauth2.util.OAuth2Util Java Examples

The following examples show how to use org.wso2.carbon.identity.oauth2.util.OAuth2Util. 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: OAuthCallbackHandlerRegistry.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Get the appropriate <Code>OAuthCallbackHandler</Code> for the given callback
 *
 * @param authzCallback <Code>OAuthCallback</Code> object
 * @return <Code>OAuthCallbackHandler</Code> instance which can handle the
 * given callback, return <Code>null</Code> if there is no OAuthCallbackHandler which
 * can handle the given callback
 * @throws IdentityOAuth2Exception Error while evaluating the canHandle method
 */
public OAuthCallbackHandler getOAuthAuthzHandler(
        OAuthCallback authzCallback) throws IdentityOAuth2Exception {

    for (OAuthCallbackHandler oauthAuthzCbHandler : authzCallbackHandlers) {
        if (oauthAuthzCbHandler.canHandle(new Callback[]{authzCallback})) {
            if (log.isDebugEnabled()) {
                log.debug("OAuthCallbackHandler was found for the callback. Class Name : " + oauthAuthzCbHandler
                        .getClass().getName() + " Resource Owner : " + authzCallback.getResourceOwner() + " " +
                        "Client Id : " + authzCallback.getClient() + " Scope : " + OAuth2Util.buildScopeString
                        (authzCallback.getRequestedScope()));
            }
            return oauthAuthzCbHandler;
        }
    }

    if (log.isDebugEnabled()) {
        log.debug("No OAuthAuthorizationCallbackHandlers were found for the callback. Resource Owner : " +
                authzCallback.getResourceOwner() + " Client Id : " + authzCallback.getClient() + " Scope : " +
                OAuth2Util.buildScopeString(authzCallback.getRequestedScope()));
    }
    return null;
}
 
Example #3
Source File: OAuthUserStoreConfigListenerImpl.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
@Override
public void onUserStoreNamePreUpdate(int tenantId, String currentUserStoreName, String newUserStoreName) throws
        UserStoreException {
    TokenMgtDAO tokenMgtDAO = new TokenMgtDAO();
    try {
        Set<AccessTokenDO> accessTokenDOs = tokenMgtDAO.getAccessTokensOfUserStore(tenantId, currentUserStoreName);
        for (AccessTokenDO accessTokenDO : accessTokenDOs) {
            //Clear cache
            OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), accessTokenDO.getAuthzUser(),
                    OAuth2Util.buildScopeString(accessTokenDO.getScope()));
            OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), accessTokenDO.getAuthzUser());
            OAuthUtil.clearOAuthCache(accessTokenDO.getAccessToken());
        }
        tokenMgtDAO.renameUserStoreDomainInAccessTokenTable(tenantId, currentUserStoreName, newUserStoreName);
        tokenMgtDAO.renameUserStoreDomainInAuthorizationCodeTable(tenantId, currentUserStoreName, newUserStoreName);
    } catch (IdentityOAuth2Exception e) {
        throw new UserStoreException("Error occurred while renaming user store : " + currentUserStoreName +
                " in tenant :" + tenantId, e);
    }
}
 
Example #4
Source File: TokenValidationHandler.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
    * 
    * @param accessTokenDO
    * @return
    * @throws IdentityOAuth2Exception 
    */
   private boolean hasAcessTokenExpired(AccessTokenDO accessTokenDO) {
// check whether the grant is expired
if (accessTokenDO.getValidityPeriod() < 0) {
    if (log.isDebugEnabled()) {
	log.debug("Access Token has infinite lifetime");
    }
} else {
    if (OAuth2Util.getAccessTokenExpireMillis(accessTokenDO) == 0) {
	if (log.isDebugEnabled()) {
	    log.debug("Access Token has expired");
	}
	return true;
    }
}

return false;
   }
 
Example #5
Source File: TokenValidationHandler.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
    * 
    * @param accessTokenDO
    * @return
    */
   private long getAccessTokenExpirationTime(AccessTokenDO accessTokenDO) {
long expiryTime = OAuth2Util.getAccessTokenExpireMillis(accessTokenDO);

if (OAuthConstants.UserType.APPLICATION_USER.equals(accessTokenDO.getTokenType())
	&& OAuthServerConfiguration.getInstance().getUserAccessTokenValidityPeriodInSeconds() < 0) {
    return Long.MAX_VALUE;
} else if (OAuthConstants.UserType.APPLICATION.equals(accessTokenDO.getTokenType())
	&& OAuthServerConfiguration.getInstance().getApplicationAccessTokenValidityPeriodInSeconds() < 0) {
    return Long.MAX_VALUE;
} else if (expiryTime < 0) {
    return Long.MAX_VALUE;
}

return expiryTime / 1000;
   }
 
Example #6
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 #7
Source File: JWTTokenGenerator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private Certificate getCertificate(String tenantDomain, int tenantId) throws Exception {

        if (tenantDomain == null) {
            tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
        }

        if (tenantId == 0) {
            tenantId = OAuth2Util.getTenantId(tenantDomain);
        }

        Certificate publicCert = null;

        if (!(publicCerts.containsKey(tenantId))) {
            // get tenant's key store manager
            KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId);

            KeyStore keyStore = null;
            if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
                // derive key store name
                String ksName = tenantDomain.trim().replace(".", "-");
                String jksName = ksName + ".jks";
                keyStore = tenantKSM.getKeyStore(jksName);
                publicCert = keyStore.getCertificate(tenantDomain);
            } else {
                publicCert = tenantKSM.getDefaultPrimaryCertificate();
            }
            if (publicCert != null) {
                publicCerts.put(tenantId, publicCert);
            }
        } else {
            publicCert = publicCerts.get(tenantId);
        }
        return publicCert;
    }
 
Example #8
Source File: TokenMgtDAO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public void persistAuthorizationCode(String authzCode, String consumerKey, String callbackUrl,
                                     AuthzCodeDO authzCodeDO) throws IdentityOAuth2Exception {

    if (!enablePersist) {
        return;
    }

    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement prepStmt = null;
    try {
        prepStmt = connection.prepareStatement(SQLQueries.STORE_AUTHORIZATION_CODE);
        prepStmt.setString(1, authzCodeDO.getAuthzCodeId());
        prepStmt.setString(2, persistenceProcessor.getProcessedAuthzCode(authzCode));
        prepStmt.setString(3, callbackUrl);
        prepStmt.setString(4, OAuth2Util.buildScopeString(authzCodeDO.getScope()));
        prepStmt.setString(5, authzCodeDO.getAuthorizedUser().getUserName());
        prepStmt.setString(6, authzCodeDO.getAuthorizedUser().getUserStoreDomain());
        int tenantId = OAuth2Util.getTenantId(authzCodeDO.getAuthorizedUser().getTenantDomain());
        prepStmt.setInt(7, tenantId);
        prepStmt.setTimestamp(8, authzCodeDO.getIssuedTime(),
                              Calendar.getInstance(TimeZone.getTimeZone(UTC)));
        prepStmt.setLong(9, authzCodeDO.getValidityPeriod());
        prepStmt.setString(10, authzCodeDO.getAuthorizedUser().getAuthenticatedSubjectIdentifier());
        prepStmt.setString(11, persistenceProcessor.getProcessedClientId(consumerKey));
        prepStmt.execute();
        connection.commit();
    } catch (SQLException e) {
        throw new IdentityOAuth2Exception("Error when storing the authorization code for consumer key : " +
                consumerKey, e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, prepStmt);
    }
}
 
Example #9
Source File: TokenMgtDAO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * This method is to revoke specific tokens
 *
 * @param tokens tokens that needs to be revoked
 * @throws IdentityOAuth2Exception if failed to revoke the access token
 */
public void revokeTokens(String[] tokens) throws IdentityOAuth2Exception {

    if (OAuth2Util.checkAccessTokenPartitioningEnabled() && OAuth2Util.checkUserNameAssertionEnabled()) {
        revokeTokensIndividual(tokens);
    } else {
        revokeTokensBatch(tokens);
    }
}
 
Example #10
Source File: TokenMgtDAO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public void revokeTokensIndividual(String[] tokens) throws IdentityOAuth2Exception {

        String accessTokenStoreTable = OAuthConstants.ACCESS_TOKEN_STORE_TABLE;
        Connection connection = IdentityDatabaseUtil.getDBConnection();
        PreparedStatement ps = null;
        try {
            for (String token: tokens){
                if (OAuth2Util.checkAccessTokenPartitioningEnabled() &&
                        OAuth2Util.checkUserNameAssertionEnabled()) {
                    accessTokenStoreTable = OAuth2Util.getAccessTokenStoreTableFromAccessToken(token);
                }
                String sqlQuery = SQLQueries.REVOKE_ACCESS_TOKEN.replace(
                        IDN_OAUTH2_ACCESS_TOKEN, accessTokenStoreTable);
                ps = connection.prepareStatement(sqlQuery);
                ps.setString(1, OAuthConstants.TokenStates.TOKEN_STATE_REVOKED);
                ps.setString(2, UUID.randomUUID().toString());
                ps.setString(3, persistenceProcessor.getProcessedAccessTokenIdentifier(token));
                int count = ps.executeUpdate();
                if (log.isDebugEnabled()) {
                    log.debug("Number of rows being updated : " + count);
                }
            }

            connection.commit();
        } catch (SQLException e) {
            IdentityDatabaseUtil.rollBack(connection);
            throw new IdentityOAuth2Exception("Error occurred while revoking Access Token : " + tokens.toString(), e);
        }  finally {
            IdentityDatabaseUtil.closeAllConnections(connection, null, ps);
        }
    }
 
Example #11
Source File: CellerySignedJWTValidator.java    From cellery-security with Apache License 2.0 5 votes vote down vote up
@Override
public boolean validateAccessToken(OAuth2TokenValidationMessageContext validationContext)
        throws IdentityOAuth2Exception {

    // validate mandatory attributes
    String accessToken = getAccessTokenIdentifier(validationContext);
    try {
        SignedJWT signedJWT = SignedJWT.parse(accessToken);
        boolean signedJWTValid = isSignedJWTValid(signedJWT);
        if (signedJWTValid) {
            JWTClaimsSet claimsSet = signedJWT.getJWTClaimsSet();

            // These two properties are set to avoid token lookup from the database in the case of signed JWTs
            // issued by external IDPs.
            validationContext.addProperty(OAuth2Util.REMOTE_ACCESS_TOKEN, Boolean.TRUE);
            validationContext.addProperty(OAuth2Util.JWT_ACCESS_TOKEN, Boolean.TRUE);

            validationContext.addProperty(OAuth2Util.IAT,
                    String.valueOf(getTimeInSeconds(claimsSet.getIssueTime())));
            validationContext.addProperty(OAuth2Util.EXP,
                    String.valueOf(getTimeInSeconds(claimsSet.getExpirationTime())));
            validationContext.addProperty(OAuth2Util.CLIENT_ID, claimsSet.getClaim(CONSUMER_KEY));
            validationContext.addProperty(OAuth2Util.SUB, claimsSet.getSubject());
            validationContext.addProperty(OAuth2Util.SCOPE, claimsSet.getClaim(OAuth2Util.SCOPE));
            validationContext.addProperty(OAuth2Util.ISS, claimsSet.getIssuer());
            validationContext.addProperty(OAuth2Util.JTI, claimsSet.getJWTID());
        }

        return signedJWTValid;
    } catch (ParseException e) {
        throw new IdentityOAuth2Exception("Error validating signed jwt.", e);
    }
}
 
Example #12
Source File: TokenMgtDAO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param authenticatedUser
 * @return
 * @throws IdentityOAuth2Exception
 */
public Set<String> getAuthorizationCodesForUser(AuthenticatedUser authenticatedUser) throws
        IdentityOAuth2Exception {

    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement ps = null;
    ResultSet rs = null;
    Set<String> authorizationCodes = new HashSet<>();
    boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreInUsernameCaseSensitive(authenticatedUser.toString());
    try {
        String sqlQuery = SQLQueries.GET_AUTHORIZATION_CODES_BY_AUTHZUSER;
        if (!isUsernameCaseSensitive) {
            sqlQuery = sqlQuery.replace(AUTHZ_USER, LOWER_AUTHZ_USER);
        }
        ps = connection.prepareStatement(sqlQuery);
        if (isUsernameCaseSensitive) {
            ps.setString(1, authenticatedUser.getUserName());
        } else {
            ps.setString(1, authenticatedUser.getUserName().toLowerCase());
        }
        ps.setString(2,Integer.toString(OAuth2Util.getTenantId(authenticatedUser.getTenantDomain())));
        ps.setString(3, authenticatedUser.getUserStoreDomain());
        rs = ps.executeQuery();
        while (rs.next()){
            authorizationCodes.add(rs.getString(1));
        }
        connection.commit();
    } catch (SQLException e) {
        IdentityDatabaseUtil.rollBack(connection);
        throw new IdentityOAuth2Exception("Error occurred while revoking Access Token with user Name : " +
                authenticatedUser.getUserName() + " tenant ID : " + OAuth2Util.getTenantId(authenticatedUser
                .getTenantDomain()), e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, ps);
    }
    return authorizationCodes;
}
 
Example #13
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;
}
 
Example #14
Source File: JWTTokenGenerator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private Key getPrivateKey(String tenantDomain, int tenantId) throws IdentityOAuth2Exception {

        if (tenantDomain == null) {
            tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
        }

        if (tenantId == 0) {
            tenantId = OAuth2Util.getTenantId(tenantDomain);
        }

        Key privateKey = null;

        if (!(privateKeys.containsKey(tenantId))) {
            // get tenant's key store manager
            KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId);

            if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
                // derive key store name
                String ksName = tenantDomain.trim().replace(".", "-");
                String jksName = ksName + ".jks";
                // obtain private key
                privateKey = tenantKSM.getPrivateKey(jksName, tenantDomain);

            } else {
                try {
                    privateKey = tenantKSM.getDefaultPrivateKey();
                } catch (Exception e) {
                    log.error("Error while obtaining private key for super tenant", e);
                }
            }
            if (privateKey != null) {
                privateKeys.put(tenantId, privateKey);
            }
        } else {
            privateKey = privateKeys.get(tenantId);
        }
        return privateKey;
    }
 
Example #15
Source File: TokenMgtDAO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Ths method is to revoke specific tokens
 *
 * @param tokenId token that needs to be revoked
 * @throws IdentityOAuth2Exception if failed to revoke the access token
 */
public void revokeToken(String tokenId, String userId) throws IdentityOAuth2Exception {

    String accessTokenStoreTable = OAuthConstants.ACCESS_TOKEN_STORE_TABLE;
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement ps = null;
    try {
        if (OAuth2Util.checkAccessTokenPartitioningEnabled() &&
            OAuth2Util.checkUserNameAssertionEnabled()) {
            accessTokenStoreTable = OAuth2Util.getAccessTokenStoreTableFromUserId(userId);
        }
        String sqlQuery = SQLQueries.REVOKE_ACCESS_TOKEN_BY_TOKEN_ID.replace(
                IDN_OAUTH2_ACCESS_TOKEN, accessTokenStoreTable);
        ps = connection.prepareStatement(sqlQuery);
        ps.setString(1, OAuthConstants.TokenStates.TOKEN_STATE_REVOKED);
        ps.setString(2, UUID.randomUUID().toString());
        ps.setString(3, tokenId);
        int count = ps.executeUpdate();
        if (log.isDebugEnabled()) {
            log.debug("Number of rows being updated : " + count);
        }
        connection.commit();
    } catch (SQLException e) {
        IdentityDatabaseUtil.rollBack(connection);
        throw new IdentityOAuth2Exception("Error occurred while revoking Access Token with ID : " + tokenId, e);
    }  finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, ps);
    }
}
 
Example #16
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 #17
Source File: RegistrationServiceImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Method to create a OAuth App with client credentials
 *
 * @param appName    application name
 * @param grantTypes grant types
 * @param userName   username of the application
 * @return created Oauth App
 */
private OAuthConsumerAppDTO createOAuthApp(String appName, OAuthApplicationInfo applicationInfo,
        String grantTypes, String userName) {
    OAuthConsumerAppDTO createdApp = null;
    OAuthAdminService oauthAdminService = new OAuthAdminService();
    OAuthConsumerAppDTO oauthConsumerAppDTO = new OAuthConsumerAppDTO();
    oauthConsumerAppDTO.setApplicationName(appName);
    if (StringUtils.isNotBlank(applicationInfo.getCallBackURL())) {
        oauthConsumerAppDTO.setCallbackUrl(applicationInfo.getCallBackURL());
    }
    oauthConsumerAppDTO.setUsername(userName);
    oauthConsumerAppDTO.setOAuthVersion(OAuthConstants.OAuthVersions.VERSION_2);
    oauthConsumerAppDTO.setGrantTypes(grantTypes.trim());
    try {
        boolean isHashDisabled = OAuth2Util.isHashDisabled();
        if (isHashDisabled) {
            //Creating the Oauth app
            oauthAdminService.registerOAuthApplicationData(oauthConsumerAppDTO);

            //Retrieving the created OAuth application
            createdApp = oauthAdminService.getOAuthApplicationDataByAppName
                    (oauthConsumerAppDTO.getApplicationName());
        } else {
            createdApp = oauthAdminService.registerAndRetrieveOAuthApplicationData(oauthConsumerAppDTO);
        }
    } catch (IdentityOAuthAdminException e) {
        log.error("Error occurred while creating the OAuth app", e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Created OAuth App " + appName);
    }
    return createdApp;
}
 
Example #18
Source File: SessionDataPublisherImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Method to build a AuthenticatedUser type object
 * @param authenticatedUser required param
 * @return AuthenticatedUser type object
 * @throws IdentityOAuth2Exception exception
 */
private AuthenticatedUser buildAuthenticatedUser(AuthenticatedUser authenticatedUser)
        throws IdentityOAuth2Exception {

    AuthenticatedUser user = new AuthenticatedUser();
    String tenantAwareusername = authenticatedUser.getUserName();
    String tenantDomain = authenticatedUser.getTenantDomain();
    user.setUserName(UserCoreUtil.removeDomainFromName(tenantAwareusername));
    user.setTenantDomain(tenantDomain);
    user.setUserStoreDomain(IdentityUtil.extractDomainFromName(tenantAwareusername));
    user.setFederatedUser(true);
    user.setUserStoreDomain(OAuth2Util.getUserStoreForFederatedUser(authenticatedUser));
    return user;
}
 
Example #19
Source File: OAuthCacheRemoveListener.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public void entryRemoved(CacheEntryEvent<? extends OAuthCacheKey, ? extends CacheEntry> cacheEntryEvent)
        throws CacheEntryListenerException {

    CacheEntry cacheEntry = cacheEntryEvent.getValue();
    if(cacheEntry == null || !(cacheEntry instanceof AccessTokenDO)){
        return;
    }
    AccessTokenDO accessTokenDO = (AccessTokenDO) cacheEntryEvent.getValue();

    if (accessTokenDO != null) {

        if (log.isDebugEnabled()) {
            log.debug("OAuth cache removed for consumer id : " + accessTokenDO.getConsumerKey());
        }

        boolean isUsernameCaseSensitive = IdentityUtil
                .isUserStoreInUsernameCaseSensitive(accessTokenDO.getAuthzUser().getUserName());
        String cacheKeyString;
        if (isUsernameCaseSensitive){
            cacheKeyString = accessTokenDO.getConsumerKey() + ":" + accessTokenDO.getAuthzUser().getUserName() + ":"
                    + OAuth2Util.buildScopeString(accessTokenDO.getScope());
        }else {
            cacheKeyString =
                    accessTokenDO.getConsumerKey() + ":" + accessTokenDO.getAuthzUser().getUserName().toLowerCase()
                            + ":" + OAuth2Util.buildScopeString(accessTokenDO.getScope());
        }

        OAuthCacheKey oauthcacheKey = new OAuthCacheKey(cacheKeyString);
        OAuthCache oauthCache = OAuthCache.getInstance();

        oauthCache.clearCacheEntry(oauthcacheKey);
        oauthcacheKey = new OAuthCacheKey(accessTokenDO.getAccessToken());

        oauthCache.clearCacheEntry(oauthcacheKey);

    }
}
 
Example #20
Source File: CellerySignedJWTValidator.java    From cellery-security with Apache License 2.0 5 votes vote down vote up
private void validateConsumerKey(JWTClaimsSet claimsSet) throws IdentityOAuth2Exception {

        String consumerKey = (String) claimsSet.getClaim(CONSUMER_KEY);
        if (StringUtils.isNotBlank(consumerKey)) {
            try {
                OAuth2Util.getAppInformationByClientId(consumerKey);
            } catch (IdentityOAuth2Exception | InvalidOAuthClientException e) {
                throw new IdentityOAuth2Exception("Invalid consumerKey. Cannot find a registered app for consumerKey: "
                        + consumerKey);
            }
        } else {
            throw new IdentityOAuth2Exception("Mandatory claim 'consumerKey' is missing in the signedJWT.");
        }
    }
 
Example #21
Source File: CellerySignedJWTBuilder.java    From cellery-security with Apache License 2.0 5 votes vote down vote up
private JWSHeader buildJWSHeader() throws IdentityOAuth2Exception {

        String certThumbPrint = OAuth2Util.getThumbPrint(TENANT_DOMAIN, TENANT_ID);
        headerBuilder.keyID(certThumbPrint);
        headerBuilder.x509CertThumbprint(new Base64URL(certThumbPrint));
        return headerBuilder.build();
    }
 
Example #22
Source File: CelleryExtendedKeyManagerImpl.java    From cellery-security with Apache License 2.0 5 votes vote down vote up
private void handleScopes(OAuth2IntrospectionResponseDTO responseDTO, AccessTokenInfo tokenInfo) {

        String[] scopes = OAuth2Util.buildScopeArray(responseDTO.getScope());
        String applicationTokenScope = getConfigurationElementValue(APIConstants.APPLICATION_TOKEN_SCOPE);
        if (scopes != null && applicationTokenScope != null && !applicationTokenScope.isEmpty()) {
            if (Arrays.asList(scopes).contains(applicationTokenScope)) {
                tokenInfo.setApplicationToken(true);
            }
        }
    }
 
Example #23
Source File: JWTAccessTokenBuilder.java    From msf4j with Apache License 2.0 5 votes vote down vote up
/**
 * To build id token from OauthToken request message context
 *
 * @param request Token request message context
 * @return Signed jwt string.
 * @throws IdentityOAuth2Exception
 */
protected String buildIDToken(OAuthTokenReqMessageContext request)
        throws IdentityOAuth2Exception {

    String issuer = OAuth2Util.getIDTokenIssuer();
    long lifetimeInMillis = OAuthServerConfiguration.getInstance().
            getApplicationAccessTokenValidityPeriodInSeconds() * 1000;
    long curTimeInMillis = Calendar.getInstance().getTimeInMillis();
    // setting subject
    String subject = request.getAuthorizedUser().getAuthenticatedSubjectIdentifier();
    if (!StringUtils.isNotBlank(subject)) {
        subject = request.getAuthorizedUser().getUserName();
    }
    // Set claims to jwt token.
    JWTClaimsSet jwtClaimsSet = new JWTClaimsSet();
    jwtClaimsSet.setIssuer(issuer);
    jwtClaimsSet.setSubject(subject);
    jwtClaimsSet.setAudience(Arrays.asList(request.getOauth2AccessTokenReqDTO().getClientId()));
    jwtClaimsSet.setClaim(Constants.AUTHORIZATION_PARTY, request.getOauth2AccessTokenReqDTO().getClientId());
    jwtClaimsSet.setExpirationTime(new Date(curTimeInMillis + lifetimeInMillis));
    jwtClaimsSet.setIssueTime(new Date(curTimeInMillis));
    addUserClaims(jwtClaimsSet, request.getAuthorizedUser());

    if (JWSAlgorithm.NONE.getName().equals(signatureAlgorithm.getName())) {
        return new PlainJWT(jwtClaimsSet).serialize();
    }
    return signJWT(jwtClaimsSet, request);
}
 
Example #24
Source File: JWTAccessTokenBuilder.java    From msf4j with Apache License 2.0 5 votes vote down vote up
/**
 * Build a signed jwt token from authorization request message context
 *
 * @param request Oauth authorization message context
 * @return Signed jwt string
 * @throws IdentityOAuth2Exception
 */
protected String buildIDToken(OAuthAuthzReqMessageContext request)
        throws IdentityOAuth2Exception {

    String issuer = OAuth2Util.getIDTokenIssuer();
    long lifetimeInMillis = OAuthServerConfiguration.getInstance().
            getApplicationAccessTokenValidityPeriodInSeconds() * 1000;
    long curTimeInMillis = Calendar.getInstance().getTimeInMillis();
    // setting subject
    String subject = request.getAuthorizationReqDTO().getUser().getAuthenticatedSubjectIdentifier();

    if (!StringUtils.isNotBlank(subject)) {
        subject = request.getAuthorizationReqDTO().getUser().getUserName();
    }

    JWTClaimsSet jwtClaimsSet = new JWTClaimsSet();
    jwtClaimsSet.setIssuer(issuer);
    jwtClaimsSet.setSubject(subject);
    jwtClaimsSet.setAudience(Arrays.asList(request.getAuthorizationReqDTO().getConsumerKey()));
    jwtClaimsSet.setClaim(Constants.AUTHORIZATION_PARTY, request.getAuthorizationReqDTO().getConsumerKey());
    jwtClaimsSet.setExpirationTime(new Date(curTimeInMillis + lifetimeInMillis));
    jwtClaimsSet.setIssueTime(new Date(curTimeInMillis));
    addUserClaims(jwtClaimsSet, request.getAuthorizationReqDTO().getUser());

    if (JWSAlgorithm.NONE.getName().equals(signatureAlgorithm.getName())) {
        return new PlainJWT(jwtClaimsSet).serialize();
    }
    return signJWT(jwtClaimsSet, request);
}
 
Example #25
Source File: EndpointUtil.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the login page URL.
 *
 * @param checkAuthentication
 * @param forceAuthenticate
 * @param scopes
 * @return
 */
public static String getLoginPageURL(String clientId, String sessionDataKey,
                                     boolean forceAuthenticate, boolean checkAuthentication, Set<String> scopes)
        throws IdentityOAuth2Exception {

    try {
        SessionDataCacheEntry entry = SessionDataCache.getInstance()
                .getValueFromCache(new SessionDataCacheKey(sessionDataKey));

        return getLoginPageURL(clientId, sessionDataKey, forceAuthenticate,
                checkAuthentication, scopes, entry.getParamMap());
    } finally {
        OAuth2Util.clearClientTenantId();
    }
}
 
Example #26
Source File: OAuth2Service.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Process the authorization request and issue an authorization code or access token depending
 * on the Response Type available in the request.
 *
 * @param oAuth2AuthorizeReqDTO <code>OAuth2AuthorizeReqDTO</code> containing information about the authorization
 *                              request.
 * @return <code>OAuth2AuthorizeRespDTO</code> instance containing the access token/authorization code
 * or an error code.
 */
public OAuth2AuthorizeRespDTO authorize(OAuth2AuthorizeReqDTO oAuth2AuthorizeReqDTO) {

    if (log.isDebugEnabled()) {
        log.debug("Authorization Request received for user : " + oAuth2AuthorizeReqDTO.getUser() +
                ", Client ID : " + oAuth2AuthorizeReqDTO.getConsumerKey() +
                ", Authorization Response Type : " + oAuth2AuthorizeReqDTO.getResponseType() +
                ", Requested callback URI : " + oAuth2AuthorizeReqDTO.getCallbackUrl() +
                ", Requested Scope : " + OAuth2Util.buildScopeString(
                oAuth2AuthorizeReqDTO.getScopes()));
    }

    try {
        AuthorizationHandlerManager authzHandlerManager =
                AuthorizationHandlerManager.getInstance();
        return authzHandlerManager.handleAuthorization(oAuth2AuthorizeReqDTO);
    } catch (Exception e) {
        log.error("Error occurred when processing the authorization request. Returning an error back to client.",
                e);
        OAuth2AuthorizeRespDTO authorizeRespDTO = new OAuth2AuthorizeRespDTO();
        authorizeRespDTO.setErrorCode(OAuth2ErrorCodes.SERVER_ERROR);
        authorizeRespDTO.setErrorMsg("Error occurred when processing the authorization " +
                "request. Returning an error back to client.");
        authorizeRespDTO.setCallbackURI(oAuth2AuthorizeReqDTO.getCallbackUrl());
        return authorizeRespDTO;
    }
}
 
Example #27
Source File: CodeResponseTypeHandler.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public OAuth2AuthorizeRespDTO issue(OAuthAuthzReqMessageContext oauthAuthzMsgCtx)
        throws IdentityOAuth2Exception {
    OAuth2AuthorizeRespDTO respDTO = new OAuth2AuthorizeRespDTO();
    String authorizationCode;
    String codeId;

    OAuth2AuthorizeReqDTO authorizationReqDTO = oauthAuthzMsgCtx.getAuthorizationReqDTO();

    Timestamp timestamp = new Timestamp(new Date().getTime());

    long validityPeriod = OAuthServerConfiguration.getInstance()
            .getAuthorizationCodeValidityPeriodInSeconds();

    // if a VALID callback is set through the callback handler, use
    // it instead of the default one
    long callbackValidityPeriod = oauthAuthzMsgCtx.getValidityPeriod();

    if ((callbackValidityPeriod != OAuthConstants.UNASSIGNED_VALIDITY_PERIOD)
            && callbackValidityPeriod > 0) {
        validityPeriod = callbackValidityPeriod;
    }
    // convert to milliseconds
    validityPeriod = validityPeriod * 1000;
    
    // set the validity period. this is needed by downstream handlers.
    // if this is set before - then this will override it by the calculated new value.
    oauthAuthzMsgCtx.setValidityPeriod(validityPeriod);

    // set code issued time.this is needed by downstream handlers.
    oauthAuthzMsgCtx.setCodeIssuedTime(timestamp.getTime());
    
    try {
        authorizationCode = oauthIssuerImpl.authorizationCode();
        codeId = UUID.randomUUID().toString();
    } catch (OAuthSystemException e) {
        throw new IdentityOAuth2Exception(e.getMessage(), e);
    }

    AuthzCodeDO authzCodeDO = new AuthzCodeDO(authorizationReqDTO.getUser(),
            oauthAuthzMsgCtx.getApprovedScope(),timestamp, validityPeriod, authorizationReqDTO.getCallbackUrl(),
            authorizationReqDTO.getConsumerKey(), authorizationCode, codeId);

    tokenMgtDAO.storeAuthorizationCode(authorizationCode, authorizationReqDTO.getConsumerKey(),
            authorizationReqDTO.getCallbackUrl(), authzCodeDO);

    if (cacheEnabled) {
        // Cache the authz Code, here we prepend the client_key to avoid collisions with
        // AccessTokenDO instances. In database level, these are in two databases. But access
        // tokens and authorization codes are in a single cache.
        String cacheKeyString = OAuth2Util.buildCacheKeyStringForAuthzCode(
                authorizationReqDTO.getConsumerKey(), authorizationCode);
        oauthCache.addToCache(new OAuthCacheKey(cacheKeyString), authzCodeDO);
        if (log.isDebugEnabled()) {
            log.debug("Authorization Code info was added to the cache for client id : " +
                    authorizationReqDTO.getConsumerKey());
        }
    }

    if (log.isDebugEnabled()) {
        log.debug("Issued Authorization Code to user : " + authorizationReqDTO.getUser() +
                ", Using the redirect url : " + authorizationReqDTO.getCallbackUrl() +
                ", Scope : " + OAuth2Util.buildScopeString(oauthAuthzMsgCtx.getApprovedScope()) +
                ", validity period : " + validityPeriod);
    }

    respDTO.setCallbackURI(authorizationReqDTO.getCallbackUrl());
    respDTO.setAuthorizationCode(authorizationCode);
    respDTO.setCodeId(codeId);
    return respDTO;
}
 
Example #28
Source File: DefaultIDTokenBuilder.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public String buildIDToken(OAuthAuthzReqMessageContext request, OAuth2AuthorizeRespDTO tokenRespDTO)
        throws IdentityOAuth2Exception {

    String issuer = OAuth2Util.getIDTokenIssuer();
    long lifetimeInMillis = Integer.parseInt(config.getOpenIDConnectIDTokenExpiration()) * 1000;
    long curTimeInMillis = Calendar.getInstance().getTimeInMillis();
    // setting subject
    String subject = request.getAuthorizationReqDTO().getUser().getAuthenticatedSubjectIdentifier();

    String nonceValue = request.getAuthorizationReqDTO().getNonce();

    // Get access token issued time
    long accessTokenIssuedTime = getAccessTokenIssuedTime(tokenRespDTO.getAccessToken(), request) / 1000;

    String atHash = null;
    String responseType = request.getAuthorizationReqDTO().getResponseType();
    //at_hash is generated on access token. Hence the check on response type to be id_token token or code
    if (!JWSAlgorithm.NONE.getName().equals(signatureAlgorithm.getName()) &&
            !OAuthConstants.ID_TOKEN.equalsIgnoreCase(responseType) &&
            !OAuthConstants.NONE.equalsIgnoreCase(responseType)) {
        String digAlg = mapDigestAlgorithm(signatureAlgorithm);
        MessageDigest md;
        try {
            md = MessageDigest.getInstance(digAlg);
        } catch (NoSuchAlgorithmException e) {
            throw new IdentityOAuth2Exception("Invalid Algorithm : " + digAlg);
        }
        md.update(tokenRespDTO.getAccessToken().getBytes(Charsets.UTF_8));
        byte[] digest = md.digest();
        int leftHalfBytes = 16;
        if (SHA384.equals(digAlg)) {
            leftHalfBytes = 24;
        } else if (SHA512.equals(digAlg)) {
            leftHalfBytes = 32;
        }
        byte[] leftmost = new byte[leftHalfBytes];
        for (int i = 0; i < leftHalfBytes; i++) {
            leftmost[i] = digest[i];
        }
        atHash = new String(Base64.encodeBase64URLSafe(leftmost), Charsets.UTF_8);
    }


    if (log.isDebugEnabled()) {
        StringBuilder stringBuilder = (new StringBuilder())
                .append("Using issuer ").append(issuer).append("\n")
                .append("Subject ").append(subject).append("\n")
                .append("ID Token life time ").append(lifetimeInMillis / 1000).append("\n")
                .append("Current time ").append(curTimeInMillis / 1000).append("\n")
                .append("Nonce Value ").append(nonceValue).append("\n")
                .append("Signature Algorithm ").append(signatureAlgorithm).append("\n");
        if (log.isDebugEnabled()) {
            log.debug(stringBuilder.toString());
        }
    }

    JWTClaimsSet jwtClaimsSet = new JWTClaimsSet();
    jwtClaimsSet.setIssuer(issuer);
    jwtClaimsSet.setSubject(subject);
    jwtClaimsSet.setAudience(Arrays.asList(request.getAuthorizationReqDTO().getConsumerKey()));
    jwtClaimsSet.setClaim("azp", request.getAuthorizationReqDTO().getConsumerKey());
    jwtClaimsSet.setExpirationTime(new Date(curTimeInMillis + lifetimeInMillis));
    jwtClaimsSet.setIssueTime(new Date(curTimeInMillis));
    jwtClaimsSet.setClaim("auth_time", accessTokenIssuedTime);
    if(atHash != null){
        jwtClaimsSet.setClaim("at_hash", atHash);
    }
    if (nonceValue != null) {
        jwtClaimsSet.setClaim("nonce", nonceValue);
    }

    request.addProperty(OAuthConstants.ACCESS_TOKEN, tokenRespDTO.getAccessToken());
    CustomClaimsCallbackHandler claimsCallBackHandler =
            OAuthServerConfiguration.getInstance().getOpenIDConnectCustomClaimsCallbackHandler();
    claimsCallBackHandler.handleCustomClaims(jwtClaimsSet, request);
    if (JWSAlgorithm.NONE.getName().equals(signatureAlgorithm.getName())) {
        return new PlainJWT(jwtClaimsSet).serialize();
    }
    return signJWT(jwtClaimsSet, request);
}
 
Example #29
Source File: OAuthUserStoreConfigListenerImpl.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public void onUserStorePreDelete(int tenantId, String userStoreName) throws UserStoreException {
    TokenMgtDAO tokenMgtDAO = new TokenMgtDAO();
    try {
        Set<AccessTokenDO> accessTokenDOs = tokenMgtDAO.getAccessTokensOfUserStore(tenantId, userStoreName);
        Map<String, AccessTokenDO> latestAccessTokens = new HashMap<>();
        for (AccessTokenDO accessTokenDO : accessTokenDOs) {
            String keyString = accessTokenDO.getConsumerKey() + ":" + accessTokenDO.getAuthzUser() + ":" +
                    OAuth2Util.buildScopeString(accessTokenDO.getScope());
            AccessTokenDO accessTokenDOFromMap = latestAccessTokens.get(keyString);
            if (accessTokenDOFromMap != null) {
                if (accessTokenDOFromMap.getIssuedTime().before(accessTokenDO.getIssuedTime())) {
                    latestAccessTokens.put(keyString, accessTokenDO);
                }
            } else {
                latestAccessTokens.put(keyString, accessTokenDO);
            }

            //Clear cache
            OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), accessTokenDO.getAuthzUser(),
                    OAuth2Util.buildScopeString(accessTokenDO.getScope()));
            OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), accessTokenDO.getAuthzUser());
            OAuthUtil.clearOAuthCache(accessTokenDO.getAccessToken());
        }
        ArrayList<String> tokensToRevoke = new ArrayList<>();
        for (Map.Entry entry : latestAccessTokens.entrySet()) {
            tokensToRevoke.add(((AccessTokenDO) entry.getValue()).getAccessToken());
        }
        tokenMgtDAO.revokeTokens(tokensToRevoke.toArray(new String[tokensToRevoke.size()]));
        List<AuthzCodeDO> latestAuthzCodes = tokenMgtDAO.getLatestAuthorizationCodesOfUserStore(tenantId,
                userStoreName);
        for (AuthzCodeDO authzCodeDO : latestAuthzCodes) {
            // remove the authorization code from the cache
            OAuthUtil.clearOAuthCache(authzCodeDO.getConsumerKey() + ":" + authzCodeDO.getAuthorizationCode());

        }
        tokenMgtDAO.deactivateAuthorizationCode(latestAuthzCodes);
    } catch (IdentityOAuth2Exception e) {
        throw new UserStoreException("Error occurred while revoking Access Token of user store : " +
                userStoreName + " in tenant :" + tenantId, e);
    }
}
 
Example #30
Source File: CellerySignedJWTBuilder.java    From cellery-security with Apache License 2.0 4 votes vote down vote up
private RSAPrivateKey getRSASigningKey() throws IdentityOAuth2Exception {

        Key privateKey = OAuth2Util.getPrivateKey(TENANT_DOMAIN, TENANT_ID);
        return (RSAPrivateKey) privateKey;
    }