Search in sources :

Example 11 with AuthenticatedUser

use of org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser in project carbon-apimgt by wso2.

the class SessionDataPublisherImpl method publishSessionTermination.

/**
 * Overridden method which implements the access token revocation
 * @param request termination request
 * @param context termination context
 * @param sessionContext termination sessionContext
 * @param params termination params
 */
@Override
public void publishSessionTermination(HttpServletRequest request, AuthenticationContext context, SessionContext sessionContext, Map<String, Object> params) {
    OAuthConsumerAppDTO[] appDTOs = new OAuthConsumerAppDTO[0];
    List<OAuthConsumerAppDTO> revokeAppList = new ArrayList<>();
    AuthenticatedUser authenticatedUser = (AuthenticatedUser) params.get(user);
    String username = authenticatedUser.getUserName();
    String tenantDomain = authenticatedUser.getTenantDomain();
    String userStoreDomain = authenticatedUser.getUserStoreDomain();
    AuthenticatedUser federatedUser;
    SystemApplicationDTO[] systemApplicationDTOS = new SystemApplicationDTO[0];
    if (authenticatedUser.isFederatedUser()) {
        try {
            federatedUser = buildAuthenticatedUser(authenticatedUser);
            authenticatedUser = federatedUser;
        } catch (IdentityOAuth2Exception e) {
            log.error("Error thrown while building authenticated user in logout flow for user " + authenticatedUser.getUserName(), e);
        }
    }
    SystemApplicationDAO systemApplicationDAO = new SystemApplicationDAO();
    try {
        systemApplicationDTOS = systemApplicationDAO.getApplications(tenantDomain);
        if (systemApplicationDTOS.length < 0) {
            if (log.isDebugEnabled()) {
                log.debug("The tenant: " + tenantDomain + " doesn't have any system apps");
            }
        }
    } catch (APIMgtDAOException e) {
        log.error("Error thrown while retrieving system applications for the tenant domain " + tenantDomain, e);
    }
    try {
        appDTOs = getAppsAuthorizedByUser(authenticatedUser);
        if (appDTOs.length > 0) {
            if (log.isDebugEnabled()) {
                log.debug("The user: " + authenticatedUser.getUserName() + " has " + appDTOs.length + " OAuth apps");
            }
        }
    } catch (IdentityOAuthAdminException e) {
        log.error("Error while retrieving applications authorized for the user " + authenticatedUser.getUserName(), e);
    }
    for (OAuthConsumerAppDTO appDTO : appDTOs) {
        for (SystemApplicationDTO systemApplicationDTO : systemApplicationDTOS) {
            if (StringUtils.equalsIgnoreCase(appDTO.getOauthConsumerKey(), systemApplicationDTO.getConsumerKey())) {
                revokeAppList.add(appDTO);
            }
        }
    }
    for (OAuthConsumerAppDTO appDTO : revokeAppList) {
        Set<AccessTokenDO> accessTokenDOs = null;
        try {
            // Retrieve all ACTIVE or EXPIRED access tokens for particular client authorized by this user
            accessTokenDOs = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().getAccessTokens(appDTO.getOauthConsumerKey(), authenticatedUser, authenticatedUser.getUserStoreDomain(), true);
        } catch (IdentityOAuth2Exception e) {
            log.error("Error while retrieving access tokens for the application " + appDTO.getApplicationName() + "and the for user " + authenticatedUser.getUserName(), e);
        }
        AuthenticatedUser authzUser;
        if (accessTokenDOs != null) {
            for (AccessTokenDO accessTokenDO : accessTokenDOs) {
                // Clear cache with AccessTokenDO
                authzUser = accessTokenDO.getAuthzUser();
                OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), authzUser, OAuth2Util.buildScopeString(accessTokenDO.getScope()), "NONE");
                OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), authzUser, OAuth2Util.buildScopeString(accessTokenDO.getScope()));
                OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), authzUser);
                OAuthUtil.clearOAuthCache(accessTokenDO.getAccessToken());
                Cache restApiTokenCache = CacheProvider.getRESTAPITokenCache();
                if (restApiTokenCache != null) {
                    restApiTokenCache.remove(accessTokenDO.getAccessToken());
                }
                AccessTokenDO scopedToken = null;
                try {
                    // Retrieve latest access token for particular client, user and scope combination if
                    // its ACTIVE or EXPIRED.
                    scopedToken = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().getLatestAccessToken(appDTO.getOauthConsumerKey(), authenticatedUser, userStoreDomain, OAuth2Util.buildScopeString(accessTokenDO.getScope()), true);
                } catch (IdentityOAuth2Exception e) {
                    log.error("Error while retrieving scoped access tokens for the application " + appDTO.getApplicationName() + "and the for user " + authenticatedUser.getUserName(), e);
                }
                if (scopedToken != null) {
                    // Revoking token from database
                    try {
                        OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().revokeAccessTokens(new String[] { scopedToken.getAccessToken() });
                    } catch (IdentityOAuth2Exception e) {
                        log.error("Error while revoking access tokens related for the application " + appDTO.getApplicationName() + "and the for user " + authenticatedUser.getUserName(), e);
                    }
                    // Revoking the oauth consent from database.
                    try {
                        OAuthTokenPersistenceFactory.getInstance().getTokenManagementDAO().revokeOAuthConsentByApplicationAndUser(authzUser.getAuthenticatedSubjectIdentifier(), tenantDomain, username);
                    } catch (IdentityOAuth2Exception e) {
                        log.error("Error while revoking access tokens related for the application " + appDTO.getApplicationName() + "and the for user " + authenticatedUser.getUserName(), e);
                    }
                }
            }
        }
    }
}
Also used : IdentityOAuthAdminException(org.wso2.carbon.identity.oauth.IdentityOAuthAdminException) APIMgtDAOException(org.wso2.carbon.apimgt.api.APIMgtDAOException) OAuthConsumerAppDTO(org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) SystemApplicationDTO(org.wso2.carbon.apimgt.impl.dto.SystemApplicationDTO) SystemApplicationDAO(org.wso2.carbon.apimgt.impl.dao.SystemApplicationDAO) Cache(javax.cache.Cache)

