Java Code Examples for org.wso2.carbon.utils.multitenancy.MultitenantUtils#getTenantAwareUsername()

The following examples show how to use org.wso2.carbon.utils.multitenancy.MultitenantUtils#getTenantAwareUsername() . 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: OAuthService.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Authorizes the OAuth request token for the given scope. In order for the Consumer to be able
 * to exchange the Request Token for an Access Token, the Consumer MUST obtain approval from the
 * User by directing the User to the Service Provider. The Consumer constructs an HTTP GET
 * request to the Service Provider's User Authorization URL with the following parameters.
 *
 * @param params             A container for the following attributes.
 * @param params:oauth_token (required) : Request token obtained from WSO2.
 * @param params:userName    : User who authorizes the token.
 * @param params:password    : Password of the user who authorizes the token.
 * @return oauth_token, oauth_verifier
 * @throws Exception
 */
public Parameters authorizeOauthRequestToken(Parameters params) throws IdentityException, AuthenticationException {
    String tenantUser = MultitenantUtils.getTenantAwareUsername(params.getAuthorizedbyUserName());
    String domainName = MultitenantUtils.getTenantDomain(params.getAuthorizedbyUserName());
    boolean isAuthenticated = false;
    try {
        isAuthenticated = IdentityTenantUtil
                .getRealm(domainName, params.getAuthorizedbyUserName()).getUserStoreManager()
                .authenticate(tenantUser, params.getAuthorizedbyUserPassword());
    } catch (UserStoreException e) {
        log.error("Error while authenticating the user", e);
        throw IdentityException.error("Error while authenticating the user");
    }
    if (isAuthenticated) {
        OAuthConsumerDAO dao = new OAuthConsumerDAO();
        String oauthVerifier = org.wso2.carbon.identity.oauth.OAuthUtil.getRandomNumber();
        Parameters token = dao.authorizeOAuthToken(params.getOauthToken(), tenantUser,
                oauthVerifier);
        token.setOauthToken(params.getOauthToken());
        token.setOauthTokenVerifier(oauthVerifier);
        return token;
    } else {
        throw new AuthenticationException("User Authentication Failed");
    }
}
 
Example 2
Source File: APIKeyMgtRemoteUserStoreMgtService.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * validates a username,password combination. Works for any tenant domain.
 * @param username username of the user(including tenant domain)
 * @param password password of the user
 * @return true if username,password is correct
 * @throws APIManagementException
 */
public boolean authenticate(String username, String password) throws APIManagementException {

    String tenantDomain = MultitenantUtils.getTenantDomain(username);
    PrivilegedCarbonContext.startTenantFlow();
    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);

    UserStoreManager userStoreManager;
    boolean isAuthenticated = false;
    try {
        userStoreManager =
                CarbonContext.getThreadLocalCarbonContext().getUserRealm().getUserStoreManager();
        String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(username);

        isAuthenticated = userStoreManager.authenticate(tenantAwareUserName, password);
    } catch (UserStoreException e) {
        APIUtil.handleException("Error occurred while validating credentials of user " + username, e);
    } finally {
        PrivilegedCarbonContext.getThreadLocalCarbonContext().endTenantFlow();
    }
    return isAuthenticated;
}
 
Example 3
Source File: UserRegistrationService.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public void addUser(UserDTO user) throws Exception {
    UserFieldDTO[] userFieldDTOs = null;
    Map<String, String> userClaims = null;

    userFieldDTOs = user.getUserFields();
    userClaims = new HashMap<String, String>();

    if (userFieldDTOs != null) {
        for (UserFieldDTO userFieldDTO : userFieldDTOs) {
            userClaims.put(userFieldDTO.getClaimUri(), userFieldDTO.getFieldValue());
        }
    }

    UserRealm realm = null;
    String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(user.getUserName());
    String tenantName = MultitenantUtils.getTenantDomain(user.getUserName());
    realm = IdentityTenantUtil.getRealm(tenantName, null);
    Registry registry = IdentityTenantUtil.getRegistry(null, null);
    addUser(tenantAwareUserName, user.getPassword(), userClaims, null, realm);
}
 
Example 4
Source File: IdentityManagementServiceUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Build user object from complete username
 * @param userName
 * @return
 */
public User getUser(String userName) {

    if (userName == null) {
        return null;
    }

    String userStoreDomain = extractDomainFromName(userName);
    String tenantDomain = MultitenantUtils.getTenantDomain(userName);
    String userNameWithoutTenantDomainAndUserStoreDomain = MultitenantUtils
            .getTenantAwareUsername(UserCoreUtil.removeDomainFromName(userName));

    User user = new User();
    user.setUsername(userNameWithoutTenantDomainAndUserStoreDomain);
    user.setRealm(userStoreDomain);
    user.setTenantDomain(tenantDomain);

    return user;
}
 
