List of usage examples for javax.servlet.http HttpServletRequest getRemoteUser
public String getRemoteUser();
null
if the user has not been authenticated. From source file:org.kuali.rice.kcb.web.spring.UserPreferencesController.java
/** * saveDelivererConfiguration - save deliverer configuration data * @param request// w ww. j a v a 2s.c om * @param response * @return * @throws ServletException * @throws IOException */ public ModelAndView saveDelivererConfiguration(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userid = request.getRemoteUser(); LOG.debug("remoteUser: " + userid); boolean error = false; Map<String, Object> model = new HashMap<String, Object>(); // create preferences map here so that we can pass them all back to the view HashMap<String, String> preferences = new HashMap<String, String>(); // Get DeliveryType classes. loop through each deliverer type to // to obtain preferenceKeys. Check to see if a matching request // parameter was provided, then save a record for the userID, channelID, and // preferences setting Collection<MessageDeliverer> deliveryTypes = this.messageDelivererRegistryService.getAllDeliverers(); // first remove all configured user delivers for this user this.recipientPreferenceService.removeRecipientDelivererConfigs(userid); for (MessageDeliverer dt : deliveryTypes) { String deliveryTypeName = dt.getName(); HashMap<String, String> prefMap = dt.getPreferenceKeys(); LOG.debug("deliveryName: " + deliveryTypeName); HashMap<String, String> userprefs = new HashMap<String, String>(); for (String prefKey : prefMap.keySet()) { LOG.debug(" key: " + prefKey + ", value: " + request.getParameter(deliveryTypeName + "." + prefKey)); userprefs.put(deliveryTypeName + "." + prefKey, request.getParameter(deliveryTypeName + "." + prefKey)); preferences.put(deliveryTypeName + "." + prefKey, request.getParameter(deliveryTypeName + "." + prefKey)); } try { this.recipientPreferenceService.saveRecipientPreferences(userid, userprefs, dt); } catch (ErrorList errorlist) { error = true; model.put("errorList", errorlist.getErrors()); } // get channelName.channels String[] channels = request.getParameterValues(deliveryTypeName + ".channels"); if (channels != null && channels.length > 0) { for (int j = 0; j < channels.length; j++) { LOG.debug(deliveryTypeName + ".channels[" + j + "] " + channels[j]); } } // now save the userid, channel selection this.recipientPreferenceService.saveRecipientDelivererConfig(userid, deliveryTypeName, channels); } // get all channels Collection<String> channels = getAllChannels(); // get existing configured deliverers Collection<RecipientDelivererConfig> currentDeliverers = this.recipientPreferenceService .getDeliverersForRecipient(userid); Map<String, Object> currentDeliverersMap = new HashMap<String, Object>(); for (RecipientDelivererConfig udc : currentDeliverers) { String channelId = udc.getChannel(); currentDeliverersMap.put(udc.getDelivererName() + "." + channelId, Boolean.TRUE); } // use for debugging, uncomment for production //LOG.info("CurrentDeliverersMap"); //Iterator iter = currentDeliverersMap.keySet().iterator(); //while (iter.hasNext()) { // Object o = iter.next(); // LOG.info("key: "+o.toString()+", value: "+ currentDeliverersMap.get(o) ); //} model.put("channels", channels); model.put("deliveryTypes", deliveryTypes); model.put("preferences", preferences); model.put("currentDeliverersMap", currentDeliverersMap); model.put("message", "Update Successful"); putBackLocation(model, request.getParameter("backLocation")); return new ModelAndView(VIEW, model); }
From source file:org.eclipse.orion.server.servlets.XSRFPreventionFilter.java
private void logReasonForInvalidNonce(HttpServletRequest request, String method, String path, CookieHandler ch, String requestNonce) {// w ww . j a v a 2 s. c o m if (ch.hasNonceCookie() && (requestNonce != null)) { LOG.error(MessageFormat.format(NONCES_DO_NOT_MATCH, method, path, request.getRemoteUser(), requestNonce, ch.getValue())); } else { if (!ch.hasNonceCookie()) { LOG.error(MessageFormat.format(NO_NONCE_IN_COOKIES, method, path, request.getRemoteUser())); } if (requestNonce == null) { LOG.error(MessageFormat.format(NO_NONCE_IN_HEADER, method, path, request.getRemoteUser())); } } }
From source file:net.officefloor.plugin.servlet.container.integrate.HttpServletIntegrateTest.java
/** * Ensure can handle authenticated {@link HttpRequest}. *//*from w ww . j av a 2s . c o m*/ public void testAuthenticatedRequest() throws Exception { // Specify servicing setServicing(new Servicer() { @Override public String service(HttpServlet servlet, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Determine if authenticated String remoteUser = req.getRemoteUser(); if (remoteUser == null) { // Challenge for authentication resp.setStatus(HttpStatus.SC_UNAUTHORIZED); resp.setHeader("WWW-Authenticate", "Basic realm=\"TestRealm\""); return "Challenge"; // challenge constructed } // Send response to user return "Hello " + req.getRemoteUser(); } }); // Provide preemptive authentication HttpClientBuilder builder = HttpClientBuilder.create(); HttpTestUtil.configureCredentials(builder, "TestRealm", null, "Daniel", "password"); try (CloseableHttpClient client = builder.build()) { // Send request HttpGet request = new HttpGet(this.getServerUrl()); HttpResponse response = client.execute(request); // Validate the response assertHttpResponse(response, 200, "Hello Daniel"); } }
From source file:psiprobe.controllers.logs.DownloadLogController.java
@Override protected ModelAndView handleLogFile(HttpServletRequest request, HttpServletResponse response, LogDestination logDest) throws Exception { boolean compressed = "true".equals(ServletRequestUtils.getStringParameter(request, "compressed")); File file = logDest.getFile(); logger.info("Sending {}{} to {} ({})", file, (compressed ? " compressed" : ""), request.getRemoteAddr(), request.getRemoteUser()); if (compressed) { Utils.sendCompressedFile(request, response, file); } else {//from ww w. j av a2 s. c o m Utils.sendFile(request, response, file); } return null; }
From source file:org.apache.hadoop.hdfs.qjournal.server.GetJournalEditServlet.java
protected boolean isValidRequestor(HttpServletRequest request, Configuration conf) throws IOException { String remotePrincipal = request.getUserPrincipal().getName(); String remoteShortName = request.getRemoteUser(); if (remotePrincipal == null) { // This really shouldn't happen... LOG.warn("Received null remoteUser while authorizing access to " + "GetJournalEditServlet"); return false; }/*from ww w .j a v a 2 s . c o m*/ if (LOG.isDebugEnabled()) { LOG.debug("Validating request made by " + remotePrincipal + " / " + remoteShortName + ". This user is: " + UserGroupInformation.getLoginUser()); } Set<String> validRequestors = new HashSet<String>(); validRequestors.addAll(DFSUtil.getAllNnPrincipals(conf)); try { validRequestors.add(SecurityUtil.getServerPrincipal( conf.get(DFSConfigKeys.DFS_SECONDARY_NAMENODE_KERBEROS_PRINCIPAL_KEY), SecondaryNameNode.getHttpAddress(conf).getHostName())); } catch (Exception e) { // Don't halt if SecondaryNameNode principal could not be added. LOG.debug("SecondaryNameNode principal could not be added", e); String msg = String.format("SecondaryNameNode principal not considered, %s = %s, %s = %s", DFSConfigKeys.DFS_SECONDARY_NAMENODE_KERBEROS_PRINCIPAL_KEY, conf.get(DFSConfigKeys.DFS_SECONDARY_NAMENODE_KERBEROS_PRINCIPAL_KEY), DFSConfigKeys.DFS_NAMENODE_SECONDARY_HTTP_ADDRESS_KEY, conf.get(DFSConfigKeys.DFS_NAMENODE_SECONDARY_HTTP_ADDRESS_KEY, DFSConfigKeys.DFS_NAMENODE_SECONDARY_HTTP_ADDRESS_DEFAULT)); LOG.warn(msg); } // Check the full principal name of all the configured valid requestors. for (String v : validRequestors) { if (LOG.isDebugEnabled()) LOG.debug("isValidRequestor is comparing to valid requestor: " + v); if (v != null && v.equals(remotePrincipal)) { if (LOG.isDebugEnabled()) LOG.debug("isValidRequestor is allowing: " + remotePrincipal); return true; } } // Additionally, we compare the short name of the requestor to this JN's // username, because we want to allow requests from other JNs during // recovery, but we can't enumerate the full list of JNs. if (remoteShortName.equals(UserGroupInformation.getLoginUser().getShortUserName())) { if (LOG.isDebugEnabled()) LOG.debug("isValidRequestor is allowing other JN principal: " + remotePrincipal); return true; } if (LOG.isDebugEnabled()) LOG.debug("isValidRequestor is rejecting: " + remotePrincipal); return false; }
From source file:io.hops.hopsworks.api.user.UserService.java
@POST @Path("changeLoginCredentials") @Produces(MediaType.APPLICATION_JSON)/*from w w w . j av a 2s .c om*/ public Response changeLoginCredentials(@FormParam("oldPassword") String oldPassword, @FormParam("newPassword") String newPassword, @FormParam("confirmedPassword") String confirmedPassword, @Context HttpServletRequest req) throws UserException { RESTApiJsonResponse json = new RESTApiJsonResponse(); userController.changePassword(req.getRemoteUser(), oldPassword, newPassword, confirmedPassword, req); json.setSuccessMessage(ResponseMessages.PASSWORD_CHANGED); return noCacheResponse.getNoCacheResponseBuilder(Response.Status.OK).entity(json).build(); }
From source file:org.kuali.mobility.shared.interceptors.NativeCookieInterceptor.java
/** * Attempts to detect REMOTE_USER and sets currentNetworkId cookie with the value * * @param request// w w w . j a va 2 s. co m * @param response * @return * @deprecated This could should be placed in an other interceptor, this interceptor is only meant to detect platform specifics */ @Deprecated private void checkAuthenticatedUser(HttpServletRequest request, HttpServletResponse response) { String loggedInUser = request.getRemoteUser(); User user; if (StringUtils.isEmpty(loggedInUser) && ((user = (User) request.getSession().getAttribute(Constants.KME_USER_KEY)) != null)) { loggedInUser = user.getLoginName(); } LOG.debug("REMOTE_USER: " + loggedInUser); if (loggedInUser != null && !loggedInUser.trim().isEmpty()) { boolean useSecureCookies = Boolean .parseBoolean(getKmeProperties().getProperty("kme.secure.cookie", "false")); Cookie userCookie = new Cookie("currentNetworkId", loggedInUser); userCookie.setMaxAge(60 * 60); //1hr userCookie.setPath(request.getContextPath()); userCookie.setSecure(useSecureCookies); response.addCookie(userCookie); LOG.debug("Setting currentNetworkId cookie : " + loggedInUser); } }
From source file:org.eclipse.orion.internal.server.search.grep.FileGrepper.java
/** * Sets the scopes to the location of each project. * @param req The request from the servlet. * @param res The response to the servlet. * @throws GrepException Thrown if there is an error reading a file. *///ww w.j ava 2 s . c om private void setDefaultScopes(HttpServletRequest req, HttpServletResponse resp) throws GrepException { String login = req.getRemoteUser(); try { UserInfo userInfo = OrionConfiguration.getMetaStore().readUserByProperty(UserConstants2.USER_NAME, login, false, false); List<String> workspaceIds = userInfo.getWorkspaceIds(); for (String workspaceId : workspaceIds) { WorkspaceInfo workspaceInfo = OrionConfiguration.getMetaStore().readWorkspace(workspaceId); options.setDefaultScope("/file/" + workspaceId); addAllProjectsToScope(workspaceInfo); } } catch (CoreException e) { throw (new GrepException(e)); } }
From source file:io.hops.hopsworks.api.user.UserService.java
@POST @Path("changeSecurityQA") @Produces(MediaType.APPLICATION_JSON)/*from w w w . jav a2s . c o m*/ public Response changeSecurityQA(@FormParam("oldPassword") String oldPassword, @FormParam("securityQuestion") String securityQuestion, @FormParam("securityAnswer") String securityAnswer, @Context HttpServletRequest req) throws UserException { RESTApiJsonResponse json = new RESTApiJsonResponse(); userController.changeSecQA(req.getRemoteUser(), oldPassword, securityQuestion, securityAnswer, req); json.setSuccessMessage(ResponseMessages.SEC_QA_CHANGED); return noCacheResponse.getNoCacheResponseBuilder(Response.Status.OK).entity(json).build(); }
From source file:com.ibm.amc.feedback.FeedbackHandler.java
public void handleRequest(final HttpServletRequest request, final HttpServletResponse response) { if (logger.isEntryEnabled()) logger.entry("handleRequest", request, response); final String user = request.getRemoteUser(); final Queue<ActionStatusResponse> statuses = getActionStatuses(user); if (statuses.isEmpty()) { // No updates pending - register listener final AsyncContext asyncContext = request.startAsync(request, response); asyncContext.setTimeout(900000000L); logger.debug("handleRequest", "Registering new listener for user " + user); synchronized (feedbackListeners) { Set<AsyncContext> contexts = feedbackListeners.get(user); if (contexts == null) { contexts = new HashSet<AsyncContext>(); feedbackListeners.put(user, contexts); }/*from w ww . ja v a2 s . c o m*/ contexts.add(asyncContext); } // Timeout listener executor.schedule(new Runnable() { @Override public void run() { synchronized (feedbackListeners) { final Set<AsyncContext> contexts = feedbackListeners.get(user); if (contexts.remove(asyncContext)) { if (logger.isDebugEnabled()) logger.debug("handleRequest$Runnable.run", "Timing out listener for user " + user); writeResponse(asyncContext.getResponse(), new LinkedList<ActionStatusResponse>()); asyncContext.complete(); if (contexts.isEmpty()) feedbackListeners.remove(user); } } } }, POLLING_TIMEOUT, TimeUnit.SECONDS); } else { // Update pending - send response immediately writeResponse(response, statuses); } if (logger.isEntryEnabled()) logger.exit("handleRequest"); }