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:com.iorga.webappwatcher.RequestLogFilter.java
@SuppressWarnings("unchecked") private RequestEventLog createRequestEventLog(final HttpServletRequest httpRequest, final String requestURI) { final RequestEventLog logRequest = EventLogManager.getInstance().addEventLog(RequestEventLog.class); logRequest.setRequestURI(requestURI); logRequest.setMethod(httpRequest.getMethod()); final Enumeration<String> parameterNames = httpRequest.getParameterNames(); final List<Parameter> parameters = new LinkedList<Parameter>(); while (parameterNames.hasMoreElements()) { final String parameterName = parameterNames.nextElement(); parameters.add(new Parameter(parameterName, httpRequest.getParameterValues(parameterName))); }/*from ww w .ja va 2 s . c om*/ logRequest.setParameters(parameters.toArray(new Parameter[parameters.size()])); final Enumeration<String> headerNames = httpRequest.getHeaderNames(); final List<Header> headers = new LinkedList<Header>(); while (headerNames.hasMoreElements()) { final String headerName = headerNames.nextElement(); headers.add(new Header(headerName, httpRequest.getHeader(headerName))); } logRequest.setHeaders(headers.toArray(new Header[headers.size()])); final Principal userPrincipal = httpRequest.getUserPrincipal(); if (userPrincipal != null) { logRequest.setPrincipal(userPrincipal.getName()); } final Thread currentThread = Thread.currentThread(); logRequest.setThreadName(currentThread.getName()); logRequest.setThreadId(currentThread.getId()); return logRequest; }
From source file:org.nuxeo.ecm.platform.oauth2.openid.web.OAuth2CallbackHandlerServlet.java
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { // Getting the "error" URL parameter String error = req.getParameter(ERROR_URL_PARAM_NAME); // / Checking if there was an error such as the user denied access if (error != null && error.length() > 0) { resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "There was an error: \"" + error + "\"."); return;/*from w w w .ja v a2 s. c om*/ } // Getting the "code" URL parameter String code = req.getParameter(CODE_URL_PARAM_NAME); // Checking conditions on the "code" URL parameter if (code == null || code.isEmpty()) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "There was an error: \"" + error + "\"."); return; } String path = req.getRequestURI().split(URL_MAPPING + "/")[1]; String[] parts = path.split("/"); String serviceProviderName = parts[0]; NuxeoOAuth2ServiceProvider provider; try { provider = getServiceProvider(serviceProviderName); if (provider == null) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "No service provider called: \"" + serviceProviderName + "\"."); return; } AuthorizationCodeFlow flow = provider.getAuthorizationCodeFlow(HTTP_TRANSPORT, JSON_FACTORY); String redirectUri = req.getRequestURL().toString(); Principal principal = req.getUserPrincipal(); HttpResponse response = flow.newTokenRequest(code).setRedirectUri(redirectUri).executeUnparsed(); TokenResponse tokenResponse = response.parseAs(TokenResponse.class); // Validate the token String accessToken = tokenResponse.getAccessToken(); HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() { @Override public void initialize(HttpRequest request) throws IOException { request.setParser(new JsonObjectParser(JSON_FACTORY)); } }); GenericUrl url = new GenericUrl("https://www.googleapis.com/oauth2/v1/tokeninfo"); url.set("access_token", accessToken); HttpRequest request = requestFactory.buildGetRequest(url); response = request.execute(); // TODO - get the email String email = "nelson.silva@gmail.com"; UserManager manager = Framework.getLocalService(UserManager.class); Map<String, Serializable> query = new HashMap<String, Serializable>(); query.put(manager.getUserEmailField(), email); DocumentModelList users = manager.searchUsers(query, null); if (users.isEmpty()) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "No user found with email: \"" + email + "\"."); } DocumentModel user = users.get(0); String userId = (String) user.getPropertyValue(manager.getUserIdField()); Framework.loginAs(userId); LoginContext loginContext = NuxeoAuthenticationFilter.loginAs(userId); loginContext.login(); resp.sendRedirect(req.getContextPath()); } catch (Exception e) { log.error("Error while processing OAuth2 Callback", e); } }
From source file:com.salesmanBuddy.Controllers.SalesmanBuddy.java
@Path("reports") // Updated 10/23 @PUT//from ww w. ja v a 2s.c o m @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN }) public Response putReport(@Context HttpServletRequest request, UserTree o, @DefaultValue("0") @QueryParam("dealershipId") Integer dealershipId, @DefaultValue("0") @QueryParam("reportType") Integer reportType, @DefaultValue("") @QueryParam("email") String email) { if (dealershipId == 0 || reportType == 0 || email.length() == 0) return Response.status(400).entity("You must specify a dealershipId, report type, email").build(); String googleUserId = request.getUserPrincipal().getName(); Users user = this.dao.getUserByGoogleId(googleUserId); if (user.getType() > 2 || (this.dao.getUsersForDealershipId(dealershipId).contains(user) && user.getType() > 1)) return Response.ok(this.dao.sendOnDemandReport(reportType, dealershipId, email)).build(); return Response.status(400).entity("You must have the rights for this dealership").build(); }
From source file:net.java.jaspicoil.MSPacSpnegoServerAuthModule.java
/** * Log the request for debug purpose//ww w .ja va2s . co m * * @param request * the HTTP Servlet Request */ private void debugRequest(HttpServletRequest request) { if (this.debug || LOG.isLoggable(Level.FINE)) { final StringBuffer sb = new StringBuffer(); sb.append("\n"); try { sb.append("Request: ").append(request.getRequestURL()).append("\n"); sb.append("UserPrincipal: ").append(request.getUserPrincipal()).append("\n"); sb.append("AuthType: ").append(request.getAuthType()).append("\n"); sb.append("Headers:\n"); @SuppressWarnings("rawtypes") final Enumeration names = request.getHeaderNames(); while (names.hasMoreElements()) { final String name = (String) names.nextElement(); sb.append("\t").append(name).append("\t").append(request.getHeader(name)).append("\n"); } LOG.log(this.debugLevel, "HTTP Request is : {0}", sb); } catch (final Throwable t) { LOG.log(Level.WARNING, "An unexpected problem has occured during log : {0}", t); } } }
From source file:org.esigate.servlet.impl.RequestFactory.java
public IncomingRequest create(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException { HttpServletRequestContext context = new HttpServletRequestContext(request, response, servletContext, filterChain);// www. j a va 2s . co m // create request line String uri = UriUtils.createURI(request.getScheme(), request.getServerName(), request.getServerPort(), request.getRequestURI(), request.getQueryString(), null); ProtocolVersion protocolVersion = BasicLineParser.parseProtocolVersion(request.getProtocol(), null); IncomingRequest.Builder builder = IncomingRequest .builder(new BasicRequestLine(request.getMethod(), uri, protocolVersion)); builder.setContext(context); // copy headers @SuppressWarnings("rawtypes") Enumeration names = request.getHeaderNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); @SuppressWarnings("rawtypes") Enumeration values = request.getHeaders(name); while (values.hasMoreElements()) { String value = (String) values.nextElement(); builder.addHeader(name, value); } } // create entity HttpServletRequestEntity entity = new HttpServletRequestEntity(request); builder.setEntity(entity); builder.setRemoteAddr(request.getRemoteAddr()); builder.setRemoteUser(request.getRemoteUser()); HttpSession session = request.getSession(false); if (session != null) { builder.setSessionId(session.getId()); } builder.setUserPrincipal(request.getUserPrincipal()); // Copy cookies // As cookie header contains only name=value so we don't need to copy // all attributes! javax.servlet.http.Cookie[] src = request.getCookies(); if (src != null) { for (int i = 0; i < src.length; i++) { javax.servlet.http.Cookie c = src[i]; BasicClientCookie dest = new BasicClientCookie(c.getName(), c.getValue()); builder.addCookie(dest); } } builder.setSession(new HttpServletSession(request)); builder.setContextPath(request.getContextPath()); return builder.build(); }
From source file:nl.b3p.kaartenbalie.struts.WMSUrlCreatorAction.java
public ActionForward getMapUrl(ActionMapping mapping, DynaValidatorForm dynaForm, HttpServletRequest request, HttpServletResponse response) throws Exception { if (!isTokenValid(request)) { prepareMethod(dynaForm, request, EDIT, LIST); addAlternateMessage(mapping, request, TOKEN_ERROR_KEY); return getAlternateForward(mapping, request); }//from w w w.j av a 2 s . c o m ActionErrors errors = dynaForm.validate(mapping, request); if (!errors.isEmpty()) { super.addMessages(request, errors); prepareMethod(dynaForm, request, EDIT, LIST); addAlternateMessage(mapping, request, VALIDATION_ERROR_KEY); return getAlternateForward(mapping, request); } //Create the String String[] layers = (String[]) dynaForm.get("sortedLayers"); String projectie = (String) dynaForm.get("selectedProjectie"); String bbox = (String) dynaForm.get("bbox"); Integer height = (Integer) dynaForm.get("height"); Integer width = (Integer) dynaForm.get("width"); String format = (String) dynaForm.get("selectedFormat"); String pUrl = (String) dynaForm.get("personalUrl"); if (layers.length == 0) { prepareMethod(dynaForm, request, LIST, LIST); addAlternateMessage(mapping, request, NO_LAYERS_SELECTED_ERROR_KEY); return getAlternateForward(mapping, request); } /* * Get the URL to start with */ User user = (User) request.getUserPrincipal(); if (user == null) { prepareMethod(dynaForm, request, LIST, LIST); addAlternateMessage(mapping, request, UNKNOWN_SES_USER_ERROR_KEY); return getAlternateForward(mapping, request); } StringBuffer layerString = new StringBuffer(); for (int i = 0; i < layers.length; i++) { layerString.append(layers[i]); layerString.append(","); } String layer = layerString.substring(0, layerString.lastIndexOf(",")); StringBuffer getMapUrl = new StringBuffer(user.getPersonalURL(request)); getMapUrl.append("?"); getMapUrl.append(OGCConstants.WMS_SERVICE); getMapUrl.append("="); getMapUrl.append(OGCConstants.WMS_SERVICE_WMS); getMapUrl.append("&"); getMapUrl.append(OGCConstants.WMS_VERSION); getMapUrl.append("="); getMapUrl.append(OGCConstants.WMS_VERSION_111); getMapUrl.append("&"); getMapUrl.append(OGCConstants.WMS_REQUEST); getMapUrl.append("="); getMapUrl.append(OGCConstants.WMS_REQUEST_GetMap); getMapUrl.append("&"); getMapUrl.append(OGCConstants.WMS_PARAM_LAYERS); getMapUrl.append("="); getMapUrl.append(layer); getMapUrl.append("&"); getMapUrl.append(OGCConstants.WMS_PARAM_BBOX); getMapUrl.append("="); getMapUrl.append(bbox); getMapUrl.append("&"); getMapUrl.append(OGCConstants.WMS_PARAM_SRS); getMapUrl.append("="); getMapUrl.append(projectie); getMapUrl.append("&"); getMapUrl.append(OGCConstants.WMS_PARAM_HEIGHT); getMapUrl.append("="); getMapUrl.append(height); getMapUrl.append("&"); getMapUrl.append(OGCConstants.WMS_PARAM_WIDTH); getMapUrl.append("="); getMapUrl.append(width); getMapUrl.append("&"); getMapUrl.append(OGCConstants.WMS_PARAM_FORMAT); getMapUrl.append("="); getMapUrl.append(format); getMapUrl.append("&"); getMapUrl.append(OGCConstants.WMS_PARAM_BGCOLOR); getMapUrl.append("="); getMapUrl.append("0xF0F0F0"); getMapUrl.append("&"); getMapUrl.append(OGCConstants.WMS_PARAM_EXCEPTIONS); getMapUrl.append("="); getMapUrl.append(OGCConstants.WMS_PARAM_EXCEPTION_INIMAGE); getMapUrl.append("&"); getMapUrl.append(OGCConstants.WMS_PARAM_STYLES); getMapUrl.append("="); user.setDefaultGetMap(getMapUrl.toString()); log.debug("Getting entity manager ......"); EntityManager em = getEntityManager(); if (user.getId() == null) { em.persist(user); } else { em.merge(user); } em.flush(); populateForm(getMapUrl.toString(), dynaForm, request); prepareMethod(dynaForm, request, LIST, EDIT); addDefaultMessage(mapping, request, ACKNOWLEDGE_MESSAGES); return getDefaultForward(mapping, request); }
From source file:it.cnr.icar.eric.server.interfaces.rest.URLHandler.java
URLHandler(HttpServletRequest request, HttpServletResponse response) throws RegistryException { this.request = request; this.response = response; // First see if user context can be gotten from cert is SSLContext for // request//from ww w. j a v a 2 s. c om getUserFromRequest(); if (currentUser == null) { if (SessionManager.getInstance().isSessionEstablished(request)) { currentUser = SessionManager.getInstance().getUserFromSession(request); } } if (currentUser == null) { // Force authentication if so configured. boolean samlMode = Boolean .valueOf(CommonProperties.getInstance().getProperty("eric.common.security.samlMode", "false")) .booleanValue(); boolean forceAuthentication = Boolean.valueOf( CommonProperties.getInstance().getProperty("eric.common.security.forceAuthentication", "false")) .booleanValue(); if (samlMode && forceAuthentication) { // TODO: Need to redirect to AM Login screen } // See if user can be gotten from pricipal currentUser = findUserByPrincipal(request.getUserPrincipal()); boolean establishSession = true; // If the UserType is registryGuest. there was no authentication, // and, // thus, there is no need to create a session if (currentUser == AuthenticationServiceImpl.getInstance().registryGuest) { establishSession = false; } SessionManager.getInstance().establishSession(request, currentUser, establishSession); } if (xFormerFactory == null) { try { xFormerFactory = TransformerFactory.newInstance(); } catch (Throwable t) { log.error(ServerResourceBundle.getInstance().getString( "message.ProblemInitializingTransformerFactory", new Object[] { t.getMessage() })); } } }
From source file:org.sakaiproject.nakamura.auth.trusted.TrustedTokenServiceImpl.java
/** * Inject a token into the request/response, this assumes htat the getUserPrincipal() of the request * or the request.getRemoteUser() contain valid user ID's from which to generate the request. * * * @param req//from www . j a v a 2 s . co m * @param resp * @param readOnlyToken if true, the session or cookie will only allow read only operations in the server. */ public String injectToken(HttpServletRequest request, HttpServletResponse response, String tokenType, UserValidator userValidator) { if (testing) { calls.add(new Object[] { "injectToken", request, response }); return "testing"; } String userId = null; String remoteAddress = request.getRemoteAddr(); if (trustedProxyServerAddrSet.contains(remoteAddress)) { if (trustedHeaderName.length() > 0) { userId = request.getHeader(trustedHeaderName); if (userId != null) { LOG.debug("Injecting Trusted Token from request: Header [{}] indicated user was [{}] ", 0, userId); } } if (userId == null && trustedParameterName.length() > 0) { userId = request.getParameter(trustedParameterName); if (userId != null) { LOG.debug("Injecting Trusted Token from request: Parameter [{}] indicated user was [{}] ", trustedParameterName, userId); } } } if (userId == null) { Principal p = request.getUserPrincipal(); if (p != null) { userId = p.getName(); if (userId != null) { LOG.debug("Injecting Trusted Token from request: User Principal indicated user was [{}] ", userId); } } } if (userId == null) { userId = request.getRemoteUser(); if (userId != null) { LOG.debug("Injecting Trusted Token from request: Remote User indicated user was [{}] ", userId); } } if (userValidator != null) { userId = userValidator.validate(userId); } if (userId != null) { if (usingSession) { HttpSession session = request.getSession(true); if (session != null) { LOG.debug("Injecting Credentials into Session for " + userId); session.setAttribute(SA_AUTHENTICATION_CREDENTIALS, createCredentials(userId, tokenType)); } } else { addCookie(response, userId, tokenType); } Dictionary<String, Object> eventDictionary = new Hashtable<String, Object>(); eventDictionary.put(TrustedTokenService.EVENT_USER_ID, userId); // send an async event to indicate that the user has been trusted, things that want to create users can hook into this. eventAdmin.sendEvent(new Event(TrustedTokenService.TRUST_USER_TOPIC, eventDictionary)); return userId; } else { LOG.warn("Unable to inject token; unable to determine user from request."); } return null; }
From source file:nl.nn.adapterframework.http.RestServiceDispatcher.java
/** * Dispatch a request.//from w w w.ja va2s. c o m * @param uri the name of the IReceiver object * @param method the correlationId of this request; * @param request the <code>String</code> with the request/input * @return String with the result of processing the <code>request</code> throught the <code>serviceName</code> */ public String dispatchRequest(String restPath, String uri, HttpServletRequest httpServletRequest, String etag, String contentType, String request, Map context, HttpServletResponse httpServletResponse, ServletContext servletContext) throws ListenerException { String method = httpServletRequest.getMethod(); if (log.isTraceEnabled()) log.trace("searching listener for uri [" + uri + "] method [" + method + "]"); String matchingPattern = findMatchingPattern(uri); if (matchingPattern == null) { throw new ListenerException("no REST listener configured for uri [" + uri + "]"); } Map methodConfig = getMethodConfig(matchingPattern, method); if (methodConfig == null) { throw new ListenerException("No RestListeners specified for uri [" + uri + "] method [" + method + "]"); } if (context == null) { context = new HashMap(); } context.put("restPath", restPath); context.put("uri", uri); context.put("method", method); context.put("etag", etag); context.put("contentType", contentType); ServiceClient listener = (ServiceClient) methodConfig.get(KEY_LISTENER); String etagKey = (String) methodConfig.get(KEY_ETAG_KEY); String contentTypeKey = (String) methodConfig.get(KEY_CONTENT_TYPE_KEY); Principal principal = null; if (httpServletRequest != null) { principal = httpServletRequest.getUserPrincipal(); if (principal != null) { context.put("principal", principal.getName()); } } String ctName = Thread.currentThread().getName(); try { boolean writeToSecLog = false; if (listener instanceof RestListener) { RestListener restListener = (RestListener) listener; if (restListener.isRetrieveMultipart()) { if (ServletFileUpload.isMultipartContent(httpServletRequest)) { try { DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); List<FileItem> items = servletFileUpload.parseRequest(httpServletRequest); for (FileItem item : items) { if (item.isFormField()) { // Process regular form field (input type="text|radio|checkbox|etc", select, etc). String fieldName = item.getFieldName(); String fieldValue = item.getString(); log.debug("setting parameter [" + fieldName + "] to [" + fieldValue + "]"); context.put(fieldName, fieldValue); } else { // Process form file field (input type="file"). String fieldName = item.getFieldName(); String fieldNameName = fieldName + "Name"; String fileName = FilenameUtils.getName(item.getName()); if (log.isTraceEnabled()) log.trace( "setting parameter [" + fieldNameName + "] to [" + fileName + "]"); context.put(fieldNameName, fileName); InputStream inputStream = item.getInputStream(); if (inputStream.available() > 0) { log.debug("setting parameter [" + fieldName + "] to input stream of file [" + fileName + "]"); context.put(fieldName, inputStream); } else { log.debug("setting parameter [" + fieldName + "] to [" + null + "]"); context.put(fieldName, null); } } } } catch (FileUploadException e) { throw new ListenerException(e); } catch (IOException e) { throw new ListenerException(e); } } } writeToSecLog = restListener.isWriteToSecLog(); if (writeToSecLog) { context.put("writeSecLogMessage", restListener.isWriteSecLogMessage()); } boolean authorized = false; if (principal == null) { authorized = true; } else { String authRoles = restListener.getAuthRoles(); if (StringUtils.isNotEmpty(authRoles)) { StringTokenizer st = new StringTokenizer(authRoles, ",;"); while (st.hasMoreTokens()) { String authRole = st.nextToken(); if (httpServletRequest.isUserInRole(authRole)) { authorized = true; } } } } if (!authorized) { throw new ListenerException("Not allowed for uri [" + uri + "]"); } Thread.currentThread().setName(restListener.getName() + "[" + ctName + "]"); } if (etagKey != null) context.put(etagKey, etag); if (contentTypeKey != null) context.put(contentTypeKey, contentType); if (log.isTraceEnabled()) log.trace("dispatching request, uri [" + uri + "] listener pattern [" + matchingPattern + "] method [" + method + "] etag [" + etag + "] contentType [" + contentType + "]"); if (httpServletRequest != null) context.put("restListenerServletRequest", httpServletRequest); if (httpServletResponse != null) context.put("restListenerServletResponse", httpServletResponse); if (servletContext != null) context.put("restListenerServletContext", servletContext); if (secLogEnabled && writeToSecLog) { secLog.info(HttpUtils.getExtendedCommandIssuedBy(httpServletRequest)); } String result = listener.processRequest(null, request, context); if (result == null && !context.containsKey("exitcode")) { log.warn("result is null!"); } return result; } finally { if (listener instanceof RestListener) { Thread.currentThread().setName(ctName); } } }
From source file:org.apache.hadoop.yarn.server.resourcemanager.webapp.TestRMWebServices.java
@Test public void testDumpingSchedulerLogs() throws Exception { ResourceManager mockRM = mock(ResourceManager.class); Configuration conf = new YarnConfiguration(); HttpServletRequest mockHsr = mock(HttpServletRequest.class); ApplicationACLsManager aclsManager = new ApplicationACLsManager(conf); when(mockRM.getApplicationACLsManager()).thenReturn(aclsManager); RMWebServices webSvc = new RMWebServices(mockRM, conf, mock(HttpServletResponse.class)); // nothing should happen webSvc.dumpSchedulerLogs("1", mockHsr); Thread.sleep(1000);/*ww w.j a v a 2 s .c o m*/ checkSchedulerLogFileAndCleanup(); conf.setBoolean(YarnConfiguration.YARN_ACL_ENABLE, true); conf.setStrings(YarnConfiguration.YARN_ADMIN_ACL, "admin"); aclsManager = new ApplicationACLsManager(conf); when(mockRM.getApplicationACLsManager()).thenReturn(aclsManager); webSvc = new RMWebServices(mockRM, conf, mock(HttpServletResponse.class)); boolean exceptionThrown = false; try { webSvc.dumpSchedulerLogs("1", mockHsr); fail("Dumping logs should fail"); } catch (ForbiddenException ae) { exceptionThrown = true; } assertTrue("ForbiddenException expected", exceptionThrown); exceptionThrown = false; when(mockHsr.getUserPrincipal()).thenReturn(new Principal() { @Override public String getName() { return "testuser"; } }); try { webSvc.dumpSchedulerLogs("1", mockHsr); fail("Dumping logs should fail"); } catch (ForbiddenException ae) { exceptionThrown = true; } assertTrue("ForbiddenException expected", exceptionThrown); when(mockHsr.getUserPrincipal()).thenReturn(new Principal() { @Override public String getName() { return "admin"; } }); webSvc.dumpSchedulerLogs("1", mockHsr); Thread.sleep(1000); checkSchedulerLogFileAndCleanup(); }