Example 5
Source File: CarbonUserRealmHostObject.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
public static boolean jsFunction_isUserAuthorized(Context cx,
		Scriptable thisObj, Object[] args, Function funObj) throws Exception {
	boolean isAuthorized = false;
	int argLength = args.length;
	if (argLength != 3) {
		throw new ScriptException("Invalid arguments.");
	}
	String user = (String) args[0];
	String userName = MultitenantUtils.getTenantAwareUsername(user);
	String domainName = MultitenantUtils.getTenantDomain(user);
	RealmService service = ServiceHodler.getRealmService();
	int tenantId = service.getTenantManager().getTenantId(domainName);
	UserRealm realm = service.getTenantUserRealm(tenantId);
	isAuthorized = realm.getAuthorizationManager().isUserAuthorized(userName, (String) args[1], (String) args[2]);
	return isAuthorized;
}
 
Example 6
Source File: UserSignUpWSWorkflowExecutor.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Override
public WorkflowResponse execute(WorkflowDTO workflowDTO) throws WorkflowException {

    if (log.isDebugEnabled()) {
        log.debug("Executing User SignUp Webservice Workflow for " + workflowDTO.getWorkflowReference());
    }

    try {
        String action = WorkflowConstants.REGISTER_USER_WS_ACTION;
        ServiceClient client = getClient(action);

        //get the default empty payload
        String payload = WorkflowConstants.REGISTER_USER_PAYLOAD;

        String callBackURL = workflowDTO.getCallbackUrl();
        String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(workflowDTO.getWorkflowReference());

        payload = payload.replace("$1", tenantAwareUserName);
        payload = payload.replace("$2", workflowDTO.getTenantDomain());
        payload = payload.replace("$3", workflowDTO.getExternalWorkflowReference());
        payload = payload.replace("$4", callBackURL != null ? callBackURL : "?");

        client.fireAndForget(AXIOMUtil.stringToOM(payload));
        super.execute(workflowDTO);
    } catch (AxisFault axisFault) {
        log.error("Error sending out message", axisFault);
        throw new WorkflowException("Error sending out message", axisFault);
    } catch (XMLStreamException e) {
        log.error("Error converting String to OMElement", e);
        throw new WorkflowException("Error converting String to OMElement", e);
    }
    return new GeneralWorkflowResponse();
}
 
Example 7
Source File: OAuth2Util.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public static AuthenticatedUser getUserFromUserName(String username) throws IllegalArgumentException {
    if (StringUtils.isNotBlank(username)) {
        String tenantDomain = MultitenantUtils.getTenantDomain(username);
        String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(username);
        String tenantAwareUsernameWithNoUserDomain = UserCoreUtil.removeDomainFromName(tenantAwareUsername);
        String userStoreDomain = IdentityUtil.extractDomainFromName(username).toUpperCase();
        AuthenticatedUser user = new AuthenticatedUser();
        user.setUserName(tenantAwareUsernameWithNoUserDomain);
        user.setTenantDomain(tenantDomain);
        user.setUserStoreDomain(userStoreDomain);

        return user;
    }
    throw new IllegalArgumentException("Cannot create user from empty user name");
}
 
Example 8
Source File: GeoLocationBasedServiceImpl.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
@Path("alerts/history")
@GET
@Consumes("application/json")
@Produces("application/json")
public Response getGeoAlertsHistoryForGeoClusters(@QueryParam("from") long from, @QueryParam("to") long to) {
    String tableName = "IOT_PER_DEVICE_STREAM_GEO_ALERTNOTIFICATIONS";
    String fromDate = String.valueOf(from);
    String toDate = String.valueOf(to);
    String query = "";
    if (from != 0 || to != 0) {
        query = "timeStamp : [" + fromDate + " TO " + toDate + "]";
    }
    try {
        List<SortByField> sortByFields = new ArrayList<>();
        SortByField sortByField = new SortByField("timeStamp", SortType.ASC);
        sortByFields.add(sortByField);

        // this is the user who initiates the request
        String authorizedUser = MultitenantUtils.getTenantAwareUsername(
                CarbonContext.getThreadLocalCarbonContext().getUsername());

        String tenantDomain = MultitenantUtils.getTenantDomain(authorizedUser);
        int tenantId = DeviceMgtAPIUtils.getRealmService().getTenantManager().getTenantId(tenantDomain);
        AnalyticsDataAPI analyticsDataAPI = DeviceMgtAPIUtils.getAnalyticsDataAPI();
        List<SearchResultEntry> searchResults = analyticsDataAPI.search(tenantId, tableName, query,
                0,
                100,
                sortByFields);
        List<Event> events = getEventBeans(analyticsDataAPI, tenantId, tableName, new ArrayList<String>(),
                searchResults);
        return Response.ok().entity(events).build();

    } catch (AnalyticsException | UserStoreException e) {
        log.error("Failed to perform search on table: " + tableName + " : " + e.getMessage(), e);
        throw DeviceMgtUtil.buildBadRequestException(
                Constants.ErrorMessages.STATUS_BAD_REQUEST_MESSAGE_DEFAULT);
    }
}
 
