List of usage examples for javax.servlet.http HttpServletRequest getUserPrincipal
public java.security.Principal getUserPrincipal();
java.security.Principal
object containing the name of the current authenticated user. From source file:org.niord.web.wms.WmsProxyServlet.java
/** * Main GET method/*from w w w .j av a 2 s.com*/ * @param request servlet request * @param response servlet response */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { // Enforce "wmsProtected" flag. If set, only authenticated users can load the tiles. // On the client level, load the tiles using Ajax (see map-directive.js) to ensure // that the proper headers are passed along if (wmsProtected && request.getUserPrincipal() == null) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.getWriter() .println("<html><body><p>WMS service only available to authenticated users</p></body></html>"); return; } // Cache for a day WebUtils.cache(response, CACHE_TIMEOUT); // Check that the WMS provider has been defined using system properties if (StringUtils.isBlank(wmsServiceName) || StringUtils.isBlank(wmsProvider) || StringUtils.isBlank(wmsLogin) || StringUtils.isBlank(wmsPassword)) { response.sendRedirect(BLANK_IMAGE); return; } @SuppressWarnings("unchecked") Map<String, String[]> paramMap = request.getParameterMap(); String params = paramMap.entrySet().stream() .filter(p -> StringUtils.isBlank(wmsLayers) || !"layers".equalsIgnoreCase(p.getKey())) .map(p -> String.format("%s=%s", p.getKey(), p.getValue()[0])).collect(Collectors.joining("&")); params += String.format("&SERVICENAME=%s&LOGIN=%s&PASSWORD=%s", wmsServiceName, wmsLogin, wmsPassword); if (StringUtils.isNotBlank(wmsLayers)) { params += String.format("&LAYERS=%s", wmsLayers); } String url = wmsProvider + "?" + params; log.trace("Loading image " + url); try { BufferedImage image = ImageIO.read(new URL(url)); if (image != null) { //image = transformWhiteToTransparent(image); OutputStream out = response.getOutputStream(); ImageIO.write(image, "png", out); image.flush(); out.close(); return; } } catch (Exception e) { log.trace("Failed loading WMS image for URL " + url + ": " + e); } // Fall back to return a blank image try { response.sendRedirect(BLANK_IMAGE); } catch (Exception e) { log.trace("Failed returning blank image for URL " + url + ": " + e); } }
From source file:io.hops.hopsworks.api.tensorflow.TensorboardProxyServlet.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { String email = servletRequest.getUserPrincipal().getName(); LOGGER.log(Level.FINE, "Request URL: {0}", servletRequest.getRequestURL()); String uri = servletRequest.getRequestURI(); // valid hostname regex: // https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address Pattern urlPattern = Pattern.compile("([a-zA-Z0-9\\-\\.]{2,255}:[0-9]{4,6})(/.*$)"); Matcher urlMatcher = urlPattern.matcher(uri); String hostPortPair = ""; String uriToFinish = "/"; if (urlMatcher.find()) { hostPortPair = urlMatcher.group(1); uriToFinish = urlMatcher.group(2); }// w w w . j a v a 2 s . c o m if (hostPortPair.isEmpty()) { throw new ServletException("Couldn't extract host:port from: " + servletRequest.getRequestURI()); } Pattern appPattern = Pattern.compile("(application_.*?_\\d*)"); Matcher appMatcher = appPattern.matcher(servletRequest.getRequestURI()); Pattern elasticPattern = Pattern.compile("(experiments)"); Matcher elasticMatcher = elasticPattern.matcher(servletRequest.getRequestURI()); if (elasticMatcher.find()) { List<TensorBoard> TBList = tensorBoardFacade.findByUserEmail(email); if (TBList == null) { servletResponse.sendError(Response.Status.FORBIDDEN.getStatusCode(), "This TensorBoard is not running right now"); } boolean foundTB = false; for (TensorBoard tb : TBList) { if (tb.getEndpoint().equals(hostPortPair)) { foundTB = true; break; } } if (!foundTB) { servletResponse.sendError(Response.Status.FORBIDDEN.getStatusCode(), "This TensorBoard is not running right now"); return; } targetUri = uriToFinish; String theHost = "http://" + hostPortPair; URI targetUriHost; try { targetUriObj = new URI(targetUri); targetUriHost = new URI(theHost); } catch (Exception e) { throw new ServletException("Trying to process targetUri init parameter: ", e); } targetHost = URIUtils.extractHost(targetUriHost); servletRequest.setAttribute(ATTR_TARGET_URI, targetUri); servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost); servletRequest.setAttribute(ATTR_URI_FINISH, uriToFinish); servletRequest.setAttribute(ATTR_HOST_PORT, hostPortPair); try { super.service(servletRequest, servletResponse); } catch (IOException ex) { sendErrorResponse(servletResponse, "This TensorBoard is not ready to serve requests right now, " + "try refreshing the page"); return; } } else if (appMatcher.find()) { String appId = appMatcher.group(1); YarnApplicationstate appState = yarnApplicationstateFacade.findByAppId(appId); if (appState == null) { servletResponse.sendError(Response.Status.FORBIDDEN.getStatusCode(), "You don't have the access right for this application"); return; } String projectName = hdfsUsersBean.getProjectName(appState.getAppuser()); ProjectDTO project; try { project = projectController.getProjectByName(projectName); } catch (ProjectException ex) { throw new ServletException(ex); } Users user = userFacade.findByEmail(email); boolean inTeam = false; for (ProjectTeam pt : project.getProjectTeam()) { if (pt.getUser().equals(user)) { inTeam = true; break; } } if (!inTeam) { servletResponse.sendError(Response.Status.FORBIDDEN.getStatusCode(), "You don't have the access right for this application"); return; } if (appState.getAppsmstate() != null && (appState.getAppsmstate().equalsIgnoreCase(YarnApplicationState.FINISHED.toString()) || appState.getAppsmstate().equalsIgnoreCase(YarnApplicationState.KILLED.toString()))) { sendErrorResponse(servletResponse, "This TensorBoard has finished running"); return; } targetUri = uriToFinish; String theHost = "http://" + hostPortPair; URI targetUriHost; try { targetUriObj = new URI(targetUri); targetUriHost = new URI(theHost); } catch (Exception e) { throw new ServletException("Trying to process targetUri init parameter: ", e); } targetHost = URIUtils.extractHost(targetUriHost); servletRequest.setAttribute(ATTR_TARGET_URI, targetUri); servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost); servletRequest.setAttribute(ATTR_URI_FINISH, uriToFinish); servletRequest.setAttribute(ATTR_HOST_PORT, hostPortPair); try { super.service(servletRequest, servletResponse); } catch (IOException ex) { sendErrorResponse(servletResponse, "This TensorBoard is not running right now"); return; } } else { servletResponse.sendError(Response.Status.FORBIDDEN.getStatusCode(), "You don't have the access right for this application"); return; } }
From source file:org.apache.hadoop.security.token.delegation.web.DelegationTokenAuthenticationFilter.java
@Override protected void doFilter(FilterChain filterChain, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { boolean requestCompleted = false; UserGroupInformation ugi = null;/*from ww w .java2 s.c om*/ AuthenticationToken authToken = (AuthenticationToken) request.getUserPrincipal(); if (authToken != null && authToken != AuthenticationToken.ANONYMOUS) { // if the request was authenticated because of a delegation token, // then we ignore proxyuser (this is the same as the RPC behavior). ugi = (UserGroupInformation) request .getAttribute(DelegationTokenAuthenticationHandler.DELEGATION_TOKEN_UGI_ATTRIBUTE); if (ugi == null) { String realUser = request.getUserPrincipal().getName(); ugi = UserGroupInformation.createRemoteUser(realUser, handlerAuthMethod); String doAsUser = getDoAs(request); if (doAsUser != null) { ugi = UserGroupInformation.createProxyUser(doAsUser, ugi); try { ProxyUsers.authorize(ugi, request.getRemoteAddr()); } catch (AuthorizationException ex) { HttpExceptionUtils.createServletExceptionResponse(response, HttpServletResponse.SC_FORBIDDEN, ex); requestCompleted = true; } } } UGI_TL.set(ugi); } if (!requestCompleted) { final UserGroupInformation ugiF = ugi; try { request = new HttpServletRequestWrapper(request) { @Override public String getAuthType() { return (ugiF != null) ? handlerAuthMethod.toString() : null; } @Override public String getRemoteUser() { return (ugiF != null) ? ugiF.getShortUserName() : null; } @Override public Principal getUserPrincipal() { return (ugiF != null) ? new Principal() { @Override public String getName() { return ugiF.getUserName(); } } : null; } }; super.doFilter(filterChain, request, response); } finally { UGI_TL.remove(); } } }
From source file:nl.b3p.kaartenbalie.service.servlet.CallScriptingServlet.java
/** * Checks the login session or credentials * * @param request The incoming request//from ww w . j a va 2 s. c o m * @param em The entityManager * @param pcode * @return The user Principal * @throws AccessDeniedException if the user can not be authenticated */ protected User checkLogin(HttpServletRequest request, EntityManager em, String pcode) throws AccessDeniedException { User user = (User) request.getUserPrincipal(); if (user != null) { log.info("Cookie accepted for login, username: " + user.getName()); return user; } // Try preemptive basic login // attempt to dig out authentication info only if the user has not yet been authenticated String authorizationHeader = request.getHeader("Authorization"); if (authorizationHeader != null) { String decoded = decodeBasicAuthorizationString(authorizationHeader); String username = parseUsername(decoded); String password = parsePassword(decoded); String encpw = null; try { encpw = KBCrypter.encryptText(password); } catch (Exception ex) { log.error("error encrypting password: ", ex); } try { user = (User) em .createQuery("from User " + "where lower(username) = lower(:username) " + "and password = :password ") .setParameter("username", username).setParameter("password", encpw).getSingleResult(); em.flush(); } catch (NonUniqueResultException nue) { log.error( "More than one person found for these credentials (to be fixed in database), trying next method."); user = null; } catch (NoResultException nre) { user = null; log.debug("No results using encrypted password, trying next method"); } // extra check voor oude non-encrypted passwords if (user == null) { try { user = (User) em .createQuery("from User " + "where lower(username) = lower(:username) " + "and password = :password ") .setParameter("username", username).setParameter("password", encpw).getSingleResult(); // Volgende keer dus wel encrypted user.setPassword(encpw); em.merge(user); em.flush(); if (!user.checkRole("beheerder")) { throw new NoResultException("Not a admin"); } log.debug("Cleartext password now encrypted!"); } catch (NonUniqueResultException nue) { log.error( "More than one person found for these (cleartext) credentials (to be fixed in database), trying next method."); user = null; } catch (NoResultException nre) { log.debug("No results using cleartext password, trying next method."); } } } if (user != null && user.checkRole("beheerder")) { log.info("Basic authentication accepted for login, username: " + user.getName()); return user; } else { throw new AccessDeniedException( "Authorisation required for this service! No credentials found in Personal url, Authentication header or Cookie, Giving up! "); } }
From source file:com.betfair.tornjak.monitor.overlay.AuthUtilsTest.java
@Test public void testSuccessfulAuthorisation() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); ServletContext context = mock(ServletContext.class); Principal p = mock(Principal.class); when(context.getAttribute("com.betfair.tornjak.monitor.overlay.RolePerms")) .thenReturn(new AuthBuilder().role("jmxadmin").allow(".*:.*:.*").getRolePerms()); when(request.getUserPrincipal()).thenReturn(p); when(request.isUserInRole("jmxadmin")).thenReturn(true); Auth auth = AuthUtils.checkAuthorised(request, response, context); assertThat("User should be authorised", auth.check(), equalTo(AUTHORISED)); }
From source file:com.betfair.tornjak.monitor.overlay.AuthUtilsTest.java
@Test public void testNotAuthorised() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); ServletContext context = mock(ServletContext.class); Principal p = mock(Principal.class); when(context.getAttribute("com.betfair.tornjak.monitor.overlay.RolePerms")) .thenReturn(new AuthBuilder().role("jmxadmin").allow(".*:.*:.*").getRolePerms()); when(request.getUserPrincipal()).thenReturn(p); when(request.isUserInRole("jmxadmin")).thenReturn(false); Auth auth = AuthUtils.checkAuthorised(request, response, context); assertThat("User should not be authorised", auth, nullValue()); verify(response, times(1)).sendError(HttpServletResponse.SC_FORBIDDEN); verifyNoMoreInteractions(response);// ww w .j a v a 2 s.c o m }
From source file:com.pivotal.gemfire.tools.pulse.internal.controllers.PulseController.java
/** * Method isUserLoggedIn Check whether user is logged in or not. * //w w w .j a v a 2 s. co m * @param request * @return boolean */ protected boolean isUserLoggedIn(HttpServletRequest request) { if (null != request.getUserPrincipal()) { return true; } else { return false; } }
From source file:io.hops.hopsworks.api.kibana.KibanaProxyServlet.java
/** * Authorize user to access particular index. * * @param servletRequest// www . j a v a2 s .com * @param servletResponse * @throws ServletException * @throws IOException */ @Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { if (servletRequest.getUserPrincipal() == null) { servletResponse.sendError(401, "User is not logged in"); return; } String email = servletRequest.getUserPrincipal().getName(); if (servletRequest.getParameterMap().containsKey("projectId")) { String projectId = servletRequest.getParameterMap().get("projectId")[0]; try { ProjectDTO projectDTO = projectController.getProjectByID(Integer.parseInt(projectId)); currentProjects.put(email, projectDTO.getProjectName()); } catch (ProjectException ex) { LOG.log(Level.SEVERE, null, ex); servletResponse.sendError(403, "Kibana was not accessed from Hopsworks, no current project information is available."); return; } } //Do not authorize admin if (email.equals(Settings.AGENT_EMAIL)) { super.service(servletRequest, servletResponse); return; } MyRequestWrapper myRequestWrapper = new MyRequestWrapper((HttpServletRequest) servletRequest); KibanaFilter kibanaFilter = null; //Filter requests based on path if (servletRequest.getRequestURI().contains("api/saved_objects")) { kibanaFilter = KibanaFilter.KIBANA_SAVED_OBJECTS_API; } else if (servletRequest.getRequestURI().contains("elasticsearch/*/_search")) { kibanaFilter = KibanaFilter.ELASTICSEARCH_SEARCH; } else if (servletRequest.getRequestURI().contains("legacy_scroll_start") || servletRequest.getRequestURI().contains("settings/defaultIndex")) { return; } //initialize request attributes from caches if unset by a subclass by this point if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) { servletRequest.setAttribute(ATTR_TARGET_URI, targetUri); } if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) { servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost); } // Make the Request //note: we won't transfer the protocol version because I'm not sure it would truly be compatible String method = servletRequest.getMethod(); String proxyRequestUri = rewriteUrlFromRequest(servletRequest); HttpRequest proxyRequest; //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body. if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) { HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri); // Add the input entity (streamed) // note: we don't bother ensuring we close the servletInputStream since the container handles it eProxyRequest.setEntity( new InputStreamEntity(myRequestWrapper.getInputStream(), servletRequest.getContentLength())); proxyRequest = eProxyRequest; } else { proxyRequest = new BasicHttpRequest(method, proxyRequestUri); } copyRequestHeaders(servletRequest, proxyRequest); super.setXForwardedForHeader(servletRequest, proxyRequest); HttpResponse proxyResponse = null; try { // Execute the request LOG.log(Level.FINE, "proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); proxyResponse = super.proxyClient.execute(super.getTargetHost(myRequestWrapper), proxyRequest); // Process the response int statusCode = proxyResponse.getStatusLine().getStatusCode(); if (doResponseRedirectOrNotModifiedLogic(myRequestWrapper, servletResponse, proxyResponse, statusCode)) { //the response is already "committed" now without any body to send //TODO copy response headers? return; } // Pass the response code. This method with the "reason phrase" is // deprecated but it's the only way to pass the reason along too. //noinspection deprecation servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase()); copyResponseHeaders(proxyResponse, servletRequest, servletResponse); // Send the content to the client copyResponseEntity(proxyResponse, servletResponse, kibanaFilter, email); } catch (Exception e) { //abort request, according to best practice with HttpClient if (proxyRequest instanceof AbortableHttpRequest) { AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest; abortableHttpRequest.abort(); } if (e instanceof RuntimeException) { throw (RuntimeException) e; } if (e instanceof ServletException) { throw (ServletException) e; } //noinspection ConstantConditions if (e instanceof IOException) { throw (IOException) e; } throw new RuntimeException(e); } finally { // make sure the entire entity was consumed, so the connection is released if (proxyResponse != null) { consumeQuietly(proxyResponse.getEntity()); } //Note: Don't need to close servlet outputStream: // http://stackoverflow.com/questions/1159168/should-one-call-close-on- //httpservletresponse-getoutputstream-getwriter } }
From source file:com.example.HoneycombFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { chain.doFilter(request, response); return;//ww w . j a va 2 s . c om } HttpServletRequest req = (HttpServletRequest) request; long start = System.nanoTime(); try { chain.doFilter(request, response); } finally { long responseTimeNanos = System.nanoTime() - start; Event event = libhoney.newEvent(); event.addField("method", req.getMethod()); event.addField("path", req.getRequestURI()); event.addField("query", req.getQueryString()); Principal principal = req.getUserPrincipal(); if (principal != null) { event.addField("user", principal.getName()); } event.addField("host", req.getRemoteHost()); event.addField("responseTimeNanos", responseTimeNanos); try { event.send(); } catch (HoneyException e) { log.error(e.getMessage(), e); } } }
From source file:net.unicon.cas.chalkwire.servlet.CasChalkWireHttpServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {/* w w w . j a v a 2 s . c om*/ if (req.getRemoteUser() == null) throw new ServletException("User is not authenticated. Check the CAS client log files for details"); String userId = req.getUserPrincipal().getName(); if (logger.isDebugEnabled()) logger.debug("Received login request from user " + userId); final String URL = buildSingleSignOnTokenRequestUrl(userId); if (logger.isDebugEnabled()) { logger.debug("Requesing security token from ePortfolio Connect Server"); logger.debug("Requesting url:" + URL); } /* * Send the single sign-on request url to server and parse the response. */ ChalkWireResponseParser parser = new ChalkWireResponseParser(URL); if (logger.isDebugEnabled()) logger.debug("Response is success:" + parser.isSuccess()); if (parser.isSuccess()) { if (logger.isDebugEnabled()) logger.debug("url: " + parser.getURL()); if (logger.isDebugEnabled()) logger.debug("token: " + parser.getToken()); String finalURL = buildFinalSingleSignOnUrl(userId, parser); if (logger.isDebugEnabled()) logger.debug("Single sign-on URL:" + finalURL); parser = new ChalkWireResponseParser(finalURL); if (!parser.isSuccess()) throw new ServletException(parser.getMessage()); resp.sendRedirect(finalURL); } else throw new ServletException(parser.getMessage()); } catch (ServletException e) { logger.error(e.getMessage(), e); String casServerLoginUrl = getServletContext().getInitParameter("casServerLoginUrl"); String service = req.getRequestURL().toString(); casServerLoginUrl += "login?renew=true&service=" + URLEncoder.encode(service, ENCODING_TYPE); RequestDispatcher dispatcher = getServletContext() .getRequestDispatcher("/WEB-INF/view/jsp/chalkWireError.jsp"); req.setAttribute("exception", e); if (logger.isDebugEnabled()) logger.debug("Constructed CAS login url:" + casServerLoginUrl); req.setAttribute("loginUrl", casServerLoginUrl); dispatcher.forward(req, resp); } }