Java Code Examples for org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser#getTenantDomain()

The following examples show how to use org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser#getTenantDomain() . 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: SSOConsentServiceImpl.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Process the provided user consent and creates a consent receipt.
 *
 * @param consentApprovedClaimIds Consent approved claims by the user.
 * @param serviceProvider         Service provider receiving consent.
 * @param authenticatedUser       Authenticated user providing consent.
 * @param consentClaimsData       Claims which the consent requested for.
 * @throws SSOConsentServiceException If error occurs while processing user consent.
 */
@Override
public void processConsent(List<Integer> consentApprovedClaimIds, ServiceProvider serviceProvider,
                           AuthenticatedUser authenticatedUser, ConsentClaimsData consentClaimsData)
        throws SSOConsentServiceException {

    if (!isSSOConsentManagementEnabled(serviceProvider)) {
        String message = "Consent management for SSO is disabled.";
        throw new SSOConsentDisabledException(message, message);
    }
    if (isDebugEnabled()) {
        logDebug("User: " + authenticatedUser.getAuthenticatedSubjectIdentifier() + " has approved consent.");
    }
    UserConsent userConsent = processUserConsent(consentApprovedClaimIds, consentClaimsData);
    String subject = buildSubjectWithUserStoreDomain(authenticatedUser);
    List<ClaimMetaData> claimsWithConsent = getAllUserApprovedClaims(serviceProvider, authenticatedUser,
            userConsent);
    String spTenantDomain = getSPTenantDomain(serviceProvider);
    String subjectTenantDomain = authenticatedUser.getTenantDomain();

    if (isNotEmpty(claimsWithConsent)) {
        addReceipt(subject, subjectTenantDomain, serviceProvider, spTenantDomain, claimsWithConsent);
    }
}
 
Example 2
Source File: FIDOAuthenticator.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
@Override
protected void processAuthenticationResponse(HttpServletRequest request,
                                             HttpServletResponse response,
                                             AuthenticationContext context)
        throws AuthenticationFailedException {

    String tokenResponse = request.getParameter("tokenResponse");
    if (tokenResponse != null && !tokenResponse.contains("errorCode")) {
        String appID = FIDOUtil.getOrigin(request);
        AuthenticatedUser user = getUsername(context);

        U2FService u2FService = U2FService.getInstance();
        FIDOUser fidoUser = new FIDOUser(user.getUserName(), user.getTenantDomain(),
                                         user.getUserStoreDomain(), AuthenticateResponse.fromJson(tokenResponse));
        fidoUser.setAppID(appID);
        u2FService.finishAuthentication(fidoUser);
        context.setSubject(user);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("FIDO authentication filed : " + tokenResponse);
        }

        throw new InvalidCredentialsException("FIDO device authentication failed ");
    }

}
 
Example 3
Source File: AbstractScopesIssuer.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * This method is used to get the application scopes including the scopes defined for the APIs subscribed to the
 * application and the API-M REST API scopes set of the current tenant.
 *
 * @param consumerKey       Consumer Key of the application
 * @param authenticatedUser Authenticated User
 * @return Application Scope List
 */
public Map<String, String> getAppScopes(String consumerKey, AuthenticatedUser authenticatedUser) {

    //Get all the scopes and roles against the scopes defined for the APIs subscribed to the application.
    Map<String, String> appScopes = null;
    String tenantDomain;
    if (authenticatedUser.isFederatedUser()) {
        tenantDomain = MultitenantUtils.getTenantDomain(authenticatedUser.getAuthenticatedSubjectIdentifier());
    } else {
        tenantDomain = authenticatedUser.getTenantDomain();
    }
    try {
        appScopes = getApiMgtDAOInstance().getScopeRolesOfApplication(consumerKey);
        //Add API Manager rest API scopes set. This list should be loaded at server start up and keep
        //in memory and add it to each and every request coming.
        appScopes.putAll(APIUtil.getRESTAPIScopesForTenant(tenantDomain));
    } catch (APIManagementException e) {
        log.error("Error while getting scopes of application " + e.getMessage(), e);
    }
    return appScopes;
}
 
Example 4
Source File: DefaultClaimHandler.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private Map<String, String> retrieveAllNunNullUserClaimValues(AuthenticatedUser authenticatedUser,
        ClaimManager claimManager, ApplicationConfig appConfig,
        org.wso2.carbon.user.core.UserStoreManager userStore) throws FrameworkException {

    String tenantDomain = authenticatedUser.getTenantDomain();
    String tenantAwareUserName = authenticatedUser.getUserName();

    Map<String, String> allLocalClaims = new HashMap<>();
    try {

        org.wso2.carbon.user.api.ClaimMapping[] claimMappings = claimManager
                .getAllClaimMappings(ApplicationConstants.LOCAL_IDP_DEFAULT_CLAIM_DIALECT);
        List<String> localClaimURIs = new ArrayList<>();
        for (org.wso2.carbon.user.api.ClaimMapping mapping : claimMappings) {
            String claimURI = mapping.getClaim().getClaimUri();
            localClaimURIs.add(claimURI);
        }
        allLocalClaims = userStore.getUserClaimValues(tenantAwareUserName,
                localClaimURIs.toArray(new String[localClaimURIs.size()]), null);

        if (allLocalClaims == null) {
            return new HashMap<>();
        }
    } catch (UserStoreException e) {
        if (e.getMessage().contains("UserNotFound")) {
            if (log.isDebugEnabled()) {
                log.debug("User " + tenantAwareUserName + " not found in user store");
            }
        } else {
            throw new FrameworkException("Error occurred while getting all user claims for " +
                    authenticatedUser + " in " + tenantDomain, e);
        }
    }
    return allLocalClaims;
}
 