Example 9
Source File: UserProfileAdmin.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public void associateID(String idpID, String associatedID) throws UserProfileException {

        Connection connection = IdentityDatabaseUtil.getDBConnection();
        PreparedStatement prepStmt = null;
        String sql = null;
        int tenantID = CarbonContext.getThreadLocalCarbonContext().getTenantId();
        String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(CarbonContext.getThreadLocalCarbonContext()
                                                                          .getUsername());
        String domainName = getDomainName(tenantAwareUsername);
        tenantAwareUsername = getUsernameWithoutDomain(tenantAwareUsername);

        try {
            sql = "INSERT INTO IDN_ASSOCIATED_ID (TENANT_ID, IDP_ID, IDP_USER_ID, DOMAIN_NAME, USER_NAME) " +
                  "VALUES (? , (SELECT ID FROM IDP WHERE NAME = ? AND TENANT_ID = ? ), ? , ?, ?)";

            prepStmt = connection.prepareStatement(sql);
            prepStmt.setInt(1, tenantID);
            prepStmt.setString(2, idpID);
            prepStmt.setInt(3, tenantID);
            prepStmt.setString(4, associatedID);
            prepStmt.setString(5, domainName);
            prepStmt.setString(6, tenantAwareUsername);


            prepStmt.execute();
            connection.commit();
        } catch (SQLException e) {
            log.error("Error occurred while persisting the federated user ID", e);
            throw new UserProfileException("Error occurred while persisting the federated user ID", e);
        } finally {
            IdentityDatabaseUtil.closeAllConnections(connection, null, prepStmt);
        }

    }
 
Example 10
Source File: OpenIDProviderService.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Get Profile details of an user
 *
 * @param openId
 * @return
 * @throws IdentityProviderException
 */
public OpenIDUserProfileDTO[] getUserProfiles(String openId, OpenIDParameterDTO[] requredClaims)
        throws IdentityProviderException {
    String userName = null;
    UserRealm realm = null;
    UserStoreManager reader = null;
    String tenatUser = null;
    String domainName = null;

    try {
        userName = OpenIDUtil.getUserName(openId);
        tenatUser = MultitenantUtils.getTenantAwareUsername(userName);
        domainName = MultitenantUtils.getDomainNameFromOpenId(openId);
        realm = IdentityTenantUtil.getRealm(domainName, userName);
        reader = realm.getUserStoreManager();
        String[] profileNames = reader.getProfileNames(tenatUser);
        OpenIDUserProfileDTO[] profileDtoSet = new OpenIDUserProfileDTO[profileNames.length];

        List<String> claimList = null;
        ParameterList paramList = getParameterList(requredClaims);
        AuthRequest authReq =
                AuthRequest.createAuthRequest(paramList, OpenIDProvider.getInstance()
                                                                       .getManager()
                                                                       .getRealmVerifier());

        claimList = getRequestedAttributes(authReq);

        for (int i = 0; i < profileNames.length; i++) {
            OpenIDUserProfileDTO profileDTO = new OpenIDUserProfileDTO();
            OpenIDClaimDTO[] claimSet =
                    getOpenIDClaimValues(openId, profileNames[i], claimList);
            profileDTO.setProfileName(profileNames[i]);
            profileDTO.setClaimSet(claimSet);
            profileDtoSet[i] = profileDTO;
        }
        return profileDtoSet;
    } catch (MalformedURLException | UserStoreException | MessageException | IdentityException e) {
        throw new IdentityProviderException("Error while retrieving user profiles", e);
    }
}
 
Example 11
Source File: FrameworkUtils.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Validate the username when email username is enabled.
 *
 * @param username Username.
 * @param context Authentication context.
 * @throws InvalidCredentialsException when username is not an email when email username is enabled.
 */
public static void validateUsername(String username, AuthenticationContext context)
        throws InvalidCredentialsException {

    if (IdentityUtil.isEmailUsernameEnabled()) {
        String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(username);
        if (StringUtils.countMatches(tenantAwareUsername, "@") < 1) {
            context.setProperty(CONTEXT_PROP_INVALID_EMAIL_USERNAME, true);
            throw new InvalidCredentialsException("Invalid username. Username has to be an email.");
        }
    }
}
 
Example 12
Source File: RegistryTopicManager.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new role which has the same name as the destinationName and assign the logged in
 * user to the newly created role. Then, authorize the newly created role to subscribe and
 * publish to the destination.
 *
 * @param username        name of the logged in user
 * @param destinationName destination name. Either topic or queue name
 * @param destinationId   ID given to the destination
 * @param userRealm       the  user store
 * @throws UserStoreException
 */
