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:org.apache.hadoop.mapred.JSPUtil.java

/**
 * Method used to process the request from the job page based on the 
 * request which it has received. For example like changing priority.
 * /*from ww w.j  ava2s  . c  om*/
 * @param request HTTP request Object.
 * @param response HTTP response object.
 * @param tracker {@link JobTracker} instance
 * @throws IOException
 * @throws InterruptedException 
 * @throws ServletException 
 */
public static void processButtons(HttpServletRequest request, HttpServletResponse response,
        final JobTracker tracker) throws IOException, InterruptedException, ServletException {

    String user = request.getRemoteUser();
    if (privateActionsAllowed(tracker.conf) && request.getParameter("killJobs") != null) {
        String[] jobs = request.getParameterValues("jobCheckBox");
        if (jobs != null) {
            boolean notAuthorized = false;
            String errMsg = "User " + user + " failed to kill the following job(s)!<br><br>";
            for (String job : jobs) {
                final JobID jobId = JobID.forName(job);
                if (user != null) {
                    UserGroupInformation ugi = UserGroupInformation.createRemoteUser(user);
                    try {
                        ugi.doAs(new PrivilegedExceptionAction<Void>() {
                            public Void run() throws IOException {

                                tracker.killJob(jobId);// checks job modify permission
                                return null;
                            }
                        });
                    } catch (AccessControlException e) {
                        errMsg = errMsg.concat("<br>" + e.getMessage());
                        notAuthorized = true;
                        // We don't return right away so that we can try killing other
                        // jobs that are requested to be killed.
                        continue;
                    }
                } else {// no authorization needed
                    tracker.killJob(jobId);
                }
            }
            if (notAuthorized) {// user is not authorized to kill some/all of jobs
                errMsg = errMsg.concat("<br><hr><a href=\"jobtracker.jsp\">Go back to JobTracker</a><br>");
                setErrorAndForward(errMsg, request, response);
                return;
            }
        }
    }

    if (privateActionsAllowed(tracker.conf) && request.getParameter("changeJobPriority") != null) {
        String[] jobs = request.getParameterValues("jobCheckBox");
        if (jobs != null) {
            final JobPriority jobPri = JobPriority.valueOf(request.getParameter("setJobPriority"));
            boolean notAuthorized = false;
            String errMsg = "User " + user + " failed to set priority for the following job(s)!<br><br>";

            for (String job : jobs) {
                final JobID jobId = JobID.forName(job);
                if (user != null) {
                    UserGroupInformation ugi = UserGroupInformation.createRemoteUser(user);
                    try {
                        ugi.doAs(new PrivilegedExceptionAction<Void>() {
                            public Void run() throws IOException {

                                // checks job modify permission
                                tracker.setJobPriority(jobId, jobPri);
                                return null;
                            }
                        });
                    } catch (AccessControlException e) {
                        errMsg = errMsg.concat("<br>" + e.getMessage());
                        notAuthorized = true;
                        // We don't return right away so that we can try operating on
                        // other jobs.
                        continue;
                    }
                } else {// no authorization needed
                    tracker.setJobPriority(jobId, jobPri);
                }
            }
            if (notAuthorized) {// user is not authorized to kill some/all of jobs
                errMsg = errMsg.concat("<br><hr><a href=\"jobtracker.jsp\">Go back to JobTracker</a><br>");
                setErrorAndForward(errMsg, request, response);
                return;
            }
        }
    }
}

From source file:org.eclipse.orion.internal.server.servlets.workspace.WorkspaceResourceHandler.java

public static void computeProjectLocation(HttpServletRequest request, ProjectInfo project, String location,
        boolean init) throws CoreException {
    String user = request.getRemoteUser();
    URI contentURI;/*w  w  w  . ja v a  2 s  .  co  m*/
    if (location == null) {
        contentURI = generateProjectLocation(project, user);
    } else {
        //use the content location specified by the user
        try {
            contentURI = new URI(location);
            EFS.getFileSystem(contentURI.getScheme());//check if we support this scheme
        } catch (Exception e) {
            //if this is not a valid URI or scheme try to parse it as file path
            contentURI = new File(location).toURI();
        }
        if (init) {
            project.setContentLocation(contentURI);
            IFileStore child = NewFileServlet.getFileStore(request, project);
            child.mkdir(EFS.NONE, null);
        }
    }
    project.setContentLocation(contentURI);
}

From source file:org.apache.hadoop.mapred.JSPUtil.java

