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:eu.europa.ec.fisheries.uvms.reporting.rest.resources.ReportingResource.java

@POST
@Path("/default/{id}")
@Produces(APPLICATION_JSON)//from   w  ww.  jav  a 2  s . c om
@Consumes(APPLICATION_JSON)
public Response defaultReport(@Context HttpServletRequest request, @PathParam("id") Long id,
        @HeaderParam("scopeName") String scopeName, @HeaderParam("roleName") String roleName,
        Map<String, Object> payload) {

    final String username = request.getRemoteUser();
    final String appName = getApplicationName(request);
    Boolean override = false;

    if (payload != null) {
        override = Boolean.valueOf(String.valueOf(payload.get("override")));
    }

    Response response;
    try {

        String defaultId = usmService.getUserPreference(DEFAULT_REPORT_ID, username, appName, roleName,
                scopeName);

        if (!StringUtils.isEmpty(defaultId) && !override) {
            response = createErrorResponse("TRYING TO OVERRIDE ALREADY EXISTING VALUE");
        } else {
            usmService.putUserPreference(DEFAULT_REPORT_ID, String.valueOf(id), appName, scopeName, roleName,
                    username);
            response = createSuccessResponse();
        }

    } catch (ServiceException e) {
        log.error("Default report saving failed.", e);
        response = createErrorResponse(e.getMessage());
    }

    return response;
}

