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.cloudbees.tomcat.valves.PrivateAppValveIntegratedTest.java
@Test public void unauthenticated_request_is_redirected_to_login_page() throws Exception { System.out.println("unauthenticated_request_is_redirected_to_login_page"); privateAppValve.setAuthenticationEntryPoint(PrivateAppValve.AuthenticationEntryPoint.BASIC_AUTH); HttpResponse response = httpClient.execute(httpHost, new HttpGet("/")); assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpServletResponse.SC_UNAUTHORIZED)); assertThat(response.containsHeader("WWW-Authenticate"), is(true)); dumpHttpResponse(response);/*from w w w. j a v a 2 s. c o m*/ EntityUtils.consumeQuietly(response.getEntity()); }
From source file:org.openmrs.module.clinicalsummary.web.controller.service.ResponseController.java
@RequestMapping(method = RequestMethod.POST) public void processResponse(@RequestParam(required = false, value = USERNAME) String username, @RequestParam(required = false, value = PASSWORD) String password, HttpServletRequest request, HttpServletResponse response) throws IOException { log.info("Processing responses from the android devices ..."); try {//ww w . j av a 2s . co m if (!Context.isAuthenticated()) Context.authenticate(username, password); UtilService utilService = Context.getService(UtilService.class); // TODO: wanna puke with this code!!!!! super hacky!!!!!!! Map parameterMap = request.getParameterMap(); for (Object parameterName : parameterMap.keySet()) { // skip the username and password request parameter if (!StringUtils.equalsIgnoreCase(USERNAME, String.valueOf(parameterName)) && !StringUtils.equalsIgnoreCase(PASSWORD, String.valueOf(parameterName))) { String id = String.valueOf(parameterName); String[] parameterValues = (String[]) parameterMap.get(id); log.info("ID: " + id); for (String parameterValue : parameterValues) log.info("Parameter Values: " + String.valueOf(parameterValue)); Patient patient = Context.getPatientService().getPatient(NumberUtils.toInt(id)); if (patient != null) processResponse(utilService, parameterValues, patient); else processDeviceLogs(utilService, id, parameterValues); } } response.setStatus(HttpServletResponse.SC_OK); } catch (ContextAuthenticationException e) { log.error("Authentication failure!", e); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } catch (Exception e) { log.error("Unspecified exception happened when processing the request!", e); response.sendError(HttpServletResponse.SC_BAD_REQUEST); } }
From source file:com.mirth.connect.server.servlets.UserServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // MIRTH-1745 response.setCharacterEncoding("UTF-8"); UserController userController = ControllerFactory.getFactory().createUserController(); EventController eventController = ControllerFactory.getFactory().createEventController(); PrintWriter out = response.getWriter(); Operation operation = Operations.getOperation(request.getParameter("op")); ObjectXMLSerializer serializer = new ObjectXMLSerializer(); if (operation.equals(Operations.USER_LOGIN)) { String username = request.getParameter("username"); String password = request.getParameter("password"); String version = request.getParameter("version"); response.setContentType(TEXT_PLAIN); serializer.toXML(login(request, response, userController, eventController, username, password, version), out);//from ww w . j a v a2s. c o m } else if (!isUserLoggedIn(request)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); } else { try { Map<String, Object> parameterMap = new HashMap<String, Object>(); if (operation.equals(Operations.USER_LOGOUT)) { // Audit the logout request but don't block it isUserAuthorized(request, null); logout(request, userController, eventController); } else if (operation.equals(Operations.USER_GET)) { /* * If the requesting user does not have permission, only * return themselves. */ response.setContentType(APPLICATION_XML); User user = (User) serializer.fromXML(request.getParameter("user")); parameterMap.put("user", user); if (!isUserAuthorized(request, parameterMap)) { user = new User(); user.setId(getCurrentUserId(request)); } serializer.toXML(userController.getUser(user), out); } else if (operation.equals(Operations.USER_UPDATE)) { User user = (User) serializer.fromXML(request.getParameter("user")); parameterMap.put("user", user); if (isUserAuthorized(request, parameterMap) || isCurrentUser(request, user)) { userController.updateUser(user); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.USER_CHECK_OR_UPDATE_PASSWORD)) { User user = (User) serializer.fromXML(request.getParameter("user")); parameterMap.put("user", user); if (isUserAuthorized(request, parameterMap) || isCurrentUser(request, user)) { String plainPassword = request.getParameter("plainPassword"); serializer.toXML(userController.checkOrUpdateUserPassword(user.getId(), plainPassword), out); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.USER_REMOVE)) { User user = (User) serializer.fromXML(request.getParameter("user")); parameterMap.put("user", user); if (isUserAuthorized(request, parameterMap)) { // Try to remove the user and then invalidate the // session if it succeeded userController.removeUser(user, (Integer) request.getSession().getAttribute(SESSION_USER)); UserSessionCache.getInstance().invalidateAllSessionsForUser(user); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.USER_IS_USER_LOGGED_IN)) { User user = (User) serializer.fromXML(request.getParameter("user")); parameterMap.put("user", user); if (isUserAuthorized(request, parameterMap)) { response.setContentType(TEXT_PLAIN); out.print(userController.isUserLoggedIn(user)); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.USER_PREFERENCES_GET)) { User user = (User) serializer.fromXML(request.getParameter("user")); parameterMap.put("user", user); // Allow if the user is requesting his own preferences. // Check this first so a current user call is not audited. if (isCurrentUser(request, user) || isUserAuthorized(request, parameterMap)) { response.setContentType(TEXT_PLAIN); serializer.toXML(userController.getUserPreferences(user), out); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } else if (operation.equals(Operations.USER_PREFERENCES_SET)) { User user = (User) serializer.fromXML(request.getParameter("user")); parameterMap.put("user", user); // Allow if the user is setting his own preferences. Check // this first so a current user call is not audited. if (isCurrentUser(request, user) || isUserAuthorized(request, parameterMap)) { String name = request.getParameter("name"); String value = request.getParameter("value"); userController.setUserPreference(user, name, value); } 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:com.bosch.iot.things.tutorial.ui.ProxyServlet.java
@Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String auth = req.getHeader("Authorization"); if (auth == null) { resp.setHeader("WWW-Authenticate", "BASIC realm=\"Proxy for Bosch IoT Things\""); resp.sendError(HttpServletResponse.SC_UNAUTHORIZED); return;//from ww w . j a v a 2 s . com } try { long time = System.currentTimeMillis(); CloseableHttpClient c = getHttpClient(); String targetUrl = URL_PREFIX + req.getPathInfo() + (req.getQueryString() != null ? ("?" + req.getQueryString()) : ""); BasicHttpRequest targetReq = new BasicHttpRequest(req.getMethod(), targetUrl); String user = ""; if (auth.toUpperCase().startsWith("BASIC ")) { String userpassDecoded = new String(Base64.getDecoder().decode(auth.substring("BASIC ".length()))); user = userpassDecoded.substring(0, userpassDecoded.indexOf(':')); String pass = userpassDecoded.substring(userpassDecoded.indexOf(':') + 1); UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass); targetReq.addHeader(new BasicScheme().authenticate(creds, targetReq, null)); } targetReq.addHeader("x-cr-api-token", req.getHeader("x-cr-api-token")); CloseableHttpResponse targetResp = c.execute(targetHost, targetReq); System.out.println("Request: " + targetHost + targetUrl + ", user " + user + " -> " + (System.currentTimeMillis() - time) + " msec: " + targetResp.getStatusLine()); resp.setStatus(targetResp.getStatusLine().getStatusCode()); targetResp.getEntity().writeTo(resp.getOutputStream()); } catch (IOException | AuthenticationException ex) { throw new RuntimeException(ex); } }
From source file:com.ecyrd.jspwiki.dav.WikiDavServlet.java
@Override public void doCopy(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "JSPWiki is read-only."); }
From source file:info.raack.appliancelabeler.web.BaseController.java
@ExceptionHandler public ModelAndView handleUncaughtException(Exception ex, HttpServletRequest request, HttpServletResponse response) throws IOException { if (ex instanceof AccessDeniedException) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } else if (ex instanceof OAuthUnauthorizedException) { /*if(request.getSession() != null) { request.getSession().invalidate(); }/*from ww w .jav a 2s . c o m*/ SecurityContextHolder.getContext().setAuthentication(null);*/ try { response.sendRedirect("/t/logout.do"); logger.warn("Could not authorize oauth request", ex); } catch (IOException e1) { logger.error("Could not send redirect", e1); } return null; } else if (ex instanceof ClientAPIException) { if (ex.getCause() != null && ex.getCause() instanceof OAuthUnauthorizedException) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } response.getOutputStream().write(ex.getMessage().getBytes()); return null; } else { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); errorService.reportError("Error while processing user web page request", URGENCY.URGENT, ex); logger.error("An exception was caught while processing", ex); } return templateProvider.showPageInTemplate(1, "error/basic", new ModelMap()); }
From source file:info.magnolia.cms.security.SecurityFilter.java
/** * Authenticate on basic headers.// ww w. j a va 2 s . co m * @param request HttpServletRequest * @param response HttpServletResponst * @return <code>true</code> if the user is authenticated */ private boolean authenticate(HttpServletRequest request, HttpServletResponse response) { try { if (Path.getURI(request).startsWith(this.filterConfig.getInitParameter(UNSECURED_URI))) { return true; } if (!Authenticator.authenticate(request)) { // invalidate previous session HttpSession httpsession = request.getSession(false); if (httpsession != null) { httpsession.invalidate(); } response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); if (StringUtils.equalsIgnoreCase(this.filterConfig.getInitParameter(AUTH_TYPE), AUTH_TYPE_BASIC)) { response.setHeader("WWW-Authenticate", "BASIC realm=\"" + Server.getBasicRealm() + "\""); } else { request.getRequestDispatcher(this.filterConfig.getInitParameter(LOGIN_FORM)).include(request, response); } return false; } } catch (Exception e) { log.error(e.getMessage(), e); return false; } return true; }
From source file:com.jaspersoft.jasperserver.rest.RESTLoginAuthenticationFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; String username = EncryptionRequestUtils.getValue(request, AuthenticationProcessingFilter.SPRING_SECURITY_FORM_USERNAME_KEY); String password = EncryptionRequestUtils.getValue(request, AuthenticationProcessingFilter.SPRING_SECURITY_FORM_PASSWORD_KEY); if (!StringUtils.isEmpty(username)) { // decoding since | is not http safe username = URLDecoder.decode(username, CharEncoding.UTF_8); UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);// ww w. j a v a2 s . c o m authRequest.setDetails(new WebAuthenticationDetails(httpRequest)); Authentication authResult; try { authResult = authenticationManager.authenticate(authRequest); } catch (AuthenticationException e) { if (log.isDebugEnabled()) { log.debug("User " + username + " failed to authenticate: " + e.toString()); } if (log.isWarnEnabled()) { log.warn("User " + username + " failed to authenticate: " + e.toString() + " " + e, e.getRootCause()); } SecurityContextHolder.getContext().setAuthentication(null); // Send an error message in the form of OperationResult... httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); //OperationResult or = servicesUtils.createOperationResult(1, "Invalid username " + username); PrintWriter pw = httpResponse.getWriter(); pw.print("Unauthorized"); return; } if (log.isDebugEnabled()) { log.debug("User " + username + " authenticated: " + authResult); } SecurityContextHolder.getContext().setAuthentication(authResult); chain.doFilter(request, response); } else { if (log.isDebugEnabled()) { log.debug("Failed to authenticate: Bad request. Username and password must be specified."); } if (log.isWarnEnabled()) { log.warn("Failed to authenticate: Bad request. Username and password must be specified."); } httpResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); PrintWriter pw = httpResponse.getWriter(); pw.print("Bad request." + (StringUtils.isEmpty(username) ? " Parameter " + AuthenticationProcessingFilter.SPRING_SECURITY_FORM_USERNAME_KEY + " not found." : "") + (StringUtils.isEmpty(password) ? " Parameter " + AuthenticationProcessingFilter.SPRING_SECURITY_FORM_PASSWORD_KEY + " not found." : "")); } }
From source file:fr.gael.dhus.server.http.webapp.api.controller.UploadController.java
@PreAuthorize("hasRole('ROLE_UPLOAD')") @RequestMapping(value = "/upload", method = { RequestMethod.POST }) public void upload(Principal principal, HttpServletRequest req, HttpServletResponse res) throws IOException { // process only multipart requests if (ServletFileUpload.isMultipartContent(req)) { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request try {//from www.ja v a 2s. c o m ArrayList<String> collectionIds = new ArrayList<>(); FileItem product = null; List<FileItem> items = upload.parseRequest(req); for (FileItem item : items) { if (COLLECTIONSKEY.equals(item.getFieldName())) { if (item.getString() != null && !item.getString().isEmpty()) { for (String cid : item.getString().split(",")) { collectionIds.add(cid); } } } else if (PRODUCTKEY.equals(item.getFieldName())) { product = item; } } if (product == null) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Your request is missing a product file to upload."); return; } productUploadService.upload(product, collectionIds); res.setStatus(HttpServletResponse.SC_CREATED); res.getWriter().print("The file was created successfully."); res.flushBuffer(); } catch (FileUploadException e) { LOGGER.error("An error occurred while parsing request.", e); res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred while parsing request : " + e.getMessage()); } catch (UserNotExistingException e) { LOGGER.error("You need to be connected to upload a product.", e); res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "You need to be connected to upload a product."); } catch (UploadingException e) { LOGGER.error("An error occurred while uploading the product.", e); res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred while uploading the product : " + e.getMessage()); } catch (RootNotModifiableException e) { LOGGER.error("An error occurred while uploading the product.", e); res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred while uploading the product : " + e.getMessage()); } catch (ProductNotAddedException e) { LOGGER.error("Your product can not be read by the system.", e); res.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Your product can not be read by the system."); } } else { res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "Request contents type is not supported by the servlet."); } }
From source file:org.openmhealth.reference.filter.ExceptionFilter.java
/** * <p>/*from w ww. j a v a 2 s .co m*/ * If the request throws an exception, specifically a OmhException, * attempt to respond with that message from the exception. * </p> * * <p> * For example, HTTP responses have their status codes changed to * {@link HttpServletResponse#SC_BAD_REQUEST} and the body of the response * is the error message. * </p> */ @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { // Get a handler for the correct exception type. Throwable exception = null; // Always let the request continue but setup to catch exceptions. try { chain.doFilter(request, response); } // The servlet container may wrap the exception, in which case we // must first unwrap it, then delegate it. catch (NestedServletException e) { // Get the underlying cause. Throwable cause = e.getCause(); // If the underlying exception is one of ours, then store the // underlying exception. if (cause instanceof OmhException) { exception = cause; } // Otherwise, store this exception. else { exception = e; } } // Otherwise, store the exception, catch (Exception e) { exception = e; } // If an exception was thrown, attempt to handle it. if (exception != null) { // Save the exception in the request. request.setAttribute(ATTRIBUTE_KEY_EXCEPTION, exception); // Handle the exception. if (exception instanceof NoSuchSchemaException) { LOGGER.log(Level.INFO, "An unknown schema was requested.", exception); // Respond to the user. sendResponse(response, HttpServletResponse.SC_NOT_FOUND, exception.getMessage()); } else if (exception instanceof InvalidAuthenticationException) { LOGGER.log(Level.INFO, "A user's authentication information was invalid.", exception); // Respond to the user. sendResponse(response, HttpServletResponse.SC_UNAUTHORIZED, exception.getMessage()); } else if (exception instanceof InvalidAuthorizationException) { LOGGER.log(Level.INFO, "A user's authorization information was invalid.", exception); // Respond to the user. sendResponse(response, HttpServletResponse.SC_UNAUTHORIZED, exception.getMessage()); } else if (exception instanceof OmhException) { LOGGER.log(Level.INFO, "An invalid request was made.", exception); // Respond to the user. sendResponse(response, HttpServletResponse.SC_BAD_REQUEST, exception.getMessage()); } // If the exception was not one of ours, the server must have // crashed. else { LOGGER.log(Level.SEVERE, "The server threw an unexpected exception.", exception); // Respond to the user. sendResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null); } } }