private static void authorizePermissionsToLoggedInUser(String username, String destinationName,
                                                       String destinationId,
                                                       UserRealm userRealm) throws
                                                                            UserStoreException {

    //For registry we use a modified queue name
    String newDestinationName = destinationName.replace("@", AT_REPLACE_CHAR);

    // creating the internal role name
    String roleName = UserCoreUtil.addInternalDomainName(TOPIC_ROLE_PREFIX +
                                                         newDestinationName.replace("/", "-"));

    // the interface to store user data
    UserStoreManager userStoreManager = CarbonContext.getThreadLocalCarbonContext().getUserRealm().getUserStoreManager();

    if (!userStoreManager.isExistingRole(roleName)) {
        String[] user = {MultitenantUtils.getTenantAwareUsername(username)};

        // adds the internal role to user store
        userStoreManager.addRole(roleName, user, null);
        // gives subscribe permissions to the internal role in the user store
        userRealm.getAuthorizationManager().authorizeRole(
                roleName, destinationId, EventBrokerConstants.EB_PERMISSION_SUBSCRIBE);
        // gives publish permissions to the internal role in the user store
        userRealm.getAuthorizationManager().authorizeRole(
                roleName, destinationId, EventBrokerConstants.EB_PERMISSION_PUBLISH);
        // gives change permissions to the internal role in the user store
        userRealm.getAuthorizationManager().authorizeRole(
                roleName, destinationId, EventBrokerConstants.EB_PERMISSION_CHANGE_PERMISSION);

    } else {
        log.warn("Unable to provide permissions to the user, " +
                 " " + username + ", to subscribe and publish to " + newDestinationName);
    }
}
 
Example 13
Source File: DefaultAttributeFinder.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
public Set<String> getAttributeValues(String subjectId, String resourceId, String actionId,
                                      String environmentId, String attributeId, String issuer) throws Exception {
    Set<String> values = new HashSet<String>();

    if (log.isDebugEnabled()) {
        log.debug("Retrieving attribute values of subjectId \'" + subjectId + "\'with attributeId \'" +
                attributeId + "\'");
    }
    if (StringUtils.isEmpty(subjectId)) {
        if (log.isDebugEnabled()) {
            log.debug("subjectId value is null or empty. Returning empty attribute set");
        }
        return values;
    }
    subjectId = MultitenantUtils.getTenantAwareUsername(subjectId);
    if (UserCoreConstants.ClaimTypeURIs.ROLE.equals(attributeId)) {
        if (log.isDebugEnabled()) {
            log.debug("Looking for roles via DefaultAttributeFinder");
        }
        String[] roles = CarbonContext.getThreadLocalCarbonContext().getUserRealm().getUserStoreManager()
                .getRoleListOfUser(subjectId);
        if (roles != null && roles.length > 0) {
            for (String role : roles) {
                if (log.isDebugEnabled()) {
                    log.debug(String.format("User %1$s belongs to the Role %2$s", subjectId,
                            role));
                }
                values.add(role);
            }
        }
    } else {
        String claimValue = null;
        try {
            claimValue = CarbonContext.getThreadLocalCarbonContext().getUserRealm().
                    getUserStoreManager().getUserClaimValue(subjectId, attributeId, null);
            if (log.isDebugEnabled()) {
                log.debug("Claim \'" + claimValue + "\' retrieved for attributeId \'" + attributeId + "\' " +
                        "for subjectId \'" + subjectId + "\'");
            }
        } catch (UserStoreException e) {
            if(e.getMessage().startsWith(IdentityCoreConstants.USER_NOT_FOUND)){
                if(log.isDebugEnabled()){
                    log.debug("User: " + subjectId + " not found in user store");
                }
            } else {
                throw e;
            }
        }
        if (claimValue == null && log.isDebugEnabled()) {
            log.debug(String.format("Request attribute %1$s not found", attributeId));
        }
        // Fix for multiple claim values
        if (claimValue != null) {
            String claimSeparator = CarbonContext.getThreadLocalCarbonContext().getUserRealm().
                    getRealmConfiguration().getUserStoreProperty(IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR);
            if (StringUtils.isBlank(claimSeparator)) {
                claimSeparator = IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR_DEFAULT;
            }
            if (claimValue.contains(claimSeparator)) {
                StringTokenizer st = new StringTokenizer(claimValue, claimSeparator);
                while (st.hasMoreElements()) {
                    String attributeValue = st.nextElement().toString();
                    if (StringUtils.isNotBlank(attributeValue)) {
                        values.add(attributeValue);
                    }
                }
            } else {
                values.add(claimValue);
            }
        }
    }
    return values;
}
 