Example 12 with AuthenticatedUser

use of org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser in project carbon-apimgt by wso2.

the class SessionDataPublisherImpl method getAppsAuthorizedByUser.

/**
 * Method to retrieve applications authorized for user
 * @param authenticatedUser authenticated user info
 * @return array of authorized applications
 * @throws IdentityOAuthAdminException exception
 */
private OAuthConsumerAppDTO[] getAppsAuthorizedByUser(AuthenticatedUser authenticatedUser) throws IdentityOAuthAdminException {
    OAuthAppDAO appDAO = new OAuthAppDAO();
    String tenantAwareusername = authenticatedUser.getUserName();
    String tenantDomain = authenticatedUser.getTenantDomain();
    String username = UserCoreUtil.addTenantDomainToEntry(tenantAwareusername, tenantDomain);
    String userStoreDomain = authenticatedUser.getUserStoreDomain();
    Set<String> clientIds;
    SystemApplicationDTO[] systemApplicationDTOS;
    SystemApplicationDAO systemApplicationDAO = new SystemApplicationDAO();
    Set<String> systemAppClientIds = new HashSet<>();
    try {
        systemApplicationDTOS = systemApplicationDAO.getApplications(tenantDomain);
        if (systemApplicationDTOS.length < 0) {
            if (log.isDebugEnabled()) {
                log.debug("The tenant: " + tenantDomain + " doesn't have any system apps");
            }
        } else {
            for (SystemApplicationDTO applicationDTO : systemApplicationDTOS) {
                try {
                    if (ApplicationMgtUtil.isUserAuthorized(applicationDTO.getName(), tenantAwareusername)) {
                        systemAppClientIds.add(applicationDTO.getConsumerKey());
                    }
                } catch (IdentityApplicationManagementException e) {
                    log.error("Error occurred while checking the authorization of the application " + applicationDTO.getName(), e);
                }
            }
        }
    } catch (APIMgtDAOException e) {
        log.error("Error thrown while retrieving system applications for the tenant domain " + tenantDomain, e);
    }
    clientIds = systemAppClientIds;
    Set<OAuthConsumerAppDTO> appDTOs = new HashSet<>();
    for (String clientId : clientIds) {
        Set<AccessTokenDO> accessTokenDOs;
        try {
            accessTokenDOs = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().getAccessTokens(clientId, authenticatedUser, userStoreDomain, true);
        } catch (IdentityOAuth2Exception e) {
            throw handleError("Error occurred while retrieving access tokens issued for " + "Client ID : " + clientId + ", User ID : " + username, e);
        }
        if (!accessTokenDOs.isEmpty()) {
            Set<String> distinctClientUserScopeCombo = new HashSet<>();
            for (AccessTokenDO accessTokenDO : accessTokenDOs) {
                AccessTokenDO scopedToken;
                String scopeString = OAuth2Util.buildScopeString(accessTokenDO.getScope());
                try {
                    scopedToken = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().getLatestAccessToken(clientId, authenticatedUser, userStoreDomain, scopeString, true);
                    if (scopedToken != null && !distinctClientUserScopeCombo.contains(clientId + ":" + username)) {
                        OAuthAppDO appDO;
                        try {
                            appDO = appDAO.getAppInformation(scopedToken.getConsumerKey());
                            appDTOs.add(buildConsumerAppDTO(appDO));
                            if (log.isDebugEnabled()) {
                                log.debug("Found App: " + appDO.getApplicationName() + " for user: " + username);
                            }
                        } catch (InvalidOAuthClientException e) {
                            String errorMsg = "Invalid Client ID : " + scopedToken.getConsumerKey();
                            log.error(errorMsg, e);
                            throw new IdentityOAuthAdminException(errorMsg);
                        } catch (IdentityOAuth2Exception e) {
                            String errorMsg = "Error occurred while retrieving app information " + "for Client ID : " + scopedToken.getConsumerKey();
                            log.error(errorMsg, e);
                            throw new IdentityOAuthAdminException(errorMsg);
                        }
                        distinctClientUserScopeCombo.add(clientId + ":" + username);
                    }
                } catch (IdentityOAuth2Exception e) {
                    String errorMsg = "Error occurred while retrieving latest access token issued for Client ID :" + " " + clientId + ", User ID : " + username + " and Scope : " + scopeString;
                    throw handleError(errorMsg, e);
                }
            }
        }
    }
    return appDTOs.toArray(new OAuthConsumerAppDTO[0]);
}
Also used : IdentityOAuthAdminException(org.wso2.carbon.identity.oauth.IdentityOAuthAdminException) APIMgtDAOException(org.wso2.carbon.apimgt.api.APIMgtDAOException) IdentityApplicationManagementException(org.wso2.carbon.identity.application.common.IdentityApplicationManagementException) OAuthConsumerAppDTO(org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO) AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) OAuthAppDAO(org.wso2.carbon.identity.oauth.dao.OAuthAppDAO) OAuthAppDO(org.wso2.carbon.identity.oauth.dao.OAuthAppDO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) SystemApplicationDTO(org.wso2.carbon.apimgt.impl.dto.SystemApplicationDTO) SystemApplicationDAO(org.wso2.carbon.apimgt.impl.dao.SystemApplicationDAO) InvalidOAuthClientException(org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException)