/**
 * Validates if current user can view the job.
 * If user is not authorized to view the job, this method will modify the
 * response and forwards to an error page and returns Job with
 * viewJobAccess flag set to false./*from   w w  w.ja v  a  2 s . c  o m*/
 * @return JobWithViewAccessCheck object(contains JobInProgress object and
 *         viewJobAccess flag). Callers of this method will check the flag
 *         and decide if view should be allowed or not. Job will be null if
 *         the job with given jobid doesnot exist at the JobTracker.
 */
public static JobWithViewAccessCheck checkAccessAndGetJob(final JobTracker jt, JobID jobid,
        HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    final JobInProgress job = jt.getJob(jobid);
    JobWithViewAccessCheck myJob = new JobWithViewAccessCheck(job);

    String user = request.getRemoteUser();
    if (user != null && job != null && jt.areACLsEnabled()) {
        final UserGroupInformation ugi = UserGroupInformation.createRemoteUser(user);
        try {
            ugi.doAs(new PrivilegedExceptionAction<Void>() {
                public Void run() throws IOException, ServletException {

                    // checks job view permission
                    jt.getACLsManager().checkAccess(job, ugi, Operation.VIEW_JOB_DETAILS);
                    return null;
                }
            });
        } catch (AccessControlException e) {
            String errMsg = "User " + ugi.getShortUserName() + " failed to view " + jobid + "!<br><br>"
                    + e.getMessage() + "<hr><a href=\"jobtracker.jsp\">Go back to JobTracker</a><br>";
            JSPUtil.setErrorAndForward(errMsg, request, response);
            myJob.setViewAccess(false);
        } catch (InterruptedException e) {
            String errMsg = " Interrupted while trying to access " + jobid
                    + "<hr><a href=\"jobtracker.jsp\">Go back to JobTracker</a><br>";
            JSPUtil.setErrorAndForward(errMsg, request, response);
            myJob.setViewAccess(false);
        }
    }
    return myJob;
}

From source file:org.apache.hadoop.mapred.JSPUtil.java

/**
 * Check the access for users to view job-history pages.
 * /* www .ja va  2s.  c o  m*/
 * @param request
 * @param response
 * @param fs
 * @param logFile
 * @return the job if authorization is disabled or if the authorization checks
 *         pass. Otherwise return null.
 * @throws IOException
 * @throws InterruptedException
 * @throws ServletException
 */
static JobInfo checkAccessAndGetJobInfo(HttpServletRequest request, HttpServletResponse response,
        final JobConf jobConf, final ACLsManager acLsManager, final FileSystem fs, final Path logFile)
        throws IOException, InterruptedException, ServletException {
    String jobid = getJobID(logFile.getName());
    String user = request.getRemoteUser();
    JobInfo job = null;
    if (user != null) {
        try {
            job = JSPUtil.getJobInfo(logFile, fs, jobConf, acLsManager, user);
        } catch (AccessControlException e) {
            String trackerAddress = jobConf.get("mapred.job.tracker.http.address");
            String errMsg = String.format(
                    "User %s failed to view %s!<br><br>%s" + "<hr>"
                            + "<a href=\"jobhistory.jsp\">Go back to JobHistory</a><br>" + "<a href=\"http://"
                            + trackerAddress + "/jobtracker.jsp\">Go back to JobTracker</a>",
                    user, jobid, e.getMessage());
            JSPUtil.setErrorAndForward(errMsg, request, response);
            return null;
        }
    } else {
        // no authorization needed
        job = JSPUtil.getJobInfo(logFile, fs, jobConf, acLsManager, null);
    }
    return job;
}

From source file:org.apache.hive.http.HttpServer.java

/**
 * Does the user sending the HttpServletRequest have the administrator ACLs? If
 * it isn't the case, response will be modified to send an error to the user.
 *
 * @param servletContext/*from ww  w  .j  a v  a  2s.  c om*/
 * @param request
 * @param response used to send the error response if user does not have admin access.
 * @return true if admin-authorized, false otherwise
 * @throws IOException
 */
static boolean hasAdministratorAccess(ServletContext servletContext, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    Configuration conf = (Configuration) servletContext.getAttribute(CONF_CONTEXT_ATTRIBUTE);
    // If there is no authorization, anybody has administrator access.
    if (!conf.getBoolean(CommonConfigurationKeys.HADOOP_SECURITY_AUTHORIZATION, false)) {
        return true;
    }

    String remoteUser = request.getRemoteUser();
    if (remoteUser == null) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                "Unauthenticated users are not " + "authorized to access this page.");
        return false;
    }

    if (servletContext.getAttribute(ADMINS_ACL) != null
            && !userHasAdministratorAccess(servletContext, remoteUser)) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                "User " + remoteUser + " is unauthorized to access this page.");
        return false;
    }

    return true;
}

From source file:org.apache.hadoop.hdfs.server.common.JspHelper.java

