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

The following examples show how to use org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser#getUserStoreDomain() . 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: 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 2
Source File: FIDOAuthenticator.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private AuthenticatedUser getUsername(AuthenticationContext context) throws AuthenticationFailedException {
    //username from authentication context.
    AuthenticatedUser authenticatedUser = null;
    for (int i = 1; i <= context.getSequenceConfig().getStepMap().size(); i++) {
        StepConfig stepConfig = context.getSequenceConfig().getStepMap().get(i);
        if (stepConfig.getAuthenticatedUser() != null && stepConfig.getAuthenticatedAutenticator()
                .getApplicationAuthenticator() instanceof LocalApplicationAuthenticator) {
            authenticatedUser = stepConfig.getAuthenticatedUser();
            if (authenticatedUser.getUserStoreDomain() == null) {
                authenticatedUser.setUserStoreDomain(UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME);
            }


            if (log.isDebugEnabled()) {
                log.debug("username :" + authenticatedUser.toString());
            }
            break;
        }
    }
    if(authenticatedUser == null){
        throw new AuthenticationFailedException("Could not locate an authenticated username from previous steps " +
                "of the sequence. Hence cannot continue with FIDO authentication.");
    }
    return authenticatedUser;
}
 
Example 3
Source File: SSOConsentServiceImpl.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private String buildSubjectWithUserStoreDomain(AuthenticatedUser authenticatedUser) {

        String userStoreDomain;
        if (authenticatedUser.isFederatedUser()) {
            userStoreDomain = getFederatedUserDomain(authenticatedUser.getFederatedIdPName());
        } else {
            userStoreDomain = authenticatedUser.getUserStoreDomain();
        }

        return UserCoreUtil.addDomainToName(authenticatedUser.getUserName(), userStoreDomain);
    }
 
Example 4
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 5
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 6
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 7
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;
}