Example 14
Source File: BasicAuthHandler.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
public boolean isAuthenticated(ContainerRequestContext message) {
    // extract authorization header and authenticate.

    // get the value for Authorization Header
    List authzHeaders = message.getHeaders().get(EntitlementEndpointConstants.AUTHORIZATION_HEADER);
    if (authzHeaders != null) {
        // get the authorization header value, if provided
        String authzHeader = (String) authzHeaders.get(0);

        // decode it and extract username and password
        byte[] decodedAuthHeader = Base64.decode(authzHeader.split(" ")[1]);
        String authHeader = new String(decodedAuthHeader);
        String userName = authHeader.split(":")[0];
        String password = authHeader.split(":")[1];
        if (userName != null && password != null) {
            String tenantDomain = MultitenantUtils.getTenantDomain(userName);
            String tenantLessUserName = MultitenantUtils.getTenantAwareUsername(userName);

            try {
                // get super tenant context and get realm service which is an osgi service
                RealmService realmService = (RealmService) PrivilegedCarbonContext
                        .getThreadLocalCarbonContext().getOSGiService(RealmService.class);
                if (realmService != null) {
                    int tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
                    if (tenantId == -1) {
                        log.error("Invalid tenant domain " + tenantDomain);
                        return false;
                    }
                    // get tenant's user realm
                    UserRealm userRealm = realmService.getTenantUserRealm(tenantId);
                    boolean authenticated = userRealm.getUserStoreManager().authenticate(
                            tenantLessUserName, password);
                    if (authenticated) {
                        // authentication success. set the username for authorization header and
                        // proceed the REST call
                        authzHeaders.set(0, userName);
                        return true;
                    } else {
                        log.error("Authentication failed for the user: " + tenantLessUserName
                                + "@" + tenantDomain);
                        return false;
                    }
                } else {
                    log.error("Error in getting Realm Service for user: " + userName);
                    return false;
                }
            } catch (UserStoreException e) {
                log.error("Internal server error while authenticating the user.");
                return false;
            }
        } else {
            log.error("Authentication required for this resource. " +
                            "Username or password not provided.");
            return false;
        }
    } else {
        log.error("Authentication required for this resource. " +
                      "Authorization header not present in the request.");
        return false;
    }

}
 
Example 15
Source File: OIDCAuthenticator.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * Login method
 *
 * @param code  code value
 * @param nonce nonce value
 * @return user name of authenticated user
 */
public String login(String code, String nonce) {

    String userName;

    try {

        HttpSession httpSession = getHttpSession();
        RealmService realmService = OIDCAuthBEDataHolder.getInstance().getRealmService();
        RegistryService registryService = OIDCAuthBEDataHolder.getInstance().getRegistryService();

        ServerConfiguration serverConfiguration = getServerConfiguration();
        AuthClient authClient = getClientConfiguration();
        String jsonResponse = getTokenFromTokenEP(serverConfiguration, authClient, code);
        AuthenticationToken oidcAuthenticationToken = getAuthenticationToken(jsonResponse);
        userName = getUserName(oidcAuthenticationToken, serverConfiguration);

        if (userName == null || userName.equals("")) {
            log.error("Authentication Request is rejected. "
                    + "User Name is Null");
            return null;
        }

        String tenantDomain = MultitenantUtils.getTenantDomain(userName);
        int tenantId = realmService.getTenantManager().getTenantId(tenantDomain);


        // Start Authentication
        handleAuthenticationStarted(tenantId);
        if (isResponseSignatureValidationEnabled()) {

            boolean isSignatureValid = validateSignature(serverConfiguration, authClient,
                    oidcAuthenticationToken, nonce);

            if (!isSignatureValid) {
                log.error("Authentication Request is rejected. "
                        + " Signature validation failed.");
                CarbonAuthenticationUtil.onFailedAdminLogin(httpSession, userName, tenantId,
                        "OIDC Authentication",
                        "Invalid Signature");
                handleAuthenticationCompleted(tenantId, false);
                return null;
            }
        }

        userName = MultitenantUtils.getTenantAwareUsername(userName);
        UserRealm realm = AnonymousSessionUtil.getRealmByTenantDomain(registryService, realmService,
                tenantDomain);

        // Starting Authorization
        PermissionUpdateUtil.updatePermissionTree(tenantId);
        boolean isAuthorized = realm.getAuthorizationManager().isUserAuthorized(userName,
                "/permission/admin/login", CarbonConstants.UI_PERMISSION_ACTION);
        if (isAuthorized) {
            CarbonAuthenticationUtil.onSuccessAdminLogin(httpSession, userName,
                    tenantId, tenantDomain, "OIDC Authentication");
            handleAuthenticationCompleted(tenantId, true);
        } else {
            log.error("Authentication Request is rejected. Authorization Failure.");
            CarbonAuthenticationUtil.onFailedAdminLogin(httpSession, userName, tenantId,
                    "OIDC Authentication", "Invalid credential");
            handleAuthenticationCompleted(tenantId, false);
            return null;
        }
    } catch (Exception e) {
        String msg = "System error while Authenticating/Authorizing User : " + e.getMessage();
        log.error(msg, e);
        return null;
    }

    return userName;
}
 
