Example usage for javax.servlet.http HttpServletRequest getRemoteUser

List of usage examples for javax.servlet.http HttpServletRequest getRemoteUser

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getRemoteUser.

Prototype

public String getRemoteUser();

Source Link

Document

Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated.

Usage

From source file:com.redhat.rhn.frontend.action.LoginHelper.java

/**
 * check whether we can login an externally authenticated user
 * @param request request/*from  w  ww.  j  a v a 2 s .c  om*/
 * @param messages messages
 * @param errors errors
 * @return user, if externally authenticated
 */
public static User checkExternalAuthentication(HttpServletRequest request, ActionMessages messages,
        ActionErrors errors) {
    String remoteUserString = request.getRemoteUser();
    User remoteUser = null;
    if (remoteUserString != null) {

        String firstname = decodeFromIso88591((String) request.getAttribute("REMOTE_USER_FIRSTNAME"), "");
        String lastname = decodeFromIso88591((String) request.getAttribute("REMOTE_USER_LASTNAME"), "");
        String email = decodeFromIso88591((String) request.getAttribute("REMOTE_USER_EMAIL"), null);

        Set<String> extGroups = getExtGroups(request);
        Set<Role> roles = getRolesFromExtGroups(extGroups);

        log.warn("REMOTE_USER_GROUPS: " + request.getAttribute("REMOTE_USER_GROUPS"));

        try {
            remoteUser = UserFactory.lookupByLogin(remoteUserString);

            if (remoteUser.isDisabled()) {
                errors.add(ActionMessages.GLOBAL_MESSAGE,
                        new ActionMessage("account.user.disabled", new String[] { remoteUserString }));
                remoteUser = null;
            }
            if (remoteUser != null) {
                UpdateUserCommand updateCmd = new UpdateUserCommand(remoteUser);
                if (!StringUtils.isEmpty(firstname)) {
                    updateCmd.setFirstNames(firstname);
                }
                if (!StringUtils.isEmpty(lastname)) {
                    updateCmd.setLastName(lastname);
                }
                if (!StringUtils.isEmpty(email)) {
                    updateCmd.setEmail(email);
                }
                updateCmd.setTemporaryRoles(roles);
                updateCmd.updateUser();
                log.warn("Externally authenticated login " + remoteUserString + " (" + firstname + " "
                        + lastname + ")");
            }
        } catch (LookupException le) {
            Org newUserOrg = null;
            Boolean useOrgUnit = SatConfigFactory
                    .getSatConfigBooleanValue(SatConfigFactory.EXT_AUTH_USE_ORGUNIT);
            if (useOrgUnit) {
                String orgUnitString = (String) request.getAttribute("REMOTE_USER_ORGUNIT");
                newUserOrg = OrgFactory.lookupByName(orgUnitString);
                if (newUserOrg == null) {
                    log.error("Cannot find organization with name: " + orgUnitString);
                }
            }
            if (newUserOrg == null) {
                Long defaultOrgId = SatConfigFactory
                        .getSatConfigLongValue(SatConfigFactory.EXT_AUTH_DEFAULT_ORGID);
                if (defaultOrgId != null) {
                    newUserOrg = OrgFactory.lookupById(defaultOrgId);
                    if (newUserOrg == null) {
                        log.error("Cannot find organization with id: " + defaultOrgId);
                    }
                }
            }
            if (newUserOrg != null) {
                Set<ServerGroup> sgs = getSgsFromExtGroups(extGroups, newUserOrg);
                try {
                    CreateUserCommand createCmd = new CreateUserCommand();
                    createCmd.setLogin(remoteUserString);
                    // set a password, that cannot really be used
                    createCmd.setRawPassword(DEFAULT_KERB_USER_PASSWORD);
                    createCmd.setFirstNames(firstname);
                    createCmd.setLastName(lastname);
                    createCmd.setEmail(email);
                    createCmd.setOrg(newUserOrg);
                    createCmd.setTemporaryRoles(roles);
                    createCmd.setServerGroups(sgs);
                    createCmd.validate();
                    createCmd.storeNewUser();
                    remoteUser = createCmd.getUser();
                    log.warn("Externally authenticated login " + remoteUserString + " (" + firstname + " "
                            + lastname + ") created in " + newUserOrg.getName() + ".");
                } catch (WrappedSQLException wse) {
                    log.error("Creation of user failed with: " + wse.getMessage());
                    HibernateFactory.rollbackTransaction();
                }
            }
            if (remoteUser != null && remoteUser.getPassword().equals(DEFAULT_KERB_USER_PASSWORD)) {
                messages.add(ActionMessages.GLOBAL_MESSAGE,
                        new ActionMessage("message.kerbuserlogged", new String[] { remoteUserString }));
            }
        }
    }
    return remoteUser;
}

