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.overlord.dtgov.taskapi.TaskApi.java
/** * Asserts that a user is logged in and then returns the user's id. * @param httpRequest//from w ww .ja v a 2 s .c o m * @throws Exception */ protected String assertCurrentUser(HttpServletRequest httpRequest) throws Exception { Principal principal = httpRequest.getUserPrincipal(); if (principal == null) { throw new Exception(Messages.i18n.format("TaskApi.NoAuthError")); //$NON-NLS-1$ } return principal.getName(); }
From source file:org.nuxeo.ecm.platform.ui.web.auth.cas2.SecurityExceptionHandler.java
@Override public void handleException(HttpServletRequest request, HttpServletResponse response, Throwable t) throws IOException, ServletException { Throwable unwrappedException = unwrapException(t); if (!ExceptionHelper.isSecurityError(unwrappedException) && !response.containsHeader(SSO_INITIAL_URL_REQUEST_KEY)) { super.handleException(request, response, t); return;/* www .j a va 2s. co m*/ } Principal principal = request.getUserPrincipal(); NuxeoPrincipal nuxeoPrincipal = null; if (principal instanceof NuxeoPrincipal) { nuxeoPrincipal = (NuxeoPrincipal) principal; // redirect to login than to requested page if (nuxeoPrincipal.isAnonymous()) { response.resetBuffer(); String urlToReach = getURLToReach(request); Cookie cookieUrlToReach = new Cookie(NXAuthConstants.SSO_INITIAL_URL_REQUEST_KEY, urlToReach); cookieUrlToReach.setPath("/"); cookieUrlToReach.setMaxAge(60); response.addCookie(cookieUrlToReach); if (!response.isCommitted()) { request.getRequestDispatcher(CAS_REDIRECTION_URL).forward(request, response); } FacesContext.getCurrentInstance().responseComplete(); } } // go back to default handler super.handleException(request, response, t); }
From source file:org.josso.spring.acegi.JOSSOProcessingFilter.java
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { if (!(servletRequest instanceof HttpServletRequest)) { throw new IllegalArgumentException("Non HTTP request unsupported by this filter"); }/*from w w w .j a v a2 s.c o m*/ if (!(servletResponse instanceof HttpServletResponse)) { throw new IllegalArgumentException("Non HTTP response unsupported by this filter"); } HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; // We have to provide Authentication information based on JOSSO auth information ... // This is the principal as injected by JOSSO in the container : Principal principal = request.getUserPrincipal(); // This is the authentication information used by ACEGI Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); // If authentication information is present, we only need to validate that it is up to date. if (authentication != null) { if (logger.isDebugEnabled()) { logger.debug("Authentication information already present : '" + SecurityContextHolder.getContext().getAuthentication() + "'"); } // If there is no principal, we may need to logout this user ... TODO detect anonymous principals ? if (principal == null && authentication.isAuthenticated()) { // If an authenticated Authentication is present, we must issue a logout ! if (logger.isDebugEnabled()) { logger.debug("Logging out user '" + authentication + "'"); } for (int i = 0; i < handlers.length; i++) { handlers[i].logout(request, response, authentication); } } chain.doFilter(request, response); return; } // We have a principal but no ACEGI authentication, propagate identity from JOSSO to ACEGI. if (principal != null) { // If a saved request is present, we use the saved request to redirect the user to the original resource. SavedRequest savedRequest = (SavedRequest) request.getSession() .getAttribute(AbstractProcessingFilter.ACEGI_SAVED_REQUEST_KEY); if (savedRequest != null) logger.debug("Redirecting to original resource " + savedRequest.getFullRequestUrl()); UserDetails userDetails = userDetailsService.loadUserByUsername(principal.getName()); String jossoSessionId = (String) request.getAttribute("org.josso.agent.ssoSessionid"); // New authenticated autentication instance. Authentication jossoAuth = new JOSSOAuthenticationToken(jossoSessionId, userDetails, userDetails.getAuthorities()); // Store to SecurityContextHolder SecurityContextHolder.getContext().setAuthentication(jossoAuth); if (logger.isDebugEnabled()) { logger.debug("SecurityContextHolder populated with JOSSO Authentication Token: '" + SecurityContextHolder.getContext().getAuthentication() + "'"); } // Fire event if (this.eventPublisher != null) { eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent( SecurityContextHolder.getContext().getAuthentication(), this.getClass())); } // We have a saved request, redirect to original URL ... if (savedRequest != null) response.sendRedirect(savedRequest.getFullRequestUrl()); } else { if (logger.isDebugEnabled()) logger.debug("No principal found in request !"); } // Move on ... chain.doFilter(request, response); }
From source file:io.hops.hopsworks.api.admin.HDFSUIProxyServlet.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { if (servletRequest.getUserPrincipal() == null) { servletResponse.sendError(403, "User is not logged in"); return;/* www .j a v a 2 s .c o m*/ } if (!servletRequest.isUserInRole("HOPS_ADMIN")) { servletResponse.sendError(Response.Status.BAD_REQUEST.getStatusCode(), "You don't have the access right for this service"); return; } 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 proxyRequestUri = rewriteUrlFromRequest(servletRequest); try { String[] targetHost_port = settings.getHDFSWebUIAddress().split(":"); File keyStore = new File(baseHadoopClientsService.getSuperKeystorePath()); File trustStore = new File(baseHadoopClientsService.getSuperTrustStorePath()); // Assume that KeyStore password and Key password are the same Protocol httpsProto = new Protocol("https", new CustomSSLProtocolSocketFactory(keyStore, baseHadoopClientsService.getSuperKeystorePassword(), baseHadoopClientsService.getSuperKeystorePassword(), trustStore, baseHadoopClientsService.getSuperTrustStorePassword()), Integer.parseInt(targetHost_port[1])); Protocol.registerProtocol("https", httpsProto); // Execute the request HttpClientParams params = new HttpClientParams(); params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); HttpClient client = new HttpClient(params); HostConfiguration config = new HostConfiguration(); InetAddress localAddress = InetAddress.getLocalHost(); config.setLocalAddress(localAddress); HttpMethod m = new GetMethod(proxyRequestUri); Enumeration<String> names = servletRequest.getHeaderNames(); while (names.hasMoreElements()) { String headerName = names.nextElement(); String value = servletRequest.getHeader(headerName); if (PASS_THROUGH_HEADERS.contains(headerName)) { //hdfs does not send back the js if encoding is not accepted //but we don't want to accept encoding for the html because we //need to be able to parse it if (headerName.equalsIgnoreCase("accept-encoding") && (servletRequest.getPathInfo() == null || !servletRequest.getPathInfo().contains(".js"))) { continue; } else { m.setRequestHeader(headerName, value); } } } String user = servletRequest.getRemoteUser(); if (user != null && !user.isEmpty()) { m.setRequestHeader("Cookie", "proxy-user" + "=" + URLEncoder.encode(user, "ASCII")); } client.executeMethod(config, m); // Process the response int statusCode = m.getStatusCode(); // 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, m.getStatusLine().getReasonPhrase()); copyResponseHeaders(m, servletRequest, servletResponse); // Send the content to the client copyResponseEntity(m, servletResponse); } catch (Exception e) { 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); } }
From source file:it.volaconnoi.servlet.BookingServlet.java
/** * Handles the HTTP <code>GET</code> method. * * @param request servlet request/*from ww w .ja va 2 s .c o m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userPath = request.getServletPath(); session = request.getSession(true); if (userPath.equals("/booking")) { String route_id = request.getParameter("id"); session.setAttribute("route", routeManagerBean.getRouteById(route_id)); if (request.getUserPrincipal() != null) { UserCredential user = userManagerBean.getUserByUsername(request.getUserPrincipal().getName()); session.setAttribute("user", user); } request.setAttribute("CountriesList", countryFacade.findAll()); request.setAttribute("tax", PricerBeanInterface.TAX); request.getRequestDispatcher("/WEB-INF/view/booking/booking.jsp").forward(request, response); } }
From source file:org.nuxeo.ecm.platform.web.common.exceptionhandling.DefaultNuxeoExceptionHandler.java
@Override public void handleException(HttpServletRequest request, HttpServletResponse response, Throwable t) throws IOException, ServletException { Throwable unwrappedException = ExceptionHelper.unwrapException(t); // check for Anonymous case if (ExceptionHelper.isSecurityError(unwrappedException)) { Principal principal = request.getUserPrincipal(); if (principal instanceof NuxeoPrincipal) { NuxeoPrincipal nuxeoPrincipal = (NuxeoPrincipal) principal; if (nuxeoPrincipal.isAnonymous()) { // redirect to login than to requested page if (handleAnonymousException(request, response)) { return; }//from ww w . j a v a 2s. co m } } } startHandlingException(request, response, t); try { ErrorHandler handler = getHandler(t); Integer code = handler.getCode(); int status = code == null ? HttpServletResponse.SC_INTERNAL_SERVER_ERROR : code.intValue(); parameters.getListener().startHandling(t, request, response); StringWriter swriter = new StringWriter(); PrintWriter pwriter = new PrintWriter(swriter); t.printStackTrace(pwriter); String stackTrace = swriter.getBuffer().toString(); if (status < HttpServletResponse.SC_INTERNAL_SERVER_ERROR) { // 500 log.debug(t.getMessage(), t); } else { log.error(stackTrace); parameters.getLogger().error(stackTrace); } parameters.getListener().beforeSetErrorPageAttribute(unwrappedException, request, response); request.setAttribute("exception_message", unwrappedException.getLocalizedMessage()); request.setAttribute("user_message", getUserMessage(handler.getMessage(), request.getLocale())); request.setAttribute("securityError", ExceptionHelper.isSecurityError(unwrappedException)); request.setAttribute("messageBundle", ResourceBundle.getBundle(parameters.getBundleName(), request.getLocale(), Thread.currentThread().getContextClassLoader())); String dumpedRequest = parameters.getRequestDumper().getDump(request); if (status >= HttpServletResponse.SC_INTERNAL_SERVER_ERROR) { // 500 parameters.getLogger().error(dumpedRequest); } request.setAttribute("isDevModeSet", Framework.isDevModeSet()); if (Framework.isDevModeSet()) { request.setAttribute("stackTrace", stackTrace); request.setAttribute("request_dump", dumpedRequest); } parameters.getListener().beforeForwardToErrorPage(unwrappedException, request, response); if (!response.isCommitted()) { response.setStatus(status); String errorPage = handler.getPage(); errorPage = (errorPage == null) ? parameters.getDefaultErrorPage() : errorPage; RequestDispatcher requestDispatcher = request.getRequestDispatcher(errorPage); if (requestDispatcher != null) { requestDispatcher.forward(request, response); } else { log.error("Cannot forward to error page, " + "no RequestDispatcher found for errorPage=" + errorPage + " handler=" + handler); } parameters.getListener().responseComplete(); } else { // do not throw an error, just log it: afterDispatch needs to // be called, and sometimes the initial error is a // ClientAbortException log.error("Cannot forward to error page: " + "response is already committed"); } parameters.getListener().afterDispatch(unwrappedException, request, response); } catch (ServletException e) { throw e; } catch (RuntimeException | IOException e) { throw new ServletException(e); } }
From source file:org.ecocean.ApiAccess.java
public HashMap<String, String> permissions(String cname, HttpServletRequest request) { HashMap<String, String> perm = new HashMap<String, String>(); this.initConfig(request); String context = "context0"; context = ServletUtilities.getContext(request); Shepherd myShepherd = new Shepherd(context); myShepherd.setAction("ApiAccess.class"); myShepherd.beginDBTransaction();//from www .ja v a2 s.c om String username = ""; if (request.getUserPrincipal() != null) username = request.getUserPrincipal().getName(); List<Role> roleObjs = myShepherd.getAllRolesForUserInContext(username, context); List<String> roles = new ArrayList<String>(); for (Role r : roleObjs) { roles.add(r.getRolename()); } System.out.println("[class " + cname + "] roles for user '" + username + "': " + roles); NodeList nlist = this.configDoc.getDocumentElement().getElementsByTagName("class"); if (nlist.getLength() < 1) { myShepherd.rollbackDBTransaction(); myShepherd.closeDBTransaction(); return perm; } for (int i = 0; i < nlist.getLength(); i++) { Node n = nlist.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { Element el = (Element) n; if (el.getAttribute("name").equals(cname)) { Node p = el.getElementsByTagName("properties").item(0); if (p == null) { myShepherd.rollbackDBTransaction(); myShepherd.closeDBTransaction(); return perm; } //System.out.println("ok in " + cname); Element propsEl = (Element) p; NodeList props = propsEl.getElementsByTagName("property"); for (int j = 0; j < props.getLength(); j++) { if (props.item(j).getNodeType() == Node.ELEMENT_NODE) { Element pel = (Element) props.item(j); String propName = pel.getAttribute("name"); if (propName != null) { ///////////// TODO for now we assume we ONLY have a sub element for <write> perm here so we skip a step NodeList proles = pel.getElementsByTagName("role"); boolean allowed = false; for (int k = 0; k < proles.getLength(); k++) { if (roles.contains(proles.item(k).getTextContent())) { allowed = true; k = proles.getLength() + 1; } } if (!allowed) perm.put(propName, "deny"); } } } } } } System.out.println(perm); myShepherd.rollbackDBTransaction(); myShepherd.closeDBTransaction(); return perm; }
From source file:org.owasp.webgoat.controller.Start.java
/** * <p>start.</p>//w w w . j a v a 2s .c o m * * @param request a {@link javax.servlet.http.HttpServletRequest} object. * @param error a {@link java.lang.String} object. * @param logout a {@link java.lang.String} object. * @return a {@link org.springframework.web.servlet.ModelAndView} object. */ @RequestMapping(value = "start.mvc", method = { RequestMethod.GET, RequestMethod.POST }) public ModelAndView start(HttpServletRequest request, @RequestParam(value = "error", required = false) String error, @RequestParam(value = "logout", required = false) String logout) { ModelAndView model = new ModelAndView(); // make sure session is set up correctly // if not redirect user to login if (checkWebSession(request.getSession()) == false) { model.setViewName("redirect:/login.mvc"); return model; } String role = getRole(); String user = request.getUserPrincipal().getName(); model.addObject("role", role); model.addObject("user", user); String contactEmail = servletContext.getInitParameter("email"); model.addObject("contactEmail", contactEmail); String emailList = servletContext.getInitParameter("emaillist"); model.addObject("emailList", emailList); Application app = Application.getInstance(); logger.info("Setting application properties: " + app); model.addObject("version", app.getVersion()); model.addObject("build", app.getBuild()); // if everything ok then go to webgoat UI model.setViewName("main_new"); return model; }
From source file:org.broadleafcommerce.profile.web.core.security.CustomerStateFilter.java
@Override public void doFilter(ServletRequest baseRequest, ServletResponse baseResponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) baseRequest; HttpServletResponse response = (HttpServletResponse) baseResponse; Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Customer customer = null;//from w w w . ja v a2 s. c o m if ((authentication != null) && !(authentication instanceof AnonymousAuthenticationToken)) { String userName = request.getUserPrincipal().getName(); customer = (Customer) request.getAttribute(customerRequestAttributeName); if (userName != null && (customer == null || !userName.equals(customer.getUsername()))) { // can only get here if the authenticated user does not match the user in session customer = customerService.readCustomerByUsername(userName); if (logger.isDebugEnabled() && customer != null) { logger.debug("Customer found by username " + userName); } } if (customer != null) { ApplicationEvent lastPublishedEvent = (ApplicationEvent) request.getSession(true) .getAttribute(LAST_PUBLISHED_EVENT_SESSION_ATTRIBUTED_NAME); if (authentication instanceof RememberMeAuthenticationToken) { // set transient property of customer customer.setCookied(true); boolean publishRememberMeEvent = true; if (lastPublishedEvent != null && lastPublishedEvent instanceof CustomerAuthenticatedFromCookieEvent) { CustomerAuthenticatedFromCookieEvent cookieEvent = (CustomerAuthenticatedFromCookieEvent) lastPublishedEvent; if (userName.equals(cookieEvent.getCustomer().getUsername())) { publishRememberMeEvent = false; } } if (publishRememberMeEvent) { CustomerAuthenticatedFromCookieEvent cookieEvent = new CustomerAuthenticatedFromCookieEvent( customer, this.getClass().getName()); eventPublisher.publishEvent(cookieEvent); request.getSession().setAttribute(LAST_PUBLISHED_EVENT_SESSION_ATTRIBUTED_NAME, cookieEvent); } } else if (authentication instanceof UsernamePasswordAuthenticationToken) { customer.setLoggedIn(true); boolean publishLoggedInEvent = true; if (lastPublishedEvent != null && lastPublishedEvent instanceof CustomerLoggedInEvent) { CustomerLoggedInEvent loggedInEvent = (CustomerLoggedInEvent) lastPublishedEvent; if (userName.equals(loggedInEvent.getCustomer().getUsername())) { publishLoggedInEvent = false; } } if (publishLoggedInEvent) { CustomerLoggedInEvent loggedInEvent = new CustomerLoggedInEvent(customer, this.getClass().getName()); eventPublisher.publishEvent(loggedInEvent); request.getSession().setAttribute(LAST_PUBLISHED_EVENT_SESSION_ATTRIBUTED_NAME, loggedInEvent); } } else { customer = null; } } } if (customer == null) { // This is an anonymous customer. // TODO: Handle a custom cookie (different than remember me) that is just for anonymous users. // This can be used to remember their cart from a previous visit. // Cookie logic probably needs to be configurable - with TCS as the exception. customer = resolveAnonymousCustomer(request); } request.setAttribute(customerRequestAttributeName, customer); // Setup customer for content rule processing Map<String, Object> ruleMap = (Map<String, Object>) request.getAttribute(BLC_RULE_MAP_PARAM); if (ruleMap == null) { ruleMap = new HashMap<String, Object>(); } ruleMap.put("customer", customer); request.setAttribute(BLC_RULE_MAP_PARAM, ruleMap); chain.doFilter(request, response); }
From source file:demo.oauth.server.spring.SpringOAuthAuthenticationFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; List<String> authorities = (List<String>) request.getAttribute(OAUTH_AUTHORITIES); List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(); if (authorities != null) { for (String authority : authorities) { grantedAuthorities.add(new GrantedAuthorityImpl(authority)); }//from ww w. ja v a 2s .c o m Authentication auth = new AnonymousAuthenticationToken(UUID.randomUUID().toString(), req.getUserPrincipal(), grantedAuthorities); SecurityContextHolder.getContext().setAuthentication(auth); } chain.doFilter(req, resp); }