From source file:com.ikon.servlet.admin.ConfigServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doGet({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String action = WebUtils.getString(request, "action");
    String filter = WebUtils.getString(request, "filter");
    String userId = request.getRemoteUser();
    updateSessionManager(request);/*from  w  w  w  .  j  a va2  s  . c om*/

    try {
        if (action.equals("create")) {
            create(userId, types, request, response);
        } else if (action.equals("edit")) {
            edit(userId, types, request, response);
        } else if (action.equals("delete")) {
            delete(userId, types, request, response);
        } else if (action.equals("check")) {
            check(userId, request, response);
        } else if (action.equals("export")) {
            export(userId, request, response);
        } else {
            list(userId, filter, request, response);
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    }
}

From source file:cn.bc.web.util.DebugUtils.java

public static StringBuffer getDebugInfo(HttpServletRequest request, HttpServletResponse response) {
    @SuppressWarnings("rawtypes")
    Enumeration e;//from  w w  w . j  av  a 2s .  c  o  m
    String name;
    StringBuffer html = new StringBuffer();

    //session
    HttpSession session = request.getSession();
    html.append("<div><b>session:</b></div><ul>");
    html.append(createLI("Id", session.getId()));
    html.append(createLI("CreationTime", new Date(session.getCreationTime()).toString()));
    html.append(createLI("LastAccessedTime", new Date(session.getLastAccessedTime()).toString()));

    //session:attributes
    e = session.getAttributeNames();
    html.append("<li>attributes:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, String.valueOf(session.getAttribute(name))));
    }
    html.append("</ul></li>\r\n");
    html.append("</ul>\r\n");

    //request
    html.append("<div><b>request:</b></div><ul>");
    html.append(createLI("URL", request.getRequestURL().toString()));
    html.append(createLI("QueryString", request.getQueryString()));
    html.append(createLI("Method", request.getMethod()));
    html.append(createLI("CharacterEncoding", request.getCharacterEncoding()));
    html.append(createLI("ContentType", request.getContentType()));
    html.append(createLI("Protocol", request.getProtocol()));
    html.append(createLI("RemoteAddr", request.getRemoteAddr()));
    html.append(createLI("RemoteHost", request.getRemoteHost()));
    html.append(createLI("RemotePort", request.getRemotePort() + ""));
    html.append(createLI("RemoteUser", request.getRemoteUser()));
    html.append(createLI("ServerName", request.getServerName()));
    html.append(createLI("ServletPath", request.getServletPath()));
    html.append(createLI("ServerPort", request.getServerPort() + ""));
    html.append(createLI("Scheme", request.getScheme()));
    html.append(createLI("LocalAddr", request.getLocalAddr()));
    html.append(createLI("LocalName", request.getLocalName()));
    html.append(createLI("LocalPort", request.getLocalPort() + ""));
    html.append(createLI("Locale", request.getLocale().toString()));

    //request:headers
    e = request.getHeaderNames();
    html.append("<li>Headers:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, request.getHeader(name)));
    }
    html.append("</ul></li>\r\n");

    //request:parameters
    e = request.getParameterNames();
    html.append("<li>Parameters:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, request.getParameter(name)));
    }
    html.append("</ul></li>\r\n");

    html.append("</ul>\r\n");

    //response
    html.append("<div><b>response:</b></div><ul>");
    html.append(createLI("CharacterEncoding", response.getCharacterEncoding()));
    html.append(createLI("ContentType", response.getContentType()));
    html.append(createLI("BufferSize", response.getBufferSize() + ""));
    html.append(createLI("Locale", response.getLocale().toString()));
    html.append("<ul>\r\n");
    return html;
}

From source file:org.eclipse.orion.server.authentication.formpersona.PersonaHelper.java

/**
 * If the request appears to be from a loopback interface, returns an audience constructed from the server name.
 * Otherwise returns null.//from   w w w  .  ja  v  a2s  . c  o m
 */
private String getLoopbackAudience(HttpServletRequest req) throws PersonaException {
    try {
        String serverName = req.getServerName();
        try {
            // First ensure the request is coming from the IP of a loopback device
            if (isLoopback(InetAddress.getByName(req.getLocalAddr()))) {
                // Verify that the server name resolves to a loopback device, to prevent spoofing/proxying
                InetAddress addr = InetAddress.getByName(serverName);
                if (isLoopback(addr))
                    return new URI(req.getScheme(), req.getRemoteUser(), serverName, req.getServerPort(), null,
                            null, null).toString();
            }
        } catch (UnknownHostException e) {
            // Bogus serverName, ignore
        }
    } catch (URISyntaxException e) {
        throw new PersonaException(e);
    }
    return null;
}

From source file:org.apache.hadoop.yarn.server.webproxy.WebAppProxyServlet.java

/**
 * Download link and have it be the response.
 * @param req the http request// w ww .  j av a 2s . co  m
 * @param resp the http response
 * @param link the link to download
 * @param c the cookie to set if any
 * @throws IOException on any error.
 */
private static void proxyLink(HttpServletRequest req, HttpServletResponse resp, URI link, Cookie c,
        String proxyHost) throws IOException {
    org.apache.commons.httpclient.URI uri = new org.apache.commons.httpclient.URI(link.toString(), false);
    HttpClientParams params = new HttpClientParams();
    params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
    HttpClient client = new HttpClient(params);
    // Make sure we send the request from the proxy address in the config
    // since that is what the AM filter checks against. IP aliasing or
    // similar could cause issues otherwise.
    HostConfiguration config = new HostConfiguration();
    InetAddress localAddress = InetAddress.getByName(proxyHost);
    if (LOG.isDebugEnabled()) {
        LOG.debug("local InetAddress for proxy host: " + localAddress.toString());
    }
    config.setLocalAddress(localAddress);
    HttpMethod method = new GetMethod(uri.getEscapedURI());
    @SuppressWarnings("unchecked")
    Enumeration<String> names = req.getHeaderNames();
    while (names.hasMoreElements()) {
        String name = names.nextElement();
        if (passThroughHeaders.contains(name)) {
            String value = req.getHeader(name);
            LOG.debug("REQ HEADER: " + name + " : " + value);
            method.setRequestHeader(name, value);
        }
    }

    String user = req.getRemoteUser();
    if (user != null && !user.isEmpty()) {
        method.setRequestHeader("Cookie", PROXY_USER_COOKIE_NAME + "=" + URLEncoder.encode(user, "ASCII"));
    }
    OutputStream out = resp.getOutputStream();
    try {
        resp.setStatus(client.executeMethod(config, method));
        for (Header header : method.getResponseHeaders()) {
            resp.setHeader(header.getName(), header.getValue());
        }
        if (c != null) {
            resp.addCookie(c);
        }
        InputStream in = method.getResponseBodyAsStream();
        if (in != null) {
            IOUtils.copyBytes(in, out, 4096, true);
        }
    } finally {
        method.releaseConnection();
    }
}

From source file:com.sixt.service.framework.jetty.RpcReadException.java

public String toJson(HttpServletRequest req) {
    JsonObject obj = new JsonObject();

    Enumeration<String> h = req.getHeaderNames();
    while (h.hasMoreElements()) {
        String hKey = h.nextElement();
        String hValue = req.getHeader(hKey);
        obj.addProperty("request_header_" + hKey, hValue);
    }/*from w  ww  . j  a  va 2  s.c  o m*/

    obj.addProperty("exception_message", this.getMessage());
    obj.addProperty("request_query_string", req.getQueryString());
    obj.addProperty("request_url", req.getRequestURL().toString());
    obj.addProperty("request_remote_addr", req.getRemoteAddr());
    obj.addProperty("request_remote_port", req.getRemotePort());
    obj.addProperty("request_remote_host", req.getRemoteHost());
    obj.addProperty("request_remote_user", req.getRemoteUser());

    String readBody = "success";
    // read the whole remaining body and put the joined base64 encoded message into the json object
    try {
        byte[] ba = IOUtils.toByteArray(this.in);
        byte[] combined;
        if ((ba != null) && (this.incomplete != null)) {
            combined = new byte[ba.length + this.incomplete.length];
            System.arraycopy(incomplete, 0, combined, 0, this.incomplete.length);
            System.arraycopy(ba, 0, combined, this.incomplete.length, ba.length);
            obj.addProperty("request_body", Base64.getEncoder().encodeToString(combined));
        } else if (ba != null) {
            combined = ba;
        } else if (this.incomplete != null) {
            combined = this.incomplete;
        } else {
            readBody = "body is empty";
        }
    } catch (Exception ex) {
        readBody = String.format("failed because: %s", ex.getCause());
    }
    obj.addProperty("read_body", readBody);

    return obj.toString();
}

From source file:oculus.memex.rest.PreclusterDetailsResource.java

@GET
@Path("{preclusterType}/{clusterId}")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public ClusterDetailsResult handleGet(@PathParam("preclusterType") String preclusterType,
        @PathParam("clusterId") Integer clusterId, @Context HttpServletRequest request) {
    List<DataRow> results = new ArrayList<DataRow>();
    TimeLog log = new TimeLog();
    log.pushTime("Precluster details: " + preclusterType + ":" + clusterId);
    log.pushTime("Fetch Ad IDs");
    HashSet<Integer> members = new HashSet<Integer>();
    Cluster.getAdsInCluster(clusterId, members, 2000);
    log.popTime();/*w ww.j  a v a  2  s  .  c  o m*/
    log.pushTime("Fetch Ad Contents");
    getDetails(members, results, request.getRemoteUser());
    log.popTime();

    log.pushTime("Prepare results");

    ArrayList<HashMap<String, String>> details = DataUtil.sanitizeHtml(results);

    ArrayList<StringMap> serializableDetails = new ArrayList<StringMap>();
    for (HashMap<String, String> map : details) {
        serializableDetails.add(new StringMap(map));
    }
    log.popTime();
    log.popTime();
    return new ClusterDetailsResult(serializableDetails);
}

From source file:com.stormcloud.ide.api.filter.UserFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {

    try {/*from  w w w .j  a  v a  2  s  .com*/

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        LOG.info("Filter Request [" + request.getRemoteAddr() + "]");

        MDC.put("api", httpRequest.getRequestURI());

        if (httpRequest.getRequestURI().endsWith("/api/login")) {

            // configure MDC for the remainging trip
            MDC.put("userName", httpRequest.getRemoteUser());

            LOG.debug("Login Request.");

            // it's a login request which succeeded (Basic Auth)
            // so we now need to genereate an authentication token
            // and store it in a cookie we sent back
            // create the cookie with key for consecutive Rest API Calls

            // Get user from db and add to the localthread
            User user = dao.getUser(httpRequest.getRemoteUser());

            if (user == null) {

                LOG.error("User not found.");
                httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                httpResponse.flushBuffer();
                return;
            }

            // update last login
            user.setLastLogin(Calendar.getInstance().getTime());

            dao.save(user);

            RemoteUser.set(user);

            try {

                // set the key cookie
                Cookie keyCookie = new Cookie("stormcloud-key", createKey(user, httpRequest.getRemoteAddr()));

                keyCookie.setMaxAge(60 * 60 * 24); // 1 day

                keyCookie.setPath("/");
                keyCookie.setSecure(true);

                httpResponse.addCookie(keyCookie);

                // set the username cookie
                Cookie userCookie = new Cookie("stormcloud-user", user.getUserName());

                userCookie.setMaxAge(60 * 60 * 24); // 1 day

                userCookie.setPath("/");
                userCookie.setSecure(true);

                httpResponse.addCookie(userCookie);

            } catch (NoSuchAlgorithmException e) {

                LOG.error(e);

                try {

                    // no go
                    httpResponse.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());

                    httpResponse.flushBuffer();
                    return;

                } catch (IOException ioe) {
                    LOG.error(ioe);
                }
            }

        } else if (httpRequest.getRequestURI().endsWith("/api/user/createAccount")) {

            // intercept and do something with create account
            LOG.debug("Create Account Request.");

        } else {

            LOG.info("API Request.");

            // any other request than a login
            // we need to check the username and received key
            Cookie[] cookies = httpRequest.getCookies();

            String userName = null;
            String key = null;

            if (cookies != null) {

                LOG.info("Found " + cookies.length + " Cookies");

                // loop trough the cookies
                for (int i = 0; i < cookies.length; i++) {

                    if (cookies[i].getName().equals("stormcloud-user")) {

                        LOG.debug("userName = " + cookies[i].getValue());
                        userName = cookies[i].getValue();
                    }

                    if (cookies[i].getName().equals("stormcloud-key")) {

                        LOG.debug("key = " + cookies[i].getValue());
                        key = cookies[i].getValue();
                    }
                }
            }

            if (userName == null || key == null) {

                LOG.info("Required credentials not found.");
                httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                httpResponse.flushBuffer();
                return;

            } else {

                // configure MDC for the remainging trip
                MDC.put("userName", userName);

                // get user
                LOG.debug("Get Persisted User");
                User user = dao.getUser(userName);

                if (user == null) {
                    httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                    httpResponse.flushBuffer();
                    return;
                }

                RemoteUser.set(user);

                try {

                    String matchKey = createKey(user, httpRequest.getRemoteAddr());

                    LOG.info("Validating Key.");

                    if (!matchKey.equals(key)) {

                        LOG.warn("Invalid Key!");
                        httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                        httpResponse.flushBuffer();
                        return;

                    } else {

                        LOG.info("Request Authenticated");
                    }

                } catch (NoSuchAlgorithmException e) {

                    LOG.error(e);

                    try {

                        // no go
                        httpResponse.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());
                        httpResponse.flushBuffer();
                        return;

                    } catch (IOException ioe) {
                        LOG.error(ioe);
                    }
                }

            }
        }

        chain.doFilter(request, response);

    } catch (IOException e) {
        LOG.error(e);
    } catch (ServletException e) {
        LOG.error(e);
    } finally {

        // clear the logging diagnostics context
        MDC.clear();

        // Remove the user from memoty
        RemoteUser.destroy();
    }
}

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