From source file:org.apache.hadoop.yarn.server.webapp.WebServices.java

protected static UserGroupInformation getUser(HttpServletRequest req) {
    String remoteUser = req.getRemoteUser();
    UserGroupInformation callerUGI = null;
    if (remoteUser != null) {
        callerUGI = UserGroupInformation.createRemoteUser(remoteUser);
    }/*from ww w . j a  v  a  2 s .  co  m*/
    return callerUGI;
}

From source file:it.geosolutions.geostore.services.rest.auditing.AuditInfoExtractor.java

private static void handleInMessage(Map<String, String> auditInfo, Message message) {
    if (message == null) {
        LogUtils.info(LOGGER, "Input message is NULL.");
        return;//from w  w w.  jav  a  2s. com
    }
    try {
        auditInfo.put(AuditInfo.HTTP_METHOD.getKey(), safeToString(message.get(Message.HTTP_REQUEST_METHOD)));
        auditInfo.put(AuditInfo.PATH.getKey(), removeGeoStore((String) message.get(Message.PATH_INFO)));
        auditInfo.put(AuditInfo.BASE_PATH.getKey(), removeGeoStore((String) message.get(Message.BASE_PATH)));
        auditInfo.put(AuditInfo.QUERY_STRING.getKey(), safeToString(message.get(Message.QUERY_STRING)));
        HttpServletRequest httpServletRequest = (HttpServletRequest) message
                .get(AbstractHTTPDestination.HTTP_REQUEST);
        auditInfo.put(AuditInfo.REMOTE_ADDR.getKey(), safeToString(httpServletRequest.getRemoteAddr()));
        auditInfo.put(AuditInfo.REMOTE_HOST.getKey(), safeToString(httpServletRequest.getRemoteHost()));
        auditInfo.put(AuditInfo.REMOTE_USER.getKey(), safeToString(httpServletRequest.getRemoteUser()));
        auditInfo.put(AuditInfo.HOST.getKey(), safeToString(httpServletRequest.getServerName()));
        fillAuthInfo(auditInfo, httpServletRequest);
        auditInfo.put(AuditInfo.BODY_AS_STRING.getKey(), getPaylod(message));
    } catch (Exception exception) {
        LogUtils.error(LOGGER, exception, "Error obtaining auditing information for input message.");
    }
}

From source file:com.gtwm.pb.servlets.ServletUtilMethods.java

/**
 * Log errors with as much information as possible: include user, URL,
 * recursive causes and a stack trace to the original occurence in the
 * application/*from   ww w . j ava2s.  c  om*/
 * 
 * NB Doesn't throw a servletException, that has to be done as well as
 * calling this
 */
public static void logException(Exception ex, HttpServletRequest request, String topLevelMessage) {
    String errorMessage = "";
    if (topLevelMessage != null) {
        errorMessage += topLevelMessage + "\r\n" + " - ";
    }
    errorMessage += ex.toString() + "\r\n";
    errorMessage += " - URL = " + getRequestQuery(request) + "\r\n";
    errorMessage += " - Logged in user: " + request.getRemoteUser() + "\r\n";
    errorMessage += getExceptionCauses(ex);
    logger.error(errorMessage);
}

From source file:org.itracker.web.util.LoginUtilities.java

/**
 * get current user from request-attribute currUser, if not set from request-session
 *
 * @return current user or null if unauthenticated
 * @throws NullPointerException if the request was null
 *//*from w  w  w . j  a  va 2  s . c  om*/
@Deprecated
public static User getCurrentUser(HttpServletRequest request) {

    final String remoteUser = request.getRemoteUser();
    if (null == remoteUser) {
        return null;
    }
    User currUser = (User) request.getAttribute("currUser");
    if (null != currUser && currUser.getLogin().equals(remoteUser)) {
        if (logger.isDebugEnabled()) {
            logger.debug("found user in request: " + remoteUser);
        }
    }
    if (null == currUser) {
        currUser = (User) request.getSession().getAttribute("currUser");
        if (null != currUser && currUser.getLogin().equals(remoteUser)) {
            if (logger.isDebugEnabled()) {
                logger.debug("found user in session: " + remoteUser);
            }
        }
    }
    if (null == currUser) {
        currUser = ServletContextUtils.getItrackerServices().getUserService().getUserByLogin(remoteUser);
        if (null != currUser && currUser.getLogin().equals(remoteUser)) {
            if (logger.isDebugEnabled()) {
                logger.debug("found user by login: " + remoteUser);
            }
        }
    }

    return currUser;
}

From source file:com.gtwm.pb.servlets.ServletDataMethods.java