Example 16
Source File: BasicAuthAuthenticator.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
private String getEndUserName(String username) {
    return MultitenantUtils.getTenantAwareUsername(username) + "@" + MultitenantUtils.getTenantDomain(username);
}
 
Example 17
Source File: DefaultAttributeFinder.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public Set<String> getAttributeValues(String subjectId, String resourceId, String actionId,
                                      String environmentId, String attributeId, String issuer) throws Exception {
    Set<String> values = new HashSet<String>();

    subjectId = MultitenantUtils.getTenantAwareUsername(subjectId);
    if (UserCoreConstants.ClaimTypeURIs.ROLE.equals(attributeId)) {
        if (log.isDebugEnabled()) {
            log.debug("Looking for roles via DefaultAttributeFinder");
        }
        String[] roles = CarbonContext.getThreadLocalCarbonContext().getUserRealm().getUserStoreManager()
                .getRoleListOfUser(subjectId);
        if (roles != null && roles.length > 0) {
            for (String role : roles) {
                if (log.isDebugEnabled()) {
                    log.debug(String.format("User %1$s belongs to the Role %2$s", subjectId,
                            role));
                }
                values.add(role);
            }
        }
    } else {
        String claimValue = null;
        try {
            claimValue = CarbonContext.getThreadLocalCarbonContext().getUserRealm().
                    getUserStoreManager().getUserClaimValue(subjectId, attributeId, null);
        } catch (UserStoreException e) {
            if(e.getMessage().startsWith(IdentityCoreConstants.USER_NOT_FOUND)){
                if(log.isDebugEnabled()){
                    log.debug("User: " + subjectId + " not found in user store");
                }
            } else {
                throw e;
            }
        }
        if (claimValue == null && log.isDebugEnabled()) {
            log.debug(String.format("Request attribute %1$s not found", attributeId));
        }
        // Fix for multiple claim values
        if (claimValue != null) {
            String claimSeparator = CarbonContext.getThreadLocalCarbonContext().getUserRealm().
                    getRealmConfiguration().getUserStoreProperty(IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR);
            if (StringUtils.isBlank(claimSeparator)) {
                claimSeparator = IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR_DEFAULT;
            }
            if (claimValue.contains(claimSeparator)) {
                StringTokenizer st = new StringTokenizer(claimValue, claimSeparator);
                while (st.hasMoreElements()) {
                    String attributeValue = st.nextElement().toString();
                    if (StringUtils.isNotBlank(attributeValue)) {
                        values.add(attributeValue);
                    }
                }
            } else {
                values.add(claimValue);
            }
        }
    }
    return values;
}
 
Example 18
Source File: DefaultProvisioningHandler.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public void handle(List<String> roles, String subject, Map<String, String> attributes,
                   String provisioningUserStoreId, String tenantDomain) throws FrameworkException {

    RegistryService registryService = FrameworkServiceComponent.getRegistryService();
    RealmService realmService = FrameworkServiceComponent.getRealmService();

    try {
        int tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
        UserRealm realm = AnonymousSessionUtil.getRealmByTenantDomain(registryService,
                                                                      realmService, tenantDomain);

        String userStoreDomain = getUserStoreDomain(provisioningUserStoreId, realm);

        String username = MultitenantUtils.getTenantAwareUsername(subject);

        UserStoreManager userStoreManager = getUserStoreManager(realm, userStoreDomain);

        // Remove userStoreManager domain from username if the userStoreDomain is not primary
        if (realm.getUserStoreManager().getRealmConfiguration().isPrimary()) {
            username = UserCoreUtil.removeDomainFromName(username);
        }

        String[] newRoles = new String[]{};

        if (roles != null) {
            roles = removeDomainFromNamesExcludeInternal(roles, userStoreManager.getTenantId());
            newRoles = roles.toArray(new String[roles.size()]);
        }

        if (log.isDebugEnabled()) {
            log.debug("User " + username + " contains roles : " + Arrays.toString(newRoles)
                      + " going to be provisioned");
        }

        // addingRoles = newRoles AND allExistingRoles
        Collection<String> addingRoles = getRolesToAdd(userStoreManager, newRoles);

        Map<String, String> userClaims = prepareClaimMappings(attributes);

        if (userStoreManager.isExistingUser(username)) {

            if (roles != null && !roles.isEmpty()) {
                // Update user
                Collection<String> currentRolesList = Arrays.asList(userStoreManager
                                                                            .getRoleListOfUser(username));
                // addingRoles = (newRoles AND existingRoles) - currentRolesList)
                addingRoles.removeAll(currentRolesList);

                Collection<String> deletingRoles = new ArrayList<String>();
                deletingRoles.addAll(currentRolesList);
                // deletingRoles = currentRolesList - newRoles
                deletingRoles.removeAll(Arrays.asList(newRoles));

                // Exclude Internal/everyonerole from deleting role since its cannot be deleted
                deletingRoles.remove(realm.getRealmConfiguration().getEveryOneRoleName());

                // TODO : Does it need to check this?
                // Check for case whether superadmin login
                handleFederatedUserNameEqualsToSuperAdminUserName(realm, username, userStoreManager, deletingRoles);

                updateUserWithNewRoleSet(username, userStoreManager, newRoles, addingRoles, deletingRoles);
            }

            if (!userClaims.isEmpty()) {
                userStoreManager.setUserClaimValues(username, userClaims, null);
            }

        } else {

            userStoreManager.addUser(username, generatePassword(), addingRoles.toArray(
                    new String[addingRoles.size()]), userClaims, null);

            if (log.isDebugEnabled()) {
                log.debug("Federated user: " + username
                          + " is provisioned by authentication framework with roles : "
                          + Arrays.toString(addingRoles.toArray(new String[addingRoles.size()])));
            }
        }

        PermissionUpdateUtil.updatePermissionTree(tenantId);

    } catch (org.wso2.carbon.user.api.UserStoreException | CarbonException e) {
        throw new FrameworkException("Error while provisioning user : " + subject, e);
    }
}
 
