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.security.AuthenticationWithProxyUserFilter.java

/**
 * This method provide the ability to do pre/post tasks
 * in filter chain. Override this method to authorize
 * proxy user between AuthenticationFilter and next filter.
 * @param filterChain the filter chain object.
 * @param request the request object.//  www  .j ava  2s  .c om
 * @param response the response object.
 *
 * @throws IOException
 * @throws ServletException
 */
@Override
protected void doFilter(FilterChain filterChain, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    // authorize proxy user before calling next filter.
    String proxyUser = getDoAs(request);
    if (proxyUser != null) {
        UserGroupInformation realUser = UserGroupInformation.createRemoteUser(request.getRemoteUser());
        UserGroupInformation proxyUserInfo = UserGroupInformation.createProxyUser(proxyUser, realUser);

        try {
            ProxyUsers.authorize(proxyUserInfo, request.getRemoteAddr());
        } catch (AuthorizationException ex) {
            HttpExceptionUtils.createServletExceptionResponse(response, HttpServletResponse.SC_FORBIDDEN, ex);
            // stop filter chain if there is an Authorization Exception.
            return;
        }

        final UserGroupInformation finalProxyUser = proxyUserInfo;
        // Change the remote user after proxy user is authorized.
        request = new HttpServletRequestWrapper(request) {
            @Override
            public String getRemoteUser() {
                return finalProxyUser.getUserName();
            }
        };

    }
    filterChain.doFilter(request, response);
}

From source file:io.hops.hopsworks.api.user.UserService.java

@POST
@Path("updateProfile")
@Produces(MediaType.APPLICATION_JSON)/*www .  j av  a 2s . c om*/
public Response updateProfile(@FormParam("firstName") String firstName, @FormParam("lastName") String lastName,
        @FormParam("telephoneNum") String telephoneNum, @FormParam("toursState") Integer toursState,
        @Context HttpServletRequest req) throws UserException {
    RESTApiJsonResponse json = new RESTApiJsonResponse();

    Users user = userController.updateProfile(req.getRemoteUser(), firstName, lastName, telephoneNum,
            toursState, req);
    UserDTO userDTO = new UserDTO(user);

    json.setSuccessMessage(ResponseMessages.PROFILE_UPDATED);
    json.setData(userDTO);

    return noCacheResponse.getNoCacheResponseBuilder(Response.Status.OK).entity(userDTO).build();
}

From source file:org.opennms.web.controller.alarm.AlarmFilterController.java

public ModelAndView createFavorite(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String error = null;/*from  w w  w  .j av  a2s .  c o  m*/
    try {
        OnmsFilterFavorite favorite = favoriteService.createFavorite(request.getRemoteUser(),
                request.getParameter("favoriteName"),
                FilterUtil.toFilterURL(request.getParameterValues("filter")), OnmsFilterFavorite.Page.ALARM);
        if (favorite != null) {
            ModelAndView successView = list(request, favorite); // success
            //Commented out per request. Left it in, in case we wanted it back later
            //AlertTag.addAlertToRequest(successView, "Favorite was created successfully", AlertType.SUCCESS);
            return successView;
        }
        error = "An error occured while creating the favorite";
    } catch (FilterFavoriteService.FilterFavoriteException ex) {
        error = ex.getMessage();
    }
    ModelAndView errorView = list(request, (OnmsFilterFavorite) null);
    AlertTag.addAlertToRequest(errorView, error, AlertType.ERROR);
    return errorView;
}

From source file:org.nema.medical.mint.server.controller.StudyRootController.java

@RequestMapping(method = RequestMethod.DELETE, value = "/studies/{uuid}")
public void deleteStudy(@PathVariable("uuid") final String uuid, final HttpServletRequest req,
        final HttpServletResponse res) throws IOException {
    final Utils.StudyStatus studyStatus = Utils.validateStudyStatus(studiesRoot, uuid, res, studyDAO);
    if (studyStatus != Utils.StudyStatus.OK) {
        return;/* w w  w.  j ava  2 s .  co m*/
    }

    deleteStudy(uuid, studiesRoot, req.getRemoteUser(), req.getRemoteHost(), changeDAO, studyDAO);
    res.setStatus(204);
}