Example 5
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 6
Source File: RoleBasedScopesIssuer.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * This method is used to get roles list of the user.
 *
 * @param authenticatedUser Authenticated user
 * @return roles list
 */
private String[] getUserRoles(AuthenticatedUser authenticatedUser) {

    String[] userRoles = null;
    String tenantDomain;
    String username;
    if (authenticatedUser.isFederatedUser()) {
        tenantDomain = MultitenantUtils.getTenantDomain(authenticatedUser.getAuthenticatedSubjectIdentifier());
        username = MultitenantUtils.getTenantAwareUsername(authenticatedUser.getAuthenticatedSubjectIdentifier());
    } else {
        tenantDomain = authenticatedUser.getTenantDomain();
        username = authenticatedUser.getUserName();
    }
    String userStoreDomain = authenticatedUser.getUserStoreDomain();
    RealmService realmService = getRealmService();
    try {
        int tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
        // If tenant Id is not set in the tokenReqContext, deriving it from username.
        if (tenantId == 0 || tenantId == -1) {
            tenantId = getTenantIdOfUser(username);
        }
        UserStoreManager userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager();
        String endUsernameWithDomain = addDomainToName(username, userStoreDomain);
        userRoles = userStoreManager.getRoleListOfUser(endUsernameWithDomain);

    } catch (UserStoreException e) {
        //Log and return since we do not want to stop issuing the token in case of scope validation failures.
        log.error("Error when getting the tenant's UserStoreManager or when getting roles of user ", e);
    }
    return userRoles;
}
 
Example 7
Source File: FIDOAuthenticator.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
protected void initiateAuthenticationRequest(HttpServletRequest request,
                                             HttpServletResponse response,
                                             AuthenticationContext context)
        throws AuthenticationFailedException {
    //FIDO BE service component
    U2FService u2FService = U2FService.getInstance();
    try {
        //authentication page's URL.
        String loginPage;
        loginPage = context.getAuthenticatorProperties().get(IdentityApplicationConstants.Authenticator.FIDO
                .FIDO_AUTH);
        if (StringUtils.isBlank(loginPage)){
            loginPage = ConfigurationFacade.getInstance().getAuthenticationEndpointURL().replace("login.do",
                    "fido-auth.jsp");
        }
        //username from basic authenticator.
        AuthenticatedUser user = getUsername(context);
        //origin as appID eg.: http://example.com:8080
        String appID = FIDOUtil.getOrigin(request);
        //calls BE service method to generate challenge.
        FIDOUser fidoUser = new FIDOUser(user.getUserName(), user.getTenantDomain(), user.getUserStoreDomain(), appID);
        AuthenticateRequestData data = u2FService.startAuthentication(fidoUser);
        //redirect to FIDO login page
        if (data != null) {
            response.sendRedirect(response.encodeRedirectURL(loginPage + ("?"))
                    + "&authenticators=" + getName() + ":" + "LOCAL" + "&type=fido&sessionDataKey=" +
                    request.getParameter("sessionDataKey") +
                    "&data=" + data.toJson());
        } else {
            String redirectURL = ConfigurationFacade.getInstance().getAuthenticationEndpointRetryURL();
            redirectURL = response.encodeRedirectURL(redirectURL + ("?")) + "&failedUsername=" + URLEncoder.encode(user.getUserName(), IdentityCoreConstants.UTF_8) +
                    "&statusMsg=" + URLEncoder.encode(FIDOAuthenticatorConstants.AUTHENTICATION_ERROR_MESSAGE, IdentityCoreConstants.UTF_8) +
                    "&status=" + URLEncoder.encode(FIDOAuthenticatorConstants.AUTHENTICATION_STATUS, IdentityCoreConstants.UTF_8);
            response.sendRedirect(redirectURL);
        }

    } catch (IOException e) {
        throw new AuthenticationFailedException(
                "Could not initiate FIDO authentication request", e);
    }
}
 
Example 8
Source File: TokenMgtDAO.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * This method is to list the application authorized by OAuth resource owners
 *
 * @param authzUser username of the resource owner
 * @return set of distinct client IDs authorized by user until now
 * @throws IdentityOAuth2Exception if failed to update the access token
 */