@POST
@Path("login")
@Produces(MediaType.APPLICATION_JSON)//w w  w . jav a2  s  .  co  m
public Response login(@FormParam("email") String email, @FormParam("password") String password,
        @FormParam("otp") String otp, @Context HttpServletRequest req) throws UserException {
    logUserLogin(req);
    RESTApiJsonResponse json = new RESTApiJsonResponse();
    if (email == null || email.isEmpty()) {
        throw new IllegalArgumentException("Email was not provided");
    }
    Users user = userFacade.findByEmail(email);
    // Do pre cauth realm check
    String passwordWithSaltPlusOtp = authController.preCustomRealmLoginCheck(user, password, otp, req);

    // logout any user already loggedin if a new user tries to login 
    if (req.getRemoteUser() != null && !req.getRemoteUser().equals(email)) {
        logoutAndInvalidateSession(req);
    }
    //only login if not already logged...
    if (req.getRemoteUser() == null) {
        login(user, email, passwordWithSaltPlusOtp, req);
    } else {
        req.getServletContext().log("Skip logged because already logged in: " + email);
    }

    //read the user data from db and return to caller
    json.setSessionID(req.getSession().getId());

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

From source file:eu.europa.ec.fisheries.uvms.reporting.rest.resources.ReportingResource.java

@POST
@Produces(APPLICATION_JSON)/*from w ww.j a  v a2s.  co  m*/
@Consumes(APPLICATION_JSON)
public Response createReport(@Context HttpServletRequest request, ReportDTO report,
        @DefaultValue("default") @QueryParam(value = "projection") String projection,
        @HeaderParam("scopeName") String scopeName) {
    Response result;
    String username = request.getRemoteUser();

    log.debug("{} is requesting createReport(...), with a ID={}, scopeName: {}, visibility: {}", username,
            report.getId(), scopeName, report.getVisibility());

    if (StringUtils.isBlank(scopeName)) {
        result = createErrorResponse(ErrorCodes.USER_SCOPE_MISSING);
    } else {
        if (isScopeAllowed(report.getVisibility(), request)) {
            report.setCreatedBy(username);
            report.setScopeName(scopeName);

            ReportFeatureEnum requiredFeature = AuthorizationCheckUtil.getRequiredFeatureToCreateReport(report,
                    username);
            ReportDTO reportDTO;
            if (requiredFeature == null || request.isUserInRole(requiredFeature.toString())) {
                try {
                    reportDTO = reportService.create(report, username);
                    switch (Projection.valueOf(projection.toUpperCase())) {

                    case DETAILED:
                        result = createSuccessResponse(reportDTO);
                        break;

                    default:
                        result = createSuccessResponse(reportDTO.getId());
                    }
                } catch (Exception e) {
                    log.error("createReport failed.", e);
                    result = createErrorResponse(ErrorCodes.CREATE_ENTITY_ERROR);
                }
            } else {
                result = createErrorResponse(ErrorCodes.NOT_AUTHORIZED);
            }
        } else {
            result = createErrorResponse(ErrorCodes.NOT_AUTHORIZED);
        }
    }
    return result;
}