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.bedework.eventreg.web.AbstractController.java

/**
 * @param req request/* ww w. j  ava2 s  .c o  m*/
 */
public void dumpRequest(final HttpServletRequest req) {
    try {
        @SuppressWarnings("unchecked")
        final Enumeration<String> names = req.getParameterNames();

        final String title = "Request parameters";

        debug(title + " - global info and uris");
        debug("getRequestURI = " + req.getRequestURI());
        debug("getRemoteUser = " + req.getRemoteUser());
        debug("getRequestedSessionId = " + req.getRequestedSessionId());
        debug("HttpUtils.getRequestURL(req) = " + req.getRequestURL());
        debug("query=" + req.getQueryString());
        debug("contentlen=" + req.getContentLength());
        debug("request=" + req);
        debug("parameters:");

        debug(title);

        while (names.hasMoreElements()) {
            final String key = names.nextElement();
            final String[] vals = req.getParameterValues(key);
            for (final String val : vals) {
                debug("  " + key + " = \"" + val + "\"");
            }
        }
    } catch (final Throwable t) {
        error(t);
    }
}

From source file:com.google.identitytoolkit.GitkitClientTest.java

public void testGetOobCodeInvalidCaptchaCode() throws Exception {
    Cookie[] gitkitCookie = { new Cookie("gtoken", "fake-token") };
    HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class);
    when(mockRequest.getCookies()).thenReturn(gitkitCookie);
    when(mockRequest.getParameter("action")).thenReturn("resetPassword");
    when(mockRequest.getParameter("email")).thenReturn("1111@example.com");
    when(mockRequest.getParameter("challenge")).thenReturn("what is the number");
    when(mockRequest.getParameter("response")).thenReturn("8888");
    when(mockRequest.getRemoteUser()).thenReturn("1.1.1.1");
    String expectedApiUrl = GitkitClient.GITKIT_API_BASE + "getOobConfirmationCode";
    when(mockSender.post(eq(expectedApiUrl), anyString(), eq(headers)))
            .thenReturn("{ \"error\": { \"code\": \"4xx\", \"message\": \"CAPTCHA_CHECK_FAILED\" }}");

    GitkitClient.OobResponse oobResponse = gitkitClient.getOobResponse(mockRequest);
    // the client collapses the error message down to a simple error:value
    assertEquals("{\"error\": \"CAPTCHA_CHECK_FAILED\" }", oobResponse.getResponseBody());

}

From source file:com.google.identitytoolkit.GitkitClientTest.java

public void testGetOobCode() throws Exception {
    Cookie[] gitkitCookie = { new Cookie("gtoken", "fake-token") };
    HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class);
    when(mockRequest.getCookies()).thenReturn(gitkitCookie);
    when(mockRequest.getParameter("action")).thenReturn("resetPassword");
    when(mockRequest.getParameter("email")).thenReturn("1111@example.com");
    when(mockRequest.getParameter("challenge")).thenReturn("what is the number");
    when(mockRequest.getParameter("response")).thenReturn("8888");
    when(mockRequest.getRemoteUser()).thenReturn("1.1.1.1");
    String expectedApiUrl = GitkitClient.GITKIT_API_BASE + "getOobConfirmationCode";
    when(mockSender.post(eq(expectedApiUrl), anyString(), eq(headers)))
            .thenReturn("{'oobCode':'fake-oob-code'}");

    GitkitClient.OobResponse oobResponse = gitkitClient.getOobResponse(mockRequest);

    assertEquals(GitkitClient.OobAction.RESET_PASSWORD, oobResponse.getOobAction());
    assertEquals("http://example.com:80/gitkit?mode=resetPassword&oobCode=fake-oob-code",
            oobResponse.getOobUrl().get());
}

From source file:org.alfresco.repo.security.authentication.external.DefaultRemoteUserMapper.java