Example 19
Source File: SAML2SSOAuthenticator.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public boolean login(AuthnReqDTO authDto) {
    String username = null;
    String tenantDomain = null;
    String auditResult = SAML2SSOAuthenticatorConstants.AUDIT_RESULT_FAILED;

    HttpSession httpSession = getHttpSession();
    try {
        XMLObject xmlObject = Util.unmarshall(org.wso2.carbon.identity.authenticator.saml2.sso.common.Util.decode(authDto.getResponse()));

        username = org.wso2.carbon.identity.authenticator.saml2.sso.common.Util.getUsername(xmlObject);

        if ((username == null) || "".equals(username.trim())) {
            log.error("Authentication Request is rejected. " +
                    "SAMLResponse does not contain the username of the subject.");
            CarbonAuthenticationUtil.onFailedAdminLogin(httpSession, username, -1,
                    "SAML2 SSO Authentication", "SAMLResponse does not contain the username of the subject");
            // Unable to call #handleAuthenticationCompleted since there is no way to determine
            // tenantId without knowing the username.
            return false;
        }

        if (!validateAudienceRestrictionInXML(xmlObject)) {
            log.error("Authentication Request is rejected. SAMLResponse AudienceRestriction validation failed.");
            CarbonAuthenticationUtil.onFailedAdminLogin(httpSession, username, -1,
                    "SAML2 SSO Authentication", "AudienceRestriction validation failed");
            return false;
        }

        RegistryService registryService = SAML2SSOAuthBEDataHolder.getInstance().getRegistryService();
        RealmService realmService = SAML2SSOAuthBEDataHolder.getInstance().getRealmService();
        tenantDomain = MultitenantUtils.getTenantDomain(username);
        int tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
        handleAuthenticationStarted(tenantId);
        if (isResponseSignatureValidationEnabled()) {
            boolean isSignatureValid = validateSignature(xmlObject, tenantDomain);
            if (!isSignatureValid) {
                log.error("Authentication Request is rejected. Signature validation failed.");
                CarbonAuthenticationUtil.onFailedAdminLogin(httpSession, username, tenantId,
                        "SAML2 SSO Authentication", "Invalid Signature");
                handleAuthenticationCompleted(tenantId, false);
                return false;
            }
        }

        username = MultitenantUtils.getTenantAwareUsername(username);
        UserRealm realm = AnonymousSessionUtil.getRealmByTenantDomain(registryService,
                realmService, tenantDomain);
        // Authentication is done

        // Starting user provisioning
        provisionUser(username, realm, xmlObject);
        // End user provisioning

        // Starting Authorization

        PermissionUpdateUtil.updatePermissionTree(tenantId);
        boolean isAuthorized = false;
        if (realm != null) {
            isAuthorized = realm.getAuthorizationManager().isUserAuthorized(username,
                    "/permission/admin/login", CarbonConstants.UI_PERMISSION_ACTION);
        }
        if (isAuthorized) {
            CarbonAuthenticationUtil.onSuccessAdminLogin(httpSession, username,
                    tenantId, tenantDomain, "SAML2 SSO Authentication");
            handleAuthenticationCompleted(tenantId, true);
            auditResult = SAML2SSOAuthenticatorConstants.AUDIT_RESULT_SUCCESS;
            return true;
        } else {
            log.error("Authentication Request is rejected. Authorization Failure.");
            CarbonAuthenticationUtil.onFailedAdminLogin(httpSession, username, tenantId,
                    "SAML2 SSO Authentication", "Authorization Failure");
            handleAuthenticationCompleted(tenantId, false);
            return false;
        }
    } catch (Exception e) {
        String msg = "System error while Authenticating/Authorizing User : " + e.getMessage();
        log.error(msg, e);
        return false;
    } finally {
        if (username != null && username.trim().length() > 0 && AUDIT_LOG.isInfoEnabled()) {

            String auditInitiator = username + UserCoreConstants.TENANT_DOMAIN_COMBINER + tenantDomain;
            String auditData = "";

            AUDIT_LOG.info(String.format(SAML2SSOAuthenticatorConstants.AUDIT_MESSAGE,
                    auditInitiator, SAML2SSOAuthenticatorConstants.AUDIT_ACTION_LOGIN, AUTHENTICATOR_NAME,
                    auditData, auditResult));
        }
    }
}
 