From source file:com.trendmicro.hdfs.webdav.HDFSWebDAVServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (LOG.isDebugEnabled()) {
        LOG.debug(request.getMethod() + " for '" + request.getRequestURI() + "' from " + request.getRemoteUser()
                + " at " + request.getRemoteAddr());
    }/*w w w.j  a va 2s  .  c  o  m*/
    try {
        super.service(request, response);
    } catch (Exception e) {
        if (e instanceof AccessControlException || e.getCause() instanceof AccessControlException) {
            LOG.info("Insufficient permissions for request for '" + request.getRequestURI() + "' from "
                    + request.getRemoteUser() + " at " + request.getRemoteAddr());
            if (request.getMethod().equalsIgnoreCase("GET")) {
                // Provide a plain 401 response for GETs
                new WebdavResponseImpl(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
            } else {
                // Otherwise send a multistatus response
                MultiStatus ms = new MultiStatus();
                ms.addResponse(new MultiStatusResponse(request.getRequestURL().toString(), 401,
                        "You do not have permission to access this resource."));
                new WebdavResponseImpl(response).sendMultiStatus(ms);
            }
        } else {
            LOG.warn("Exception processing request for '" + request.getRequestURI() + "' from "
                    + request.getRemoteUser() + " at " + request.getRemoteAddr() + " authType "
                    + request.getAuthType(), e);
            new WebdavResponseImpl(response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}

From source file:com.pkrete.locationservice.admin.interceptor.UserSessionInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    // Get current HTTP session
    HttpSession session = request.getSession();
    // Get User object from the session
    User user = (User) session.getAttribute("user");
    // Get remote user from the request
    String remoteUser = request.getRemoteUser();
    // If User is null and remote user is not null,
    // remote user must be added to the session
    if (user == null && remoteUser != null) {
        // Get User object by remote user from DB
        user = usersService.getUser(request.getRemoteUser());
        // If User is still null, stop the handler exceution chain
        if (user == null) {
            logger.warn(/*from  ww w . j ava 2s . co m*/
                    "Unable to find User object matching the remote user \"{}\". Stop handler execution chain.",
                    remoteUser);
            // Logout the current user by forwarding to logout controller
            request.getRequestDispatcher("/logout.htm").forward(request, response);
            // Returning false stops the handler execution chain
            return false;
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Added User object to the session.");
        }
        // Add User object to the session
        session.setAttribute("user", user);
    } else if (user != null && remoteUser != null) {
        // Check that User and remote user are the same
        if (!user.getUsername().equals(remoteUser)) {
            logger.warn(
                    "Current user \"" + user.getUsername()
                            + "\" and remote user \"{}\" don't match. Stop handler execution chain.",
                    remoteUser);
            // Logout the current user by forwarding to logout controller
            request.getRequestDispatcher("/logout.htm").forward(request, response);
            // Stop handler execution chain if they don't match
            return false;
        }
    }
    // Continue handler execution chain
    return true;
}

From source file:edu.wisc.doit.tcrypt.controller.CreateController.java

@RequestMapping(value = "/create", method = RequestMethod.POST)
public ModelAndView createServiceKey(@RequestParam("serviceName") String serviceName,
        @RequestParam("keyLength") int keyLength, HttpServletRequest request) throws Exception {

    ModelAndView modelAndView = new ModelAndView("createServiceKeyDownload");

    //validation/*from   w ww  .ja  va 2 s .co  m*/
    String validationResult = validate(serviceName);
    if (!validationResult.isEmpty()) {
        throw new ValidationException(validationResult);
    }

    try {
        String username = request.getRemoteUser() != null ? request.getRemoteUser() : "UNKNOWNUSERNAME";

        //Create ServiceKey Object and write public key out to FS
        final KeyPair keyPair = keysKeeper.createServiceKey(serviceName, keyLength, username);

        //Add serviceKey object on session (for download) and put the serviceName in the object list
        request.getSession().setAttribute("serviceKey_" + serviceName, keyPair);
        modelAndView.addObject("serviceName", serviceName);
    } catch (Exception e) {
        logger.error("An error occurred when creating a service key", e);
        throw new ServiceErrorException(serviceName, "error.createServiceKey");
    }

    return modelAndView;
}

From source file:org.kuali.coeus.sys.framework.controller.interceptor.RequestLoggingFilter.java

/**
 * <p>Does the actual logging. The log4j.properties file already covers user and date/time logging for us, so the
 * only thing that gets logged in <b>INFO</b> here is the intended action.</p>
 * //from   w  w w  .jav  a  2s .c  om
 * <p><b>Inefficiency:</b>Currently, an action map is being used
 * to determine the intended action of the user.</p>
 * 
 * <p>This is a convenience method so avoid redeclaration of variables.</p>
 *
 * @param request cast from ServletRequest
 * @param response cast from ServletResponse
 * @see #doFilter(ServletRequest,ServletResponse,FilterChain)
 */
private void doFilter(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    MDC.put("clientIp", request.getRemoteAddr());
    if (LOG.isInfoEnabled()) {
        final String logMessage = "Current User: " + request.getRemoteUser() + ", RequestURI: "
                + request.getRequestURI() + ", Logged-By-Default Parameters: "
                + getRequestParametersMessage(request, SENSITIVE_FILEDS_FILTER, paramsToLogInfoByDefault);

        LOG.info(logMessage);
    }

    if (LOG.isDebugEnabled()) {
        final String logMessage = "\n***************************** HEADERS **********************************\n"
                + getRequestHeadersMessage(request)
                + "\n***************************** PARAMETERS *******************************\n"
                + getRequestParametersMessage(request, SENSITIVE_FILEDS_FILTER)
                + "\n***************************** ATTRIBUTES *******************************\n"
                + getRequestAttributesMessage(request);
        LOG.debug(logMessage);
    }

}

From source file:org.opennms.web.controller.alarm.AlarmFilterController.java

public ModelAndView deleteFavorite(HttpServletRequest request, HttpServletResponse response) throws Exception {
    // delete//from   ww w  . j a  va2s. c o  m
    String favoriteId = request.getParameter("favoriteId");
    boolean success = favoriteService.deleteFavorite(favoriteId, request.getRemoteUser());

    ModelAndView resultView = list(request, (OnmsFilterFavorite) null);
    resultView.addObject("favorite", null); // we deleted the favorite
    if (!StringUtils.isEmpty(request.getParameter("redirect"))) {
        resultView.setViewName(request.getParameter("redirect")); // change to redirect View
    }

    if (!success) {
        AlertTag.addAlertToRequest(resultView, "Favorite couldn't be deleted.", AlertType.ERROR);
    } else {
        AlertTag.addAlertToRequest(resultView, "Favorite deleted successfully.", AlertType.SUCCESS);
    }
    return resultView;
}

From source file:de.fhg.fokus.openride.services.favoritepoint.FavoritePointService.java

@DELETE
@Path("{displayName}/")
@Produces("text/json")
public Response removeFavoritePoint(@Context HttpServletRequest con, @PathParam("username") String username,
        @PathParam("displayName") String displayName) {

    System.out.println("removeFavoritePoint start");

    // check if remote user == {username} in path param
    if (!username.equals(con.getRemoteUser())) {
        return Response.status(Response.Status.FORBIDDEN).build();
    }/*from  w w  w  .ja  va  2 s  . com*/

    CustomerEntity c = customerControllerBean.getCustomerByNickname(username);

    FavoritePointEntity point;
    try {
        point = favoritePointControllerBean
                .getFavoritePointByDisplayName(URLDecoder.decode(displayName, "UTF-8"), c);

        if (point != null) {
            favoritePointControllerBean.removeFavoritePoint(point.getFavptId());
        } else {
            // A favpt of the given displayName does not exist for this customer
            return Response.status(Response.Status.NOT_FOUND).build();
        }

    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(FavoritePointService.class.getName()).log(Level.SEVERE, null, ex);
        return Response.serverError().build();
    }

    return Response.ok().build();

}