/**
 * Get {@link UserGroupInformation} and possibly the delegation token out of
 * the request.//from   w w  w . ja v a 2s  . c o  m
 *
 * @param context
 *     the ServletContext that is serving this request.
 * @param request
 *     the http request
 * @param conf
 *     configuration
 * @param secureAuthMethod
 *     the AuthenticationMethod used in secure mode.
 * @param tryUgiParameter
 *     Should it try the ugi parameter?
 * @return a new user from the request
 * @throws AccessControlException
 *     if the request has no token
 */
public static UserGroupInformation getUGI(ServletContext context, HttpServletRequest request,
        Configuration conf, final AuthenticationMethod secureAuthMethod, final boolean tryUgiParameter)
        throws IOException {
    UserGroupInformation ugi = null;
    final String usernameFromQuery = getUsernameFromQuery(request, tryUgiParameter);
    final String doAsUserFromQuery = request.getParameter(DoAsParam.NAME);
    final String remoteUser;

    if (UserGroupInformation.isSecurityEnabled()) {
        remoteUser = request.getRemoteUser();
        final String tokenString = request.getParameter(DELEGATION_PARAMETER_NAME);
        if (tokenString != null) {
            // Token-based connections need only verify the effective user, and
            // disallow proxying to different user.  Proxy authorization checks
            // are not required since the checks apply to issuing a token.
            ugi = getTokenUGI(context, request, tokenString, conf);
            checkUsername(ugi.getShortUserName(), usernameFromQuery);
            checkUsername(ugi.getShortUserName(), doAsUserFromQuery);
        } else if (remoteUser == null) {
            throw new IOException("Security enabled but user not authenticated by filter");
        }
    } else {
        // Security's not on, pull from url or use default web user
        remoteUser = (usernameFromQuery == null) ? getDefaultWebUserName(conf)
                // not specified in request
                : usernameFromQuery;
    }

    if (ugi == null) { // security is off, or there's no token
        ugi = UserGroupInformation.createRemoteUser(remoteUser);
        checkUsername(ugi.getShortUserName(), usernameFromQuery);
        if (UserGroupInformation.isSecurityEnabled()) {
            // This is not necessarily true, could have been auth'ed by user-facing
            // filter
            ugi.setAuthenticationMethod(secureAuthMethod);
        }
        if (doAsUserFromQuery != null) {
            // create and attempt to authorize a proxy user
            ugi = UserGroupInformation.createProxyUser(doAsUserFromQuery, ugi);
            ProxyUsers.authorize(ugi, getRemoteAddr(request), conf);
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("getUGI is returning: " + ugi.getShortUserName());
    }
    return ugi;
}

From source file:org.opennms.web.svclayer.outage.CurrentOutageParseResponse.java

/**
 * <p>findSelectedOutagesIDs</p>
 *
 * @param request a {@link javax.servlet.http.HttpServletRequest} object.
 * @param outageService a {@link org.opennms.web.svclayer.outage.OutageService} object.
 * @return a java$util$Map object./*from   w  ww.j  a  va 2  s . c  o m*/
 */
public static Map<String, String> findSelectedOutagesIDs(HttpServletRequest request,
        OutageService outageService) {
    Map<String, String> myOutages = new HashMap<String, String>();
    @SuppressWarnings("unchecked")
    Enumeration<String> parameterNames = request.getParameterNames();

    while (parameterNames.hasMoreElements()) {
        String parameterName = parameterNames.nextElement();
        if (parameterName.startsWith("chkbx_")) {
            String outageId = StringUtils.substringAfter(parameterName, "chkbx_");
            String parameterValue = request.getParameter(parameterName);
            if (parameterValue.equals(SuppressOutageCheckBoxConstants.SELECTED)) {
                m_suppress.suppress(WebSecurityUtils.safeParseInt(outageId),
                        request.getParameter("suppresstime_" + outageId), outageService,
                        request.getRemoteUser().toString());

                myOutages.remove(outageId);
            } else {
                myOutages.remove(outageId);
            }
        }
    }

    return myOutages;
}

From source file:org.wte4j.ui.auth.server.AuthController.java

@RequestMapping(value = "isLoggedIn", method = RequestMethod.GET, produces = "application/json")
public boolean isLoggedIn(HttpServletRequest request) throws Exception {
    return (request.getRemoteUser() != null);
}

From source file:org.apache.hadoop.hdfs.server.namenode.JspHelper.java

/**
 * Get {@link UserGroupInformation} and possibly the delegation token out of
 * the request./*from   w w w .jav  a2  s .co m*/
 * @param context the Servlet context
 * @param request the http request
 * @param conf configuration
 * @param secureAuthMethod the AuthenticationMethod used in secure mode.
 * @param tryUgiParameter Should it try the ugi parameter?
 * @return a new user from the request
 * @throws AccessControlException if the request has no token
 */
public static UserGroupInformation getUGI(ServletContext context, HttpServletRequest request,
        Configuration conf, final AuthenticationMethod secureAuthMethod, final boolean tryUgiParameter)
        throws IOException {
    final UserGroupInformation ugi;
    final String usernameFromQuery = getUsernameFromQuery(request, tryUgiParameter);
    final String doAsUserFromQuery = request.getParameter(DoAsParam.NAME);

    if (UserGroupInformation.isSecurityEnabled()) {
        final String remoteUser = request.getRemoteUser();
        String tokenString = request.getParameter(DELEGATION_PARAMETER_NAME);
        if (tokenString != null) {
            Token<DelegationTokenIdentifier> token = new Token<DelegationTokenIdentifier>();
            token.decodeFromUrlString(tokenString);
            SecurityUtil.setTokenService(token, NameNode.getAddress(conf));
            token.setKind(DelegationTokenIdentifier.HDFS_DELEGATION_KIND);

            ByteArrayInputStream buf = new ByteArrayInputStream(token.getIdentifier());
            DataInputStream in = new DataInputStream(buf);
            DelegationTokenIdentifier id = new DelegationTokenIdentifier();
            id.readFields(in);
            if (context != null) {
                NameNode nn = (NameNode) context.getAttribute("name.node");
                if (nn != null) {
                    //Verify the token.
                    nn.getNamesystem().getDelegationTokenSecretManager().verifyToken(id, token.getPassword());
                }
            }
            ugi = id.getUser();
            if (ugi.getRealUser() == null) {
                //non-proxy case
                checkUsername(ugi.getShortUserName(), usernameFromQuery);
                checkUsername(null, doAsUserFromQuery);
            } else {
                //proxy case
                checkUsername(ugi.getRealUser().getShortUserName(), usernameFromQuery);
                checkUsername(ugi.getShortUserName(), doAsUserFromQuery);
                ProxyUsers.authorize(ugi, request.getRemoteAddr(), conf);
            }
            ugi.addToken(token);
            ugi.setAuthenticationMethod(AuthenticationMethod.TOKEN);
        } else {
            if (remoteUser == null) {
                throw new IOException("Security enabled but user not " + "authenticated by filter");
            }
            final UserGroupInformation realUgi = UserGroupInformation.createRemoteUser(remoteUser);
            checkUsername(realUgi.getShortUserName(), usernameFromQuery);
            // This is not necessarily true, could have been auth'ed by user-facing
            // filter
            realUgi.setAuthenticationMethod(secureAuthMethod);
            ugi = initUGI(realUgi, doAsUserFromQuery, request, true, conf);
        }
    } else { // Security's not on, pull from url
        final UserGroupInformation realUgi = usernameFromQuery == null ? getDefaultWebUser(conf) // not specified in request
                : UserGroupInformation.createRemoteUser(usernameFromQuery);
        realUgi.setAuthenticationMethod(AuthenticationMethod.SIMPLE);
        ugi = initUGI(realUgi, doAsUserFromQuery, request, false, conf);
    }

    if (LOG.isDebugEnabled())
        LOG.debug("getUGI is returning: " + ugi.getShortUserName());
    return ugi;
}

From source file:com.indeed.imhotep.web.QueryServlet.java

/**
 * Gets the user name from the HTTP request if it was provided through Basic authentication.
 * // ww  w  .  ja  v  a 2 s  .  co  m
 * @param request Http request
 * @return User name if Basic auth is used or null otherwise
 */
private static String getUserNameFromRequest(final HttpServletRequest request) {
    final String authHeader = request.getHeader("Authorization");
    if (authHeader == null) {
        // try simple
        final String rawUser = request.getRemoteUser();
        if (rawUser == null) {
            return null;
        } else {
            return rawUser;
        }
    } else {
        final String credStr;
        if (authHeader.startsWith("user ")) {
            credStr = authHeader.substring(5);
        } else {
            // try basic auth
            if (!authHeader.toUpperCase().startsWith("BASIC ")) {
                // Not basic
                return null;
            }

            // remove basic
            final String credEncoded = authHeader.substring(6); //length of 'BASIC '

            final byte[] credRaw = Base64.decodeBase64(credEncoded.getBytes());
            if (credRaw == null) {
                // invalid decoding
                return null;
            }

            credStr = new String(credRaw);
        }

        // get username part from username:password
        final String[] x = credStr.split(":");
        if (x.length < 1) {
            // bad split
            return null;
        }

        return x[0];
    }
}