Example 20
Source File: StratosAuthenticationHandler.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
/**
 * Authenticate the user against the user store. Once authenticate, populate the {@link org.wso2.carbon.context.CarbonContext}
 * to be used by the downstream code.
 *
 * @param message
 * @param classResourceInfo
 * @return
 */
public Response handle(Message message, ClassResourceInfo classResourceInfo) {
    if (log.isDebugEnabled()) {
        log.debug(String.format("Authenticating request: [message-id] %s", message.getId()));
    }

    // If Mutual SSL is enabled
    HttpServletRequest request = (HttpServletRequest) message.get("HTTP.REQUEST");
    Object certObject = request.getAttribute("javax.servlet.request.X509Certificate");

    AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);
    String username = policy.getUserName().trim();
    String password = policy.getPassword().trim();

    //sanity check
    if (StringUtils.isEmpty(username)) {
        log.error("username is seen as null/empty values");
        return Response.status(Response.Status.UNAUTHORIZED)
                .header("WWW-Authenticate", "Basic").type(MediaType.APPLICATION_JSON)
                .entity(new ResponseMessageBean(ResponseMessageBean.ERROR, "Username cannot be null")).build();
    } else if (certObject == null && (StringUtils.isEmpty(password))) {
        log.error("password is seen as null/empty values");
        return Response.status(Response.Status.UNAUTHORIZED)
                .header("WWW-Authenticate", "Basic").type(MediaType.APPLICATION_JSON)
                .entity(new ResponseMessageBean(ResponseMessageBean.ERROR, "password cannot be null")).build();
    }

    try {
        RealmService realmService = ServiceHolder.getRealmService();
        RegistryService registryService = ServiceHolder.getRegistryService();
        String tenantDomain = MultitenantUtils.getTenantDomain(username);
        int tenantId = realmService.getTenantManager().getTenantId(tenantDomain);

        UserRealm userRealm = null;
        if (certObject == null) {
            userRealm = AnonymousSessionUtil.getRealmByTenantDomain(registryService, realmService, tenantDomain);
            if (userRealm == null) {
                log.error("Invalid domain or unactivated tenant login");
                // is this the correct HTTP code for this scenario ? (401)
                return Response.status(Response.Status.UNAUTHORIZED).header("WWW-Authenticate", "Basic").
                        type(MediaType.APPLICATION_JSON).entity(
                        new ResponseMessageBean(ResponseMessageBean.ERROR, "Tenant not found")).build();
            }
        }
        username = MultitenantUtils.getTenantAwareUsername(username);
        if (certObject != null || userRealm.getUserStoreManager().authenticate(username, password)) {  // if authenticated

            // setting the correct tenant info for downstream code..
            PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
            carbonContext.setTenantDomain(tenantDomain);
            carbonContext.setTenantId(tenantId);
            carbonContext.setUsername(username);
            //populate the secuirtyContext of authenticated user
            SecurityContext securityContext = new StratosSecurityContext(username);
            message.put(SecurityContext.class, securityContext);

            // set the authenticated flag and let the request to continue
            AuthenticationContext.setAuthenticated(true);
            if (log.isDebugEnabled()) {
                log.debug("Authenticated using the " + CookieBasedAuthenticationHandler.class.getName() + "for username  :" +
                        username + "tenantDomain : " + tenantDomain + " tenantId : " + tenantId);
            }
            return null;
        } else {
            log.warn(String.format("Unable to authenticate the request: [message-id] %s", message.getId()));
            // authentication failed, request the authetication, add the realm name if needed to the value of WWW-Authenticate
            return Response.status(Response.Status.UNAUTHORIZED).header("WWW-Authenticate", "Basic").
                    type(MediaType.APPLICATION_JSON).entity(new ResponseMessageBean(ResponseMessageBean.ERROR,
                    "Authentication failed. Please check your username/password")).build();
        }
    } catch (Exception exception) {
        log.error(String.format("Authentication failed: [message-id] %s", message.getId()), exception);
        // server error in the eyes of the client. Hence 5xx HTTP code.
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).type(MediaType.APPLICATION_JSON).
                entity(new ResponseMessageBean(ResponseMessageBean.ERROR,
                        "Unexpected error. Please contact the system admin")).build();
    }
}