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

The following examples show how to use org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser#getUserName() . 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: OpenIDConnectUserRPStore.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * @param user
 * @param appName
 * @throws OAuthSystemException
 */
public void putUserRPToStore(AuthenticatedUser user, String appName, boolean trustedAlways, String clientId) throws
        OAuthSystemException {
    OpenIDUserRPDO repDO = new OpenIDUserRPDO();
    repDO.setDefaultProfileName(DEFAULT_PROFILE_NAME);
    repDO.setRpUrl(appName);
    repDO.setUserName(user.getAuthenticatedSubjectIdentifier());
    repDO.setTrustedAlways(trustedAlways);
    int tenantId = -1;
    if (user.getUserName() != null) {
        tenantId = IdentityTenantUtil.getTenantId(user.getTenantDomain());
    } else {
        OAuthAppDAO oAuthAppDAO = new OAuthAppDAO();
        OAuthAppDO appDO;
        try {
            appDO = oAuthAppDAO.getAppInformation(clientId);
            tenantId = IdentityTenantUtil.getTenantId(appDO.getUser().getTenantDomain());
        } catch (IdentityOAuth2Exception | InvalidOAuthClientException e) {
            throw new OAuthSystemException("Error while retrieving app");
        }
    }

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

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

    return false;
}
 
Example 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: 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 6
Source File: ExtendedClientCredentialsGrantHandler.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Override
public boolean validateGrant(OAuthTokenReqMessageContext tokReqMsgCtx)
        throws IdentityOAuth2Exception {

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

    return validateResult;
}
 
Example 7
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 8
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 9
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 10
Source File: TokenMgtDAO.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * @param authenticatedUser
 * @return
 * @throws IdentityOAuth2Exception
 */
public Set<String> getAccessTokensForUser(AuthenticatedUser authenticatedUser) throws
        IdentityOAuth2Exception {
    String accessTokenStoreTable = OAuthConstants.ACCESS_TOKEN_STORE_TABLE;
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement ps = null;
    ResultSet rs = null;
    Set<String> accessTokens = new HashSet<>();
    boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreInUsernameCaseSensitive(authenticatedUser.toString());
    try {
        if (OAuth2Util.checkAccessTokenPartitioningEnabled() &&
                OAuth2Util.checkUserNameAssertionEnabled()) {
            accessTokenStoreTable = OAuth2Util.getAccessTokenStoreTableFromUserId(authenticatedUser.toString());
        }
        String sqlQuery = SQLQueries.GET_ACCESS_TOKEN_BY_AUTHZUSER.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, authenticatedUser.getUserName());
        } else {
            ps.setString(1, authenticatedUser.getUserName().toLowerCase());
        }
        ps.setString(2, Integer.toString(OAuth2Util.getTenantId(authenticatedUser.getTenantDomain())));
        ps.setString(3, OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE);
        ps.setString(4, authenticatedUser.getUserStoreDomain());
        rs = ps.executeQuery();
        while (rs.next()){
            accessTokens.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 accessTokens;
}
 
Example 11
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 12
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;
}