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.apache.hadoop.hdfsproxy.ProxyFilter.java
/** {@inheritDoc} */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest rqst = (HttpServletRequest) request; HttpServletResponse rsp = (HttpServletResponse) response; if (LOG.isDebugEnabled()) { StringBuilder b = new StringBuilder("Request from ").append(rqst.getRemoteHost()).append("/") .append(rqst.getRemoteAddr()).append(":").append(rqst.getRemotePort()); @SuppressWarnings("unchecked") Enumeration<String> e = rqst.getAttributeNames(); for (; e.hasMoreElements();) { String attribute = e.nextElement(); b.append("\n " + attribute + " => " + rqst.getAttribute(attribute)); }//from ww w. j a v a 2 s . c om X509Certificate[] userCerts = (X509Certificate[]) rqst .getAttribute("javax.servlet.request.X509Certificate"); if (userCerts != null) for (X509Certificate cert : userCerts) b.append("\n Client certificate Subject Name is " + cert.getSubjectX500Principal().getName()); b.append("\n The Scheme is " + rqst.getScheme()); b.append("\n The Auth Type is " + rqst.getAuthType()); b.append("\n The Path Info is " + rqst.getPathInfo()); b.append("\n The Translated Path Info is " + rqst.getPathTranslated()); b.append("\n The Context Path is " + rqst.getContextPath()); b.append("\n The Query String is " + rqst.getQueryString()); b.append("\n The Remote User is " + rqst.getRemoteUser()); b.append("\n The User Principal is " + rqst.getUserPrincipal()); b.append("\n The Request URI is " + rqst.getRequestURI()); b.append("\n The Request URL is " + rqst.getRequestURL()); b.append("\n The Servlet Path is " + rqst.getServletPath()); LOG.debug(b.toString()); } boolean unitTest = false; if (rqst.getScheme().equalsIgnoreCase("http") && rqst.getParameter("UnitTest") != null) unitTest = true; if (rqst.getScheme().equalsIgnoreCase("https") || unitTest) { boolean isAuthorized = false; X509Certificate[] certs = (X509Certificate[]) rqst .getAttribute("javax.servlet.request.X509Certificate"); if (unitTest) { try { LOG.debug("==> Entering https unit test"); String SslPath = rqst.getParameter("SslPath"); InputStream inStream = new FileInputStream(SslPath); CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream); inStream.close(); certs = new X509Certificate[] { cert }; } catch (Exception e) { // do nothing here } } if (certs == null || certs.length == 0) { rsp.sendError(HttpServletResponse.SC_BAD_REQUEST, "No client SSL certificate received"); LOG.info("No Client SSL certificate received"); return; } for (X509Certificate cert : certs) { try { cert.checkValidity(); } catch (CertificateExpiredException e) { LOG.info("Received cert for " + cert.getSubjectX500Principal().getName() + " expired"); rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Certificate expired"); return; } catch (CertificateNotYetValidException e) { LOG.info("Received cert for " + cert.getSubjectX500Principal().getName() + " is not yet valid"); rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Certificate is not yet valid"); return; } } String[] tokens = certs[0].getSubjectX500Principal().getName().split("\\s*,\\s*"); String userID = null; for (String s : tokens) { if (s.startsWith("CN=")) { userID = s; break; } } if (userID == null || userID.length() < 4) { LOG.info("Can't retrieve user ID from SSL certificate"); rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Can't retrieve user ID from SSL certificate"); return; } userID = userID.substring(3); String servletPath = rqst.getServletPath(); if (unitTest) { servletPath = rqst.getParameter("TestSevletPathInfo"); LOG.info("this is for unit test purpose only"); } if (HFTP_PATTERN.matcher(servletPath).matches()) { // request is an HSFTP request if (FILEPATH_PATTERN.matcher(servletPath).matches()) { // file path as part of the URL isAuthorized = checkPath(userID, certs[0], rqst.getPathInfo() != null ? rqst.getPathInfo() : "/"); } else { // file path is stored in "filename" parameter isAuthorized = checkPath(userID, certs[0], rqst.getParameter("filename")); } } else if (RELOAD_PATTERN.matcher(servletPath).matches() && checkUser("Admin", certs[0])) { Configuration conf = new Configuration(false); conf.addResource("hdfsproxy-default.xml"); Map<String, Set<Path>> permsMap = getPermMap(conf); Map<String, Set<BigInteger>> certsMap = getCertsMap(conf); if (permsMap == null || certsMap == null) { LOG.warn("Permission files reloading failed"); rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Permission files reloading failed"); return; } ProxyFilter.permsMap = permsMap; ProxyFilter.certsMap = certsMap; LOG.info("User permissions and user certs files reloaded"); rsp.setStatus(HttpServletResponse.SC_OK); return; } if (!isAuthorized) { rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Unauthorized access"); return; } // request is authorized, set ugi for servlets UserGroupInformation ugi = UserGroupInformation.createRemoteUser(userID); rqst.setAttribute("authorized.ugi", ugi); rqst.setAttribute("org.apache.hadoop.hdfsproxy.authorized.userID", userID); } else if (rqst.getScheme().equalsIgnoreCase("http")) { // http request, set ugi for servlets, only for testing purposes String ugi = rqst.getParameter("ugi"); if (ugi != null) { rqst.setAttribute("authorized.ugi", UserGroupInformation.createRemoteUser(ugi)); rqst.setAttribute("org.apache.hadoop.hdfsproxy.authorized.userID", ugi.split(",")[0]); } } chain.doFilter(request, response); }
From source file:org.apache.falcon.security.BasicAuthFilter.java
@Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain filterChain) throws IOException, ServletException { FilterChain filterChainWrapper = new FilterChain() { @Override//from w w w .ja v a 2 s . c om public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) servletRequest; if (httpRequest.getMethod().equals("OPTIONS")) { // option request meant only for authentication optionsServlet.service(request, response); } else { final String user = getUserFromRequest(httpRequest); if (StringUtils.isEmpty(user)) { ((HttpServletResponse) response).sendError(Response.Status.BAD_REQUEST.getStatusCode(), "User can't be empty"); } else if (blackListedUsers.contains(user)) { ((HttpServletResponse) response).sendError(Response.Status.BAD_REQUEST.getStatusCode(), "User can't be a superuser:" + BLACK_LISTED_USERS_KEY); } else { try { String requestId = UUID.randomUUID().toString(); NDC.push(user + ":" + httpRequest.getMethod() + "/" + httpRequest.getPathInfo()); NDC.push(requestId); CurrentUser.authenticate(user); LOG.info("Request from user: {}, URL={}", user, getRequestUrl(httpRequest)); filterChain.doFilter(servletRequest, servletResponse); } finally { NDC.pop(); NDC.pop(); } } } } private String getUserFromRequest(HttpServletRequest httpRequest) { String user = httpRequest.getRemoteUser(); // this is available from wrapper in super class if (!StringUtils.isEmpty(user)) { return user; } user = httpRequest.getParameter("user.name"); // available in query-param if (!StringUtils.isEmpty(user)) { return user; } user = httpRequest.getHeader("Remote-User"); // backwards-compatibility if (!StringUtils.isEmpty(user)) { return user; } return null; } private String getRequestUrl(HttpServletRequest request) { StringBuffer url = request.getRequestURL(); if (request.getQueryString() != null) { url.append("?").append(request.getQueryString()); } return url.toString(); } }; super.doFilter(request, response, filterChainWrapper); }
From source file:it.eng.spago.dispatching.httpchannel.AdapterHTTP.java
/** * Sets the http request data.//w w w . j ava 2 s . c o m * * @param request the request * @param requestContainer the request container */ private void setHttpRequestData(HttpServletRequest request, RequestContainer requestContainer) { requestContainer.setAttribute(HTTP_REQUEST_AUTH_TYPE, request.getAuthType()); requestContainer.setAttribute(HTTP_REQUEST_CHARACTER_ENCODING, request.getCharacterEncoding()); requestContainer.setAttribute(HTTP_REQUEST_CONTENT_LENGTH, String.valueOf(request.getContentLength())); requestContainer.setAttribute(HTTP_REQUEST_CONTENT_TYPE, request.getContentType()); requestContainer.setAttribute(HTTP_REQUEST_CONTEXT_PATH, request.getContextPath()); requestContainer.setAttribute(HTTP_REQUEST_METHOD, request.getMethod()); requestContainer.setAttribute(HTTP_REQUEST_PATH_INFO, request.getPathInfo()); requestContainer.setAttribute(HTTP_REQUEST_PATH_TRANSLATED, request.getPathTranslated()); requestContainer.setAttribute(HTTP_REQUEST_PROTOCOL, request.getProtocol()); requestContainer.setAttribute(HTTP_REQUEST_QUERY_STRING, request.getQueryString()); requestContainer.setAttribute(HTTP_REQUEST_REMOTE_ADDR, request.getRemoteAddr()); requestContainer.setAttribute(HTTP_REQUEST_REMOTE_HOST, request.getRemoteHost()); requestContainer.setAttribute(HTTP_REQUEST_REMOTE_USER, request.getRemoteUser()); requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID, request.getRequestedSessionId()); requestContainer.setAttribute(HTTP_REQUEST_REQUEST_URI, request.getRequestURI()); requestContainer.setAttribute(HTTP_REQUEST_SCHEME, request.getScheme()); requestContainer.setAttribute(HTTP_REQUEST_SERVER_NAME, request.getServerName()); requestContainer.setAttribute(HTTP_REQUEST_SERVER_PORT, String.valueOf(request.getServerPort())); requestContainer.setAttribute(HTTP_REQUEST_SERVLET_PATH, request.getServletPath()); if (request.getUserPrincipal() != null) requestContainer.setAttribute(HTTP_REQUEST_USER_PRINCIPAL, request.getUserPrincipal()); requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_FROM_COOKIE, String.valueOf(request.isRequestedSessionIdFromCookie())); requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_FROM_URL, String.valueOf(request.isRequestedSessionIdFromURL())); requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_VALID, String.valueOf(request.isRequestedSessionIdValid())); requestContainer.setAttribute(HTTP_REQUEST_SECURE, String.valueOf(request.isSecure())); Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = (String) headerNames.nextElement(); String headerValue = request.getHeader(headerName); requestContainer.setAttribute(headerName, headerValue); } // while (headerNames.hasMoreElements()) requestContainer.setAttribute(HTTP_SESSION_ID, request.getSession().getId()); requestContainer.setAttribute(Constants.HTTP_IS_XML_REQUEST, "FALSE"); }
From source file:org.gbif.portal.web.controller.registration.RegistrationController.java
/** * The entry point once a user has logged in. */// ww w . j a v a 2 s . co m @SuppressWarnings("unchecked") public ModelAndView viewAdminMenu(HttpServletRequest request, HttpServletResponse response) throws Exception { UserLogin userLogin = ldapUtils.getUserLogin(request.getRemoteUser()); // retrieve login/business key mapping List<String> businessKeys = uddiUtils.getAssociatedBusinessKeys(request.getRemoteUser()); List<ProviderDetail> pds = new ArrayList<ProviderDetail>(); for (int i = 0; i < businessKeys.size(); i++) { ProviderDetail pd = uddiUtils.createProviderFromUDDI(businessKeys.get(i), userLogin.getFullName()); pds.add(pd); } ModelAndView mav = new ModelAndView("registrationMain"); mav.addObject("providerDetails", pds); if (StringUtils.isNotEmpty(userLogin.getFullName())) { mav.addObject("username", userLogin.getFullName()); } else { mav.addObject("username", userLogin.getUsername()); } return mav; }
From source file:org.ambraproject.wombat.controller.CommentController.java
/** * @param parentArticleDoi null if a reply to another comment * @param parentCommentUri null if a direct reply to an article *//*from ww w . java 2 s . c o m*/ @RequestMapping(name = "postComment", method = RequestMethod.POST, value = "/article/comments/new") @ResponseBody public Object receiveNewComment(HttpServletRequest request, @SiteParam Site site, @RequestParam("commentTitle") String commentTitle, @RequestParam("comment") String commentBody, @RequestParam("isCompetingInterest") boolean hasCompetingInterest, @RequestParam(value = "authorEmailAddress", required = false) String authorEmailAddress, @RequestParam(value = "authorName", required = false) String authorName, @RequestParam(value = "authorPhone", required = false) String authorPhone, @RequestParam(value = "authorAffiliation", required = false) String authorAffiliation, @RequestParam(value = "ciStatement", required = false) String ciStatement, @RequestParam(value = "target", required = false) String parentArticleDoi, @RequestParam(value = "inReplyTo", required = false) String parentCommentUri) throws IOException { if (honeypotService.checkHoneypot(request, authorPhone, authorAffiliation)) { return ImmutableMap.of("status", "success"); } checkCommentsAreEnabled(); Map<String, Object> validationErrors = commentValidationService.validateComment(site, commentTitle, commentBody, hasCompetingInterest, ciStatement); if (!validationErrors.isEmpty()) { return ImmutableMap.of("validationErrors", validationErrors); } if (parentArticleDoi == null) { Map<String, Object> comment = getComment(parentCommentUri); parentArticleDoi = getParentArticleDoiFromComment(comment); } ApiAddress address = ApiAddress.builder("articles").embedDoi(parentArticleDoi).addToken("comments").build(); String authId = request.getRemoteUser(); final String creatorUserId = authId == null ? null : userApi.getUserIdFromAuthId(authId); ArticleComment comment = new ArticleComment(parentArticleDoi, creatorUserId, parentCommentUri, commentTitle, commentBody, ciStatement, authorEmailAddress, authorName); HttpResponse response = articleApi.postObject(address, comment); String responseJson = EntityUtils.toString(response.getEntity()); Map<String, Object> commentJson = gson.fromJson(responseJson, HashMap.class); return ImmutableMap.of("createdCommentUri", commentJson.get("commentUri")); }
From source file:org.gbif.portal.web.controller.registration.RegistrationController.java
/** * This is the entry point when the user types in the URL directly * It must have a key//from w w w . ja va2 s.c o m */ public ModelAndView showDataResources(HttpServletRequest request, HttpServletResponse response) throws Exception { // get the authenticated user from LDAP UserLogin userLogin = ldapUtils.getUserLogin(request.getRemoteUser()); ProviderDetail detail = null; String key = request.getParameter(REQUEST_BUSINESS_UDDI_KEY); if (StringUtils.isNotEmpty(key)) { detail = uddiUtils.createProviderFromUDDI(key, userLogin.getUsername()); } if (detail != null) { return retrieveRegisteredDataResources(request, response, detail); } else { logger.warn("Direct use of showDataResources with no key or invalid key: " + key); return new ModelAndView("registrationBadBusinessKey"); } }
From source file:org.gbif.portal.web.controller.registration.RegistrationController.java
/** * Setup page for a new data provider. When registering a new contact, some details are prepopulated from LDAP. * // w w w. j av a 2 s .c o m * @param request * @param response * @return * @throws Exception */ public ModelAndView registerDataProvider(HttpServletRequest request, HttpServletResponse response) throws Exception { // get the authenticated user from LDAP UserLogin userLogin = ldapUtils.getUserLogin(request.getRemoteUser()); // get the provider from UDDI if necessary ProviderDetail detail = new ProviderDetail(); // these are prepopulated from LDAP detail.getBusinessPrimaryContact().setName(userLogin.getUsername()); detail.getBusinessPrimaryContact().setPhone(userLogin.getTelephone()); detail.getBusinessPrimaryContact().setEmail(userLogin.getEmail()); Map<String, Object> data = new HashMap<String, Object>(); data.putAll(referenceDataForProvider(request)); data.put(RegistrationController.REQUEST_PROVIDER_DETAIL, detail); ModelAndView mav = new ModelAndView("registrationUpdateProviderDetail", data); return mav; }
From source file:org.gbif.portal.web.controller.registration.RegistrationController.java
/** * Populates the form for displaying the data provider if there is a key in the request. If there isn't then an * empty form is used, with a prepolution of the primary contact from LDAP * //from www. j av a 2 s. co m * @TODO Exception handling for services down, invalid keys... */ @SuppressWarnings("unchecked") public ModelAndView updateDataProvider(HttpServletRequest request, HttpServletResponse response) throws Exception { // get the authenticated user from LDAP UserLogin userLogin = ldapUtils.getUserLogin(request.getRemoteUser()); // get the provider from UDDI if necessary ProviderDetail detail = null; String key = request.getParameter(REQUEST_BUSINESS_UDDI_KEY); if (StringUtils.isNotEmpty(key)) { detail = uddiUtils.createProviderFromUDDI(key, userLogin.getUsername()); } if (detail == null) { return new ModelAndView("registrationBadBusinessKey"); } // LDAP details override the UDDI version - is this right? // detail.getBusinessPrimaryContact().setName(namePhoneEmail[0]); // detail.getBusinessPrimaryContact().setPhone(namePhoneEmail[1]); // detail.getBusinessPrimaryContact().setEmail(namePhoneEmail[2]); Map<String, Object> data = new HashMap<String, Object>(); data.putAll(referenceDataForProvider(request)); data.put(RegistrationController.REQUEST_PROVIDER_DETAIL, detail); return new ModelAndView("registrationUpdateProviderDetail", data); }
From source file:oculus.memex.rest.AttributeDetailsResource.java
@GET @Path("{attribute}/{value}") @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public ClusterDetailsResult handleGet(@PathParam("attribute") String attribute, @PathParam("value") String value, @Context HttpServletRequest request) { List<DataRow> results = new ArrayList<DataRow>(); TimeLog log = new TimeLog(); log.pushTime("Attribute details: " + attribute + ":" + value); log.pushTime("Fetch Ad IDs"); // Open both databases MemexOculusDB oculusdb = MemexOculusDB.getInstance(); Connection oculusconn = oculusdb.open(); MemexHTDB htdb = MemexHTDB.getInstance(); Connection htconn = htdb.open(); Integer attrid = null;//from www. jav a2 s .c o m HashMap<Integer, AttributeValue> allAttributes = AttributeLinks.getAttributes(oculusconn); if (attribute.equals("id")) { attrid = Integer.parseInt(value); } else { for (Entry<Integer, AttributeValue> e : allAttributes.entrySet()) { AttributeValue av = e.getValue(); if (av.attribute.equals(attribute) && av.value.equals(value)) { attrid = e.getKey(); break; } } } if (attrid == null) { oculusdb.close(); htdb.close(); log.popTime(); log.popTime(); return null; } // Get the ad->attribute list mapping HashMap<Integer, HashSet<Integer>> adToAttributes = new HashMap<Integer, HashSet<Integer>>(); ArrayList<Integer> ads = new ArrayList<Integer>(); AttributeDetails.getAdsInAttributes(attrid, attrid, allAttributes, adToAttributes, oculusconn, htconn, ads); HashSet<Integer> members = new HashSet<Integer>(adToAttributes.keySet()); oculusdb.close(); htdb.close(); log.popTime(); log.pushTime("Fetch Ad Contents"); PreclusterDetailsResource.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:org.midonet.cluster.rest_api.auth.LoginFilter.java
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { log.debug("Processing login request"); HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; // Get the Authorization header. 'getHeader' is case insensitive String authorization = request.getHeader("authorization"); if (StringUtils.isEmpty(authorization)) { ResponseUtils.setAuthErrorResponse(response, "Authorization header is not set."); return;//from w ww . ja v a 2 s . c om } // Support only Basic if (!authorization.toLowerCase().startsWith(HttpSupport.BASIC_AUTH_PREFIX.toLowerCase())) { ResponseUtils.setAuthErrorResponse(response, "Authorization header does not contain Basic."); return; } // Get the base64 portion String credentialsEnc = authorization.substring(HttpSupport.BASIC_AUTH_PREFIX.length()); // Decode base64 String credentials = new String(Base64.decodeBase64(credentialsEnc.getBytes())); // Get the username/password String[] credList = credentials.split(":"); if (credList.length != 2) { ResponseUtils.setAuthErrorResponse(response, "Authorization header is not valid"); return; } try { String project = request.getHeader(HEADER_X_AUTH_PROJECT); if (StringUtils.isBlank(project)) project = null; Token token = service.authenticate(credList[0], credList[1], Option$.MODULE$.apply(project)); // Set the Cookie ResponseUtils.setCookie(response, token.key, token.getExpiresString()); // Set the Token object as the body of the response. ResponseUtils.setEntity(response, token); } catch (AuthException ex) { ResponseUtils.setAuthErrorResponse(response, ex.getMessage()); log.error("Login authorization error occurred for user {}", request.getRemoteUser(), ex); } }