public Set<String> getAllTimeAuthorizedClientIds(AuthenticatedUser authzUser) throws IdentityOAuth2Exception {

    String accessTokenStoreTable = OAuthConstants.ACCESS_TOKEN_STORE_TABLE;
    PreparedStatement ps = null;
    Connection connection = IdentityDatabaseUtil.getDBConnection();;
    ResultSet rs = null;
    Set<String> distinctConsumerKeys = new HashSet<>();
    boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreInUsernameCaseSensitive(authzUser.toString());
    String tenantDomain = authzUser.getTenantDomain();
    String tenantAwareUsernameWithNoUserDomain = authzUser.getUserName();
    String userDomain = authzUser.getUserStoreDomain();
    if ((userDomain != null)){
        userDomain.toUpperCase();
    }
    try {
        int tenantId = OAuth2Util.getTenantId(tenantDomain);
        if (OAuth2Util.checkAccessTokenPartitioningEnabled() &&
                OAuth2Util.checkUserNameAssertionEnabled()) {
            accessTokenStoreTable = OAuth2Util.getAccessTokenStoreTableFromUserId(authzUser.toString());
        }
        String sqlQuery = SQLQueries.GET_DISTINCT_APPS_AUTHORIZED_BY_USER_ALL_TIME.replace(
                IDN_OAUTH2_ACCESS_TOKEN, accessTokenStoreTable);
        if (!isUsernameCaseSensitive) {
            sqlQuery = sqlQuery.replace(AUTHZ_USER, LOWER_AUTHZ_USER);
        }
        ps = connection.prepareStatement(sqlQuery);
        if (isUsernameCaseSensitive) {
            ps.setString(1, tenantAwareUsernameWithNoUserDomain);
        } else {
            ps.setString(1, tenantAwareUsernameWithNoUserDomain.toLowerCase());
        }
        ps.setInt(2, tenantId);
        ps.setString(3, userDomain);
        rs = ps.executeQuery();
        while (rs.next()) {
            String consumerKey = persistenceProcessor.getPreprocessedClientId(rs.getString(1));
            distinctConsumerKeys.add(consumerKey);
        }
    } catch (SQLException e) {
        throw new IdentityOAuth2Exception(
                "Error occurred while retrieving all distinct Client IDs authorized by " +
                        "User ID : " + authzUser + " until now", e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, rs, ps);
    }
    return distinctConsumerKeys;
}
 
Example 9
Source File: PermissionBasedScopeIssuer.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * This method is used to get the authorized scopes out of requested scopes. It checks requested scopes with app
 * scopes whether user has permissions to take actions for the requested scopes.
 *
 * @param authenticatedUser Authenticated user.
 * @param reqScopeList      Requested scope list.
 * @param appScopes         App scopes.
 * @return Returns a list of scopes.
 */
private List<String> getAuthorizedScopes(AuthenticatedUser authenticatedUser, List<String> reqScopeList,
                                         Map<String, String> appScopes, List<String> whiteListedScopes) {

    boolean status;
    List<String> authorizedScopes = new ArrayList<>();
    int tenantId;
    String username = authenticatedUser.getUserName();
    String tenantDomain = authenticatedUser.getTenantDomain();
    RealmService realmService = getRealmService();
    List<String> defaultScope = new ArrayList<>();
    defaultScope.add(DEFAULT_SCOPE_NAME);

    try {
        tenantId = realmService.getTenantManager().getTenantId(tenantDomain);

        // If tenant Id is not set in the tokenReqContext, deriving it from username.
        if (tenantId == 0 || tenantId == -1) {
            tenantId = getTenantIdOfUser(username);
        }

        UserRealm userRealm = realmService.getTenantUserRealm(tenantId);

        //Iterate the requested scopes list.
        for (String scope : reqScopeList) {
            status = false;

            //Get the set of roles associated with the requested scope.
            String appPermissions = appScopes.get(scope);

            //If the scope has been defined in the context of the App and if permissions have been defined for
            // the scope
            if (appPermissions != null && appPermissions.length() != 0) {
                List<String> permissions = new ArrayList<>(Arrays.asList(appPermissions
                        .replaceAll(" ", "").split(",")));

                //Check if user has at least one of the permission associated with the scope
                if (!permissions.isEmpty()) {
                    for (String permission : permissions) {
                        if (userRealm != null && userRealm.getAuthorizationManager() != null) {
                            String userStore = authenticatedUser.getUserStoreDomain();
                            username = MultitenantUtils.getTenantAwareUsername(username);
                            if (userStore != null) {
                                status = userRealm.getAuthorizationManager()
                                        .isUserAuthorized(userStore + "/" + username, permission, UI_EXECUTE);
                            } else {
                                status = userRealm.getAuthorizationManager()
                                        .isUserAuthorized(username, permission, UI_EXECUTE);
                            }
                            if (status) {
                                break;
                            }
                        }
                    }
                    if (status) {
                        authorizedScopes.add(scope);
                    }
                }
            }

            //The scope string starts with 'device_'.
            else if (appScopes.containsKey(scope) || isWhiteListedScope(whiteListedScopes, scope)) {
                authorizedScopes.add(scope);
            }
        }
    } catch (UserStoreException e) {
        log.error("Error occurred while initializing user store.", e);
    }
    return (!authorizedScopes.isEmpty()) ? authorizedScopes : defaultScope;
}