Example 13 with AuthenticatedUser

use of org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser in project carbon-apimgt by wso2.

the class SessionDataPublisherImpl method buildAuthenticatedUser.

/**
 * 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));
    user.setFederatedIdPName(authenticatedUser.getFederatedIdPName());
    return user;
}
Also used : AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)

Example 14 with AuthenticatedUser

use of org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser in project identity-outbound-auth-sms-otp by wso2-extensions.

the class SMSOTPAuthenticator method checkWithBackUpCodes.

/**
 * If user forgets the mobile, then user can use the back up codes to authenticate the user.
 *
 * @param context           the AuthenticationContext
 * @param userToken         the userToken
 * @param authenticatedUser the name of authenticatedUser
 * @throws AuthenticationFailedException
 */
private void checkWithBackUpCodes(AuthenticationContext context, String userToken, AuthenticatedUser authenticatedUser) throws AuthenticationFailedException {
    String savedOTPString = null;
    String username = context.getProperty(SMSOTPConstants.USER_NAME).toString();
    String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(username);
    UserRealm userRealm = getUserRealm(username);
    try {
        if (userRealm != null) {
            savedOTPString = userRealm.getUserStoreManager().getUserClaimValue(tenantAwareUsername, SMSOTPConstants.SAVED_OTP_LIST, null);
        }
        if (StringUtils.isEmpty(savedOTPString)) {
            if (log.isDebugEnabled()) {
                log.debug("The claim " + SMSOTPConstants.SAVED_OTP_LIST + " does not contain any values");
            }
            throw new AuthenticationFailedException("The claim " + SMSOTPConstants.SAVED_OTP_LIST + " does not contain any values");
        } else if (savedOTPString.contains(userToken)) {
            if (log.isDebugEnabled()) {
                log.debug("Found saved backup SMS OTP for user :" + authenticatedUser);
            }
            context.setSubject(authenticatedUser);
            savedOTPString = savedOTPString.replaceAll(userToken, "").replaceAll(",,", ",");
            userRealm.getUserStoreManager().setUserClaimValue(tenantAwareUsername, SMSOTPConstants.SAVED_OTP_LIST, savedOTPString, null);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("User entered OTP :" + userToken + " does not match with any of the saved backup codes");
            }
            throw new AuthenticationFailedException("Verification Error due to Code " + userToken + " mismatch.");
        }
    } catch (UserStoreException e) {
        throw new AuthenticationFailedException("Cannot find the user claim for OTP list for user : " + authenticatedUser, e);
    }
}
Also used : UserRealm(org.wso2.carbon.user.api.UserRealm) AuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException) UserStoreException(org.wso2.carbon.user.api.UserStoreException)

