List of usage examples for javax.servlet.http HttpServletResponse SC_UNAUTHORIZED
int SC_UNAUTHORIZED
To view the source code for javax.servlet.http HttpServletResponse SC_UNAUTHORIZED.
Click Source Link
From source file:com.mirth.connect.server.servlets.ExtensionServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // MIRTH-1745 response.setCharacterEncoding("UTF-8"); if (!isUserLoggedIn(request)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); } else {/*w w w.ja va 2 s .c o m*/ try { ExtensionController extensionController = ControllerFactory.getFactory() .createExtensionController(); ObjectXMLSerializer serializer = new ObjectXMLSerializer(); PrintWriter out = response.getWriter(); FileItem multiPartFileItem = null; Operation operation = null; Map<String, Object> parameterMap = new HashMap<String, Object>(); if (ServletFileUpload.isMultipartContent(request)) { Map<String, String> multipartParameters = new HashMap<String, String>(); File installTempDir = new File(ExtensionController.getExtensionsPath(), "install_temp"); if (!installTempDir.exists()) { installTempDir.mkdir(); } // we need to load properties from the multipart data DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(installTempDir); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { multipartParameters.put(item.getFieldName(), item.getString()); } else { // only supports a single file multiPartFileItem = item; } } operation = Operations.getOperation(multipartParameters.get("op")); } else { operation = Operations.getOperation(request.getParameter("op")); } if (operation.equals(Operations.PLUGIN_PROPERTIES_GET)) { String pluginName = request.getParameter("name"); if (isUserAuthorizedForExtension(request, pluginName, operation.getName(), null)) { response.setContentType(APPLICATION_XML); serializer.toXML(extensionController.getPluginProperties(pluginName), out); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.PLUGIN_PROPERTIES_SET)) { String pluginName = request.getParameter("name"); if (isUserAuthorizedForExtension(request, pluginName, operation.getName(), null)) { Properties properties = (Properties) serializer.fromXML(request.getParameter("properties")); extensionController.setPluginProperties(pluginName, properties); extensionController.updatePluginProperties(pluginName, properties); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.PLUGIN_METADATA_GET)) { response.setContentType(APPLICATION_XML); serializer.toXML(extensionController.getPluginMetaData(), out); } else if (operation.equals(Operations.EXTENSION_SET_ENABLED)) { String pluginName = request.getParameter("name"); boolean enabled = BooleanUtils.toBoolean(request.getParameter("enabled")); parameterMap.put("extension", pluginName); parameterMap.put("enabled", enabled); if (isUserAuthorized(request, parameterMap)) { extensionController.setExtensionEnabled(pluginName, enabled); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.CONNECTOR_METADATA_GET)) { response.setContentType(APPLICATION_XML); serializer.toXML(extensionController.getConnectorMetaData(), out); } else if (operation.equals(Operations.EXTENSION_IS_ENABLED)) { String extensionName = request.getParameter("name"); response.setContentType(TEXT_PLAIN); out.print(extensionController.isExtensionEnabled(extensionName)); } else if (operation.equals(Operations.PLUGIN_SERVICE_INVOKE)) { String pluginName = request.getParameter("name"); String method = request.getParameter("method"); Object object = serializer.fromXML(request.getParameter("object")); String sessionId = request.getSession().getId(); if (isUserAuthorizedForExtension(request, pluginName, method, null)) { serializer.toXML( extensionController.invokePluginService(pluginName, method, object, sessionId), out); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.CONNECTOR_SERVICE_INVOKE)) { String name = request.getParameter("name"); String method = request.getParameter("method"); Object object = serializer.fromXML(request.getParameter("object")); String sessionId = request.getSession().getId(); response.setContentType(APPLICATION_XML); serializer.toXML(extensionController.invokeConnectorService(name, method, object, sessionId), out); } else if (operation.equals(Operations.EXTENSION_UNINSTALL)) { String packageName = request.getParameter("packageName"); parameterMap.put("packageName", packageName); if (isUserAuthorized(request, parameterMap)) { extensionController.prepareExtensionForUninstallation(packageName); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.EXTENSION_INSTALL)) { if (isUserAuthorized(request, null)) { /* * This is a multi-part method, so we need our * parameters from the new map */ extensionController.extractExtension(multiPartFileItem); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } } catch (RuntimeIOException rio) { logger.debug(rio); } catch (Throwable t) { logger.error(ExceptionUtils.getStackTrace(t)); throw new ServletException(t); } } }
From source file:eu.dasish.annotation.backend.rest.ResourceResource.java
/** * /* w w w . j a va 2 s . c o m*/ * @return the internal database id of the logged in principal if the authentication went well, * otherwise sends a corresponding error message. * @throws IOException if sending an error fails. */ public Number getPrincipalID() throws IOException { dbDispatcher.setResourcesPaths(this.getRelativeServiceURI()); String remotePrincipal = httpServletRequest.getRemoteUser(); if (remotePrincipal != null) { if (!remotePrincipal.equals(anonym)) { try { return dbDispatcher.getPrincipalInternalIDFromRemoteID(remotePrincipal); } catch (NotInDataBaseException e) { loggerServer.info(e.toString()); loggerServer.info("The record for the user with the id " + remotePrincipal + " will be generated now automatically."); try { try { Principal newPrincipal = Helpers.createPrincipalElement(remotePrincipal, remotePrincipal); return dbDispatcher.addPrincipal(newPrincipal, remotePrincipal); } catch (PrincipalExists e2) { loggerServer.info(e2.toString()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e2.toString()); return null; } } catch (NotInDataBaseException e1) { loggerServer.info(e1.toString()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e1.toString()); return null; } } } else { loggerServer.info("Shibboleth fall-back. Logged in as 'anonymous' with no rights."); httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, " Shibboleth fall-back. Logged in as 'anonymous' with no rights."); return null; } } else { loggerServer.info("Null principal"); httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, " Null principal"); return null; } }
From source file:com.formtek.dashlets.sitetaskmgr.SiteTaskInstancePut.java
@Override protected Map<String, Object> buildModel(WorkflowModelBuilder modelBuilder, WebScriptRequest req, Status status, Cache cache) {//from www. j ava 2s .c o m Map<String, String> params = req.getServiceMatch().getTemplateVars(); // getting task id from request parameters String wfId = getWorkflowId(req); logger.debug("Processing workflowId: " + wfId); String site = getSite(req); logger.debug("Workflow should be associated with site: " + site); logger.debug("Workflow type: " + workflowService.getWorkflowById(wfId).getDefinition().getName()); if (wfId == null || site == null) { throw new WebScriptException(HttpServletResponse.SC_NOT_FOUND, "Can't set task properties because workflow Id or site name are not defined correctly."); } JSONObject json = null; try { // read request json containing properties to write json = new JSONObject(new JSONTokener(req.getContent().getContent())); logger.debug(json.toString()); // get the workflow path from the incoming workflow Id // for site task manager workflows, there will be a single path WorkflowPath wfPath = SiteWFUtil.getWorkflowPath(wfId, workflowService); // If User is not authorized to change this workflow, exit if (!SiteWFUtil.canUserChangeWorkflow(wfPath, site, workflowService, nodeService, authenticationService, authorityService)) { throw new WebScriptException(HttpServletResponse.SC_UNAUTHORIZED, "User is not authorized to change workflows for this site: " + site); } // Retrieve the current task. For the site task workfklow, there should be a single current task WorkflowTask workflowTask = SiteWFUtil.getWorkflowTask(wfPath, workflowService); String taskId = workflowTask.getId(); logger.debug("Processing taskId: " + taskId); // update task properties workflowTask = workflowService.updateTask(taskId, parseTaskProperties(json, workflowTask), null, null); // task was not found -> return 404 if (workflowTask == null) { throw new WebScriptException(HttpServletResponse.SC_NOT_FOUND, "Failed to find workflow task with id: " + taskId); } // build the model for ftl Map<String, Object> model = new HashMap<String, Object>(); model.put("workflowTask", modelBuilder.buildDetailed(workflowTask)); return model; } catch (IOException iox) { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Could not read content from request.", iox); } catch (JSONException je) { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Could not parse JSON from request.", je); } }
From source file:com.wandisco.s3hdfs.auth.AWSAuthenticationHandler.java
/** * Verifies the AWS authentication header * <p/>/*from ww w . ja v a 2s . com*/ * * @param request the HTTP client request. * @param response the HTTP client response. * @return an authentication token if the AWS authentication header is correct * <code>null</code> if it is in progress (in this case the handler handles the response to the client). * @throws IOException thrown if an IO error occurred. * @throws AuthenticationException thrown if the AWS authentication header is incorrect */ @Override public AuthenticationToken authenticate(HttpServletRequest request, final HttpServletResponse response) throws IOException, AuthenticationException { String authorization = request.getHeader(AUTHORIZATION); LOG.debug("authenticate - authorization = " + authorization); if (authorization == null || !authorization.startsWith("AWS")) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return null; } else { if (LOG.isDebugEnabled()) LOG.debug("authenticate - returning jagane"); String[] splitAuth = authorization.split("\\s"); if (splitAuth.length < 2) { LOG.warn("authenticate - auth string does not have enough info. " + authorization); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return null; } String[] splitKey = splitAuth[1].split(":"); if (splitKey.length < 2) { LOG.warn("authenticate - auth string does not have key/signature. " + authorization); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return null; } String nameAndSecretAccessKey[] = getNameAndSecretAccessKey(splitKey[0]); if (nameAndSecretAccessKey == null || nameAndSecretAccessKey[1].length() == 0) { LOG.warn("authenticate - cannot find secretAccessKey for accessKeyId " + splitKey[0]); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return null; } String hostHeader = request.getHeader("Host"); try { verifySignature(request.getMethod(), nameAndSecretAccessKey[1], splitKey[1], "HmacSHA1", hostHeader, request.getRequestURI(), getCanonicalizedQueryString(request)); } catch (Exception ex) { LOG.warn("verifySignature threw " + ex); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return null; } return new AuthenticationToken(nameAndSecretAccessKey[0], nameAndSecretAccessKey[0], "AWS"); } }
From source file:eu.trentorise.smartcampus.communicatorservice.controller.NotificationController.java
@RequestMapping(method = RequestMethod.GET, value = "/app/{capp:.*}/notification") public @ResponseBody Notifications getNotificationsByApp(HttpServletRequest request, HttpServletResponse response, HttpSession session, @RequestParam("since") Long since, @RequestParam("position") Integer position, @RequestParam("count") Integer count, @PathVariable("capp") String capp) throws DataException, IOException, SmartCampusException { if (capp == null) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return null; }// w w w . j a va 2 s .c o m String userId = getUserId(); if (userId == null) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } Notifications result = new Notifications(); result.setNotifications(notificationManager.get(userId, capp, since, position, count, null)); return result; }
From source file:org.artifactory.rest.common.exception.ArtifactoryRestExceptionMapper.java
private Response createUnauthorizedResponseWithChallenge() { Response.ResponseBuilder responseBuilder = Response.status(HttpStatus.SC_UNAUTHORIZED) .type(MediaType.APPLICATION_JSON_TYPE) .entity(new ErrorResponse(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized")); // ui related request do not require chanllange message if (!UiRequestUtils.isUiRestRequest(servletRequest)) { responseBuilder.header("WWW-Authenticate", "Basic realm=\"" + authenticationEntryPoint.getRealmName() + "\""); }//from w w w.jav a 2 s . co m return responseBuilder.build(); }
From source file:org.openxdata.server.servlet.FormDownloadServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { OutputStream os = response.getOutputStream(); try {/*from www . j av a 2 s.c om*/ String action = request.getParameter(OpenXDataConstants.REQUEST_PARAMETER_ACTION); if (action == null) formsServer.processConnection(request.getInputStream(), os); else { User user = authenticationService.authenticate( request.getParameter(OpenXDataConstants.REQUEST_PARAM_USERNAME), request.getParameter(OpenXDataConstants.REQUEST_PARAM_PASSWORD)); if (user == null) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); XformSerializer formSerializer = serializationService.getFormSerializer( request.getParameter(OpenXDataConstants.REQUEST_PARAM_FORM_SERIALIZER)); formSerializer.serializeAccessDenied(os); } else { if (OpenXDataConstants.REQUEST_ACTION_UPLOAD_DATA.equalsIgnoreCase(action)) { uploadData(request, response); String serializerKey = request .getParameter(OpenXDataConstants.REQUEST_PARAM_FORM_SERIALIZER); XformSerializer formSerializer = serializationService.getFormSerializer(serializerKey); formSerializer.serializeSuccess(os); } else if (OpenXDataConstants.REQUEST_ACTION_DOWNLOAD_FORMS.equalsIgnoreCase(action)) downloadForms(request, response); else if (OpenXDataConstants.ACTION_DOWNLOAD_STUDIES.equalsIgnoreCase(action)) downloadStudies(request, response); else if (OpenXDataConstants.REQUEST_ACTION_DOWNLOAD_USERS.equalsIgnoreCase(action)) downloadUsers(request, response); } } } catch (Exception ex) { try { String serializerKey = request.getParameter(OpenXDataConstants.REQUEST_PARAM_FORM_SERIALIZER); XformSerializer formSerializer = serializationService.getFormSerializer(serializerKey); formSerializer.serializeFailure(os, ex); } catch (Exception e) { log.error(e.getLocalizedMessage(), e); } } }
From source file:it.attocchi.web.filters.NtmlFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { logger.debug("Filtro Ntlm"); HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; HttpSession session = httpRequest.getSession(); String requestPath = httpRequest.getServletPath(); logger.debug("requestPath " + requestPath); String user_agent = null;//from w w w . ja v a 2 s.c om String auth = null; String workstation = null; String domain = null; String username = null; try { /* * Operatore loggato? SI: prosegue con il flusso normalmente; NO: * tentativo di accesso con utente Windows e poi, se fallisce, * redirect alla pagina di autenticazione; */ if ((requestPath != null && requestPath.endsWith("index.jspx")) || (requestPath != null && requestPath.endsWith("status.jspx")) || requestPath != null && requestPath.endsWith("logout.jspx") || requestPath != null && requestPath.endsWith("authenticate.jspx")) { logger.debug("Richiesta una pagina fra quelle speciali, esco dal filtro"); // chain.doFilter(request, response); // return; } else { /* COMMENTATO per problemi POST JSF */ // // <editor-fold defaultstate="collapsed" // desc="DETERMINAZIONE UTENTE WINDOWS"> /* * La tecnica utilizzata (settaggio header) per la * determinazione dell'utente Windows funzionante * esclusivamente con browser Microsoft Internet Explorer. Se * altro browser salta questo step */ user_agent = httpRequest.getHeader("user-agent"); // if ((user_agent != null) && (user_agent.indexOf("MSIE") > // -1)) { if ((user_agent != null)) { logger.debug("USER-AGENT: " + user_agent); auth = httpRequest.getHeader("Authorization"); if (auth == null) { logger.debug("STEP1: SC_UNAUTHORIZED"); httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); httpResponse.setHeader("WWW-Authenticate", "NTLM"); httpResponse.flushBuffer(); return; } if (auth.startsWith("NTLM ")) { logger.debug("STEP2: NTLM"); byte[] msg = org.apache.commons.codec.binary.Base64.decodeBase64(auth.substring(5)); // byte[] msg = new // sun.misc.BASE64Decoder().decodeBuffer(auth.substring(5)); int off = 0, length, offset; if (msg[8] == 1) { logger.debug("STEP2a: NTLM"); byte z = 0; byte[] msg1 = { (byte) 'N', (byte) 'T', (byte) 'L', (byte) 'M', (byte) 'S', (byte) 'S', (byte) 'P', z, (byte) 2, z, z, z, z, z, z, z, (byte) 40, z, z, z, (byte) 1, (byte) 130, z, z, z, (byte) 2, (byte) 2, (byte) 2, z, z, z, z, z, z, z, z, z, z, z, z }; // httpResponse.setHeader("WWW-Authenticate", // "NTLM " + new // sun.misc.BASE64Encoder().encodeBuffer(msg1)); httpResponse.setHeader("WWW-Authenticate", "NTLM " + Base64.encodeBase64String(msg1)); httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } else if (msg[8] == 3) { logger.debug("STEP2b: read data"); off = 30; length = msg[off + 17] * 256 + msg[off + 16]; offset = msg[off + 19] * 256 + msg[off + 18]; workstation = new String(msg, offset, length); length = msg[off + 1] * 256 + msg[off]; offset = msg[off + 3] * 256 + msg[off + 2]; domain = new String(msg, offset, length); length = msg[off + 9] * 256 + msg[off + 8]; offset = msg[off + 11] * 256 + msg[off + 10]; username = new String(msg, offset, length); char a = 0; char b = 32; // logger.debug("Username:" + // username.trim().replace(a, b).replaceAll("", // "")); username = username.trim().replace(a, b).replaceAll(" ", ""); workstation = workstation.trim().replace(a, b).replaceAll(" ", ""); domain = domain.trim().replace(a, b).replaceAll(" ", ""); logger.debug("Username: " + username); logger.debug("RemoteHost: " + workstation); logger.debug("Domain: " + domain); chain.doFilter(request, response); } } } // if IE // </editor-fold> /* * Mirco 30/09/10: Autentico solo con il nome utente senza il * prefisso DOMINIO Questo mi e' utile per i nomi importati da * LDAP che hanno specificato solo il nome dell'account */ String winUser = username; // domain + "\\" + username; try { if (winUser != null) { // utenteDaLoggare = // UtentiDAO.getUtenteByWindowsLogin(winUser); } } catch (Exception e) { } } } catch (RuntimeException e) { logger.error("Errore nel Filtro Autenticazione"); logger.error(e); chain.doFilter(request, response); } finally { } logger.debug("Fine Filtro Ntlm"); }
From source file:org.apache.archiva.redback.integration.filter.authentication.basic.HttpBasicAuthentication.java
/** * Return a HTTP 403 - Access Denied response. * * @param request the request to use.//from ww w . j a va2 s. c o m * @param response the response to use. * @param realmName the realm name to state. * @param exception the exception to base the message off of. * @throws IOException if there was a problem with the {@link HttpServletResponse#sendError(int,String)} call. */ public void challenge(HttpServletRequest request, HttpServletResponse response, String realmName, AuthenticationException exception) throws IOException { response.addHeader("WWW-Authenticate", "Basic realm=\"" + realmName + "\""); String message = "You must provide a username and password to access this resource."; if ((exception != null) && StringUtils.isNotEmpty(exception.getMessage())) { message = exception.getMessage(); } response.sendError(HttpServletResponse.SC_UNAUTHORIZED, message); }
From source file:com.devicehive.auth.rest.HttpAuthenticationFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; Optional<String> authHeader = Optional.ofNullable(httpRequest.getHeader(HttpHeaders.AUTHORIZATION)); String resourcePath = new UrlPathHelper().getPathWithinApplication(httpRequest); logger.debug("Security intercepted request to {}", resourcePath); try {// w ww . ja v a 2 s . c o m if (authHeader.isPresent()) { String header = authHeader.get(); if (header.startsWith(Constants.BASIC_AUTH_SCHEME)) { processBasicAuth(header); } else if (header.startsWith(Constants.TOKEN_SCHEME)) { processJwtAuth(authHeader.get().substring(6).trim()); } } else { processAnonymousAuth(); } Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null && authentication instanceof AbstractAuthenticationToken) { MDC.put("usrinf", authentication.getName()); HiveAuthentication.HiveAuthDetails details = createUserDetails(httpRequest); ((AbstractAuthenticationToken) authentication).setDetails(details); } chain.doFilter(request, response); } catch (InternalAuthenticationServiceException e) { SecurityContextHolder.clearContext(); logger.error("Internal authentication service exception", e); httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (AuthenticationException e) { SecurityContextHolder.clearContext(); httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage()); } finally { MDC.remove("usrinf"); } }