private static void logDataChanges(HttpServletRequest request, DatabaseInfo databaseDefn, String operation)
        throws DisallowedException, ObjectNotFoundException {
    AppUserInfo currentUser = databaseDefn.getAuthManager().getUserByUserName(request, request.getRemoteUser());
    String fullname = currentUser.getForename() + " " + currentUser.getSurname();
    String timestamp = String.format(Locale.UK, "%1$td-%1$tb-%1$tY %1$tH:%1$tM:%1$tS", new Date());
    logger.info(fullname + " (" + currentUser + ") " + operation + " at " + timestamp);
}

From source file:com.edgenius.wiki.util.WikiUtil.java

public static String getUserName() {
    HttpServletRequest request = WebUtil.getRequest();
    if (request != null) {
        return request.getRemoteUser();
    } else {/*from   w  w  w  .  j ava  2 s  .c om*/
        User user = ProxyLoginUtil.getRequester();
        if (user != null) {
            return user.getUsername();
        }
        return null;
    }

}

From source file:jeeves.server.sources.ServiceRequestFactory.java

/**
 * Build up a map of the HTTP headers./*from w  w  w  .j a  va 2 s  .c  o  m*/
 * @param req The web request
 * @return Map of header keys and values.
 */
@SuppressWarnings("unchecked")
private static Map<String, String> extractHeaders(HttpServletRequest req) {
    Map<String, String> headerMap = new HashMap<String, String>();
    for (Enumeration<String> e = req.getHeaderNames(); e.hasMoreElements();) {
        String key = e.nextElement();
        headerMap.put(key, req.getHeader(key));
    }
    // The remote user needs to be saved as a header also
    if (req.getRemoteUser() != null) {
        headerMap.put("REMOTE_USER", req.getRemoteUser());
    }
    return headerMap;
}

From source file:org.apache.qpid.server.management.plugin.HttpManagementUtil.java

public static Subject tryToAuthenticate(HttpServletRequest request,
        HttpManagementConfiguration managementConfig) {
    Subject subject = null;//from ww  w.j  av a 2  s . com
    SocketAddress localAddress = getSocketAddress(request);
    final AuthenticationProvider authenticationProvider = managementConfig
            .getAuthenticationProvider(localAddress);
    SubjectCreator subjectCreator = authenticationProvider.getSubjectCreator(request.isSecure());
    String remoteUser = request.getRemoteUser();

    if (remoteUser != null || authenticationProvider instanceof AnonymousAuthenticationManager) {
        subject = authenticateUser(subjectCreator, remoteUser, null);
    } else if (authenticationProvider instanceof ExternalAuthenticationManager && Collections
            .list(request.getAttributeNames()).contains("javax.servlet.request.X509Certificate")) {
        Principal principal = null;
        X509Certificate[] certificates = (X509Certificate[]) request
                .getAttribute("javax.servlet.request.X509Certificate");
        if (certificates != null && certificates.length != 0) {
            principal = certificates[0].getSubjectX500Principal();

            if (!Boolean.valueOf(String.valueOf(authenticationProvider
                    .getAttribute(ExternalAuthenticationManager.ATTRIBUTE_USE_FULL_DN)))) {
                String username;
                String dn = ((X500Principal) principal).getName(X500Principal.RFC2253);

                username = SSLUtil.getIdFromSubjectDN(dn);
                principal = new UsernamePrincipal(username);
            }

            subject = subjectCreator.createSubjectWithGroups(new AuthenticatedPrincipal(principal));
        }
    } else {
        String header = request.getHeader("Authorization");
        if (header != null) {
            String[] tokens = header.split("\\s");
            if (tokens.length >= 2 && "BASIC".equalsIgnoreCase(tokens[0])) {
                boolean isBasicAuthSupported = false;
                if (request.isSecure()) {
                    isBasicAuthSupported = managementConfig.isHttpsBasicAuthenticationEnabled();
                } else {
                    isBasicAuthSupported = managementConfig.isHttpBasicAuthenticationEnabled();
                }
                if (isBasicAuthSupported) {
                    String base64UsernameAndPassword = tokens[1];
                    String[] credentials = (new String(
                            Base64.decodeBase64(base64UsernameAndPassword.getBytes()))).split(":", 2);
                    if (credentials.length == 2) {
                        subject = authenticateUser(subjectCreator, credentials[0], credentials[1]);
                    }
                }
            }
        }
    }
    return subject;
}

From source file:com.tc.utils.XSPUtils.java

public static String userName() {
    HttpServletRequest req = (HttpServletRequest) XSPUtils.context().getExternalContext().getRequest();
    return req.getRemoteUser();
}