Example 15 with AuthenticatedUser

use of org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser in project identity-outbound-auth-sms-otp by wso2-extensions.

the class SMSOTPAuthenticator method processAuthenticationResponse.

/**
 * Process the response of the SMSOTP end-point.
 *
 * @param request  the HttpServletRequest
 * @param response the HttpServletResponse
 * @param context  the AuthenticationContext
 * @throws AuthenticationFailedException
 */
@Override
protected void processAuthenticationResponse(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws AuthenticationFailedException {
    String userToken = request.getParameter(SMSOTPConstants.CODE);
    String contextToken = (String) context.getProperty(SMSOTPConstants.OTP_TOKEN);
    AuthenticatedUser authenticatedUser = (AuthenticatedUser) context.getProperty(SMSOTPConstants.AUTHENTICATED_USER);
    if (StringUtils.isEmpty(request.getParameter(SMSOTPConstants.CODE))) {
        throw new InvalidCredentialsException("Code cannot not be null");
    }
    if (Boolean.parseBoolean(request.getParameter(SMSOTPConstants.RESEND))) {
        if (log.isDebugEnabled()) {
            log.debug("Retrying to resend the OTP");
        }
        throw new InvalidCredentialsException("Retrying to resend the OTP");
    }
    if (userToken.equals(contextToken)) {
        context.setSubject(authenticatedUser);
    } else if (SMSOTPUtils.getBackupCode(context, getName()).equals("true")) {
        checkWithBackUpCodes(context, userToken, authenticatedUser);
    } else {
        context.setProperty(SMSOTPConstants.CODE_MISMATCH, true);
        throw new AuthenticationFailedException("Code mismatch");
    }
}
Also used : InvalidCredentialsException(org.wso2.carbon.identity.application.authentication.framework.exception.InvalidCredentialsException) AuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)

Aggregations

AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)14 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)4 Test (org.testng.annotations.Test)4 AuthenticationFailedException (org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException)3 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)3 AccessTokenDO (org.wso2.carbon.identity.oauth2.model.AccessTokenDO)3 UserStoreException (org.wso2.carbon.user.api.UserStoreException)3 APIMgtDAOException (org.wso2.carbon.apimgt.api.APIMgtDAOException)2 SystemApplicationDAO (org.wso2.carbon.apimgt.impl.dao.SystemApplicationDAO)2 SystemApplicationDTO (org.wso2.carbon.apimgt.impl.dto.SystemApplicationDTO)2 AuthenticatorFlowStatus (org.wso2.carbon.identity.application.authentication.framework.AuthenticatorFlowStatus)2 IdentityOAuthAdminException (org.wso2.carbon.identity.oauth.IdentityOAuthAdminException)2 OAuthConsumerAppDTO (org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO)2 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)1 SignedJWT (com.nimbusds.jwt.SignedJWT)1 ParseException (java.text.ParseException)1 Cache (javax.cache.Cache)1 Before (org.junit.Before)1 Matchers.anyString (org.mockito.Matchers.anyString)1 Assertion (org.opensaml.saml.saml2.core.Assertion)1