public String getRemoteUser(HttpServletRequest request) {
    if (logger.isDebugEnabled())
        logger.debug("Getting RemoteUser from http request.");
    if (!this.isEnabled) {
        if (logger.isDebugEnabled())
            logger.debug("DefaultRemoteUserMapper is disabled, returning null.");
        return null;
    }/*from w w w .  j a v a2 s.  c  o  m*/
    String remoteUserId = request.getRemoteUser();
    String headerUserId = extractUserFromProxyHeader(request);
    if (logger.isDebugEnabled()) {
        logger.debug("The remote user id is: " + remoteUserId);
        logger.debug("The header user id is: " + headerUserId);
        logger.debug("The proxy user name is: " + this.proxyUserName);
    }
    if (this.proxyUserName == null) {
        // Normalize the user ID taking into account case sensitivity settings
        String normalizedUserId = normalizeUserId(headerUserId != null ? headerUserId : remoteUserId);
        if (logger.isDebugEnabled())
            logger.debug("Returning " + normalizedUserId);
        return normalizedUserId;
    } else if (remoteUserId == null) {
        String normalizedUserId = null;
        // Try to extract the remote user from SSL certificate
        // MNT-13989
        X509Certificate[] certs = (X509Certificate[]) request
                .getAttribute("javax.servlet.request.X509Certificate");
        if (request.getScheme().toLowerCase().equals("https") && certs != null && certs.length > 0) {
            if (logger.isDebugEnabled()) {
                logger.debug("Checking SSL certificate subject DN to match " + this.proxyUserName);
            }
            for (int i = 0; i < certs.length; i++) {
                String subjectDN = certs[i].getSubjectX500Principal().getName();
                if (logger.isDebugEnabled()) {
                    logger.debug("Found subject DN " + subjectDN);
                }
                if (subjectDN.equals(this.proxyUserName)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("The subject DN " + subjectDN + " matches " + this.proxyUserName);
                    }
                    // Found the subject distinguished name
                    remoteUserId = subjectDN;
                    // Normalize the user ID taking into account case sensitivity settings
                    normalizedUserId = normalizeUserId(headerUserId != null ? headerUserId : remoteUserId);
                    break;
                }
            }
        }
        if (logger.isDebugEnabled())
            logger.debug("Returning " + normalizedUserId);
        return normalizedUserId;
    } else {
        // Normalize the user ID taking into account case sensitivity settings
        String normalizedUserId = normalizeUserId(
                remoteUserId.equals(this.proxyUserName) ? headerUserId : remoteUserId);
        if (logger.isDebugEnabled())
            logger.debug("Returning " + normalizedUserId);
        return normalizedUserId;
    }
}

From source file:alpha.portal.webapp.controller.CardFormController.java

/**
 * Assign card./* ww w .ja v a2  s.c om*/
 * 
 * @param jspCard
 *            the jsp card
 * @param errors
 *            the errors
 * @param request
 *            the request
 * @return the string
 * @throws Exception
 *             the exception
 */
@RequestMapping(method = RequestMethod.POST, params = { "assignToMe" })
public String assignCard(final AlphaCard jspCard, final BindingResult errors, final HttpServletRequest request)
        throws Exception {
    final AlphaCard alphaCard = this.alphaCardManager.get(jspCard.getAlphaCardIdentifier());
    final User currentUser = this.userManager.getUserByUsername(request.getRemoteUser());
    alphaCard.getAlphaCardDescriptor().setAdornment(AdornmentType.Contributor.getName(),
            currentUser.getId().toString());

    this.alphaCardManager.save(alphaCard);

    final AlphaCardIdentifier identifier = alphaCard.getAlphaCardIdentifier();
    return "redirect:/caseform?caseId=" + identifier.getCaseId() + "&activeCardId=" + identifier.getCardId();
}

From source file:org.eurekaclinical.user.service.resource.UserResource.java

/**
 * Get a user by the user's identification number.
 *
 * @param req in request/*from   w  ww .  j a v  a2s  .c  om*/
 * @param inId The identification number for the user to fetch.
 * @return The user referenced by the identification number.
 */
@RolesAllowed({ "researcher", "admin" })
@Path("/{id}")
@GET
public User getUserById(@Context HttpServletRequest req, @PathParam("id") Long inId) {
    UserEntity userEntity = this.userDao.retrieve(inId);
    if (userEntity == null) {
        throw new HttpStatusException(Response.Status.NOT_FOUND);
    }
    if (!req.isUserInRole("admin") && !req.getRemoteUser().equals(userEntity.getUsername())) {
        throw new HttpStatusException(Response.Status.FORBIDDEN);
    }
    this.userDao.refresh(userEntity);
    LOGGER.debug("Returning user for ID {}", inId);
    UserEntityToUserVisitor visitor = new UserEntityToUserVisitor();
    userEntity.accept(visitor);
    return visitor.getUser();
}

From source file:com.adeptj.runtime.servlet.ToolsServlet.java

/**
 * Renders tools page.// w  ww  . ja  va  2s.c o m
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
    Bundle[] bundles = BundleContextHolder.getInstance().getBundleContext().getBundles();
    long startTime = ManagementFactory.getRuntimeMXBean().getStartTime();
    MemoryUsage memoryUsage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
    TemplateEngine.getInstance()
            .render(TemplateContext.builder().request(req).response(resp).template(TOOLS_TEMPLATE)
                    .locale(req.getLocale())
                    .templateData(TemplateData.newTemplateData().put("username", req.getRemoteUser())
                            .put("sysProps", System.getProperties().entrySet())
                            .put("totalBundles", bundles.length).put("bundles", bundles)
                            .put("runtime", JAVA_RUNTIME_NAME + "(build " + JAVA_RUNTIME_VERSION + ")")
                            .put("jvm", JAVA_VM_NAME + "(build " + JAVA_VM_VERSION + ", " + JAVA_VM_INFO + ")")
                            .put("startTime", Date.from(Instant.ofEpochMilli(startTime)))
                            .put("upTime", Times.format(startTime))
                            .put("maxMemory", FileUtils.byteCountToDisplaySize(memoryUsage.getMax()))
                            .put("usedMemory", FileUtils.byteCountToDisplaySize(memoryUsage.getUsed()))
                            .put("processors", Runtime.getRuntime().availableProcessors()))
                    .build());
}

From source file:com.edgenius.wiki.security.acegi.BasicAuthenticationRequireFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {
    String header = request.getHeader("Authorization");
    if ((header != null) && header.startsWith("Basic ")) {
        //this user input authenticate code
        chain.doFilter(request, response);
        return;/* w  w w  . jav a  2 s  .  co m*/
    }

    //if user does not input Basic Authentication information, then try to use HttpRequest to authenticate
    String enString = "Basic ";
    User user = userReadingService.getUserByName(request.getRemoteUser());
    if (user != null && !user.isAnonymous()) {
        enString = user.getUsername() + ":" + user.getPassword();
        enString = "Basic " + new String(Base64.encodeBase64(enString.getBytes()));
    }

    request = new AuthenticateRequestWrapper(request, enString);
    chain.doFilter(request, response);

}

From source file:com.jivesoftware.os.upena.deployable.UpenaEndpoints.java

@GET
@Path("/logout")
@Produces(MediaType.TEXT_HTML)/*  w  ww .  ja  v a  2  s.  c o m*/
public Response logout(@Context HttpServletRequest httpRequest, @Context UriInfo uriInfo)
        throws ServletException {
    httpRequest.logout();
    String rendered = soyService.render(httpRequest.getRemoteUser(),
            uriInfo.getAbsolutePath() + "propagator/download", amzaClusterName.name);
    return Response.ok(rendered).build();
}

From source file:org.kuali.rice.ken.web.spring.SendNotificationMessageController.java

/**
 * This method prepares the model used for the send simple notification message form.
 * @param request//from ww  w  .  ja  v  a2 s  .  c om
 * @return Map<String, Object>
 */
private Map<String, Object> setupModelForSendSimpleNotification(HttpServletRequest request) {
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("defaultSender", request.getRemoteUser());
    model.put("channels", notificationChannelService.getAllNotificationChannels());
    model.put("priorities", businessObjectDao.findAll(NotificationPriorityBo.class));
    // set sendDateTime to current datetime if not provided
    String sendDateTime = request.getParameter("sendDateTime");
    String currentDateTime = Util.getCurrentDateTime();
    if (StringUtils.isEmpty(sendDateTime)) {
        sendDateTime = currentDateTime;
    }
    model.put("sendDateTime", sendDateTime);

    // retain the original date time or set to current if
    // it was not in the request
    if (request.getParameter("originalDateTime") == null) {
        model.put("originalDateTime", currentDateTime);
    } else {
        model.put("originalDateTime", request.getParameter("originalDateTime"));
    }

    model.put("userRecipients", request.getParameter("userRecipients"));
    model.put("workgroupRecipients", request.getParameter("workgroupRecipients"));
    model.put("workgroupNamespaceCodes", request.getParameter("workgroupNamespaceCodes"));

    return model;
}