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:it.attocchi.web.auth.AuthenticationFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { logger.debug("Filtro Autenticazione"); 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 . j a v a2s . c om String auth = null; String workstation = null; String domain = null; String username = null; try { if (requestPath != null && (requestPath.endsWith("index.xhtml") || requestPath.endsWith("login.xhtml"))) { logger.debug("Richiesta una pagina fra quelle speciali, esco dal filtro"); chain.doFilter(request, response); return; } else { user_agent = httpRequest.getHeader("user-agent"); if ((user_agent != null) && (user_agent.indexOf("MSIE") > -1)) { 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 " + org.apache.commons.codec.binary.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); } } } // if IE else { chain.doFilter(request, response); } String winUser = username; // domain + "\\" + username; } } catch (RuntimeException e) { logger.error("Errore nel Filtro Autenticazione"); logger.error(e); chain.doFilter(request, response); httpResponse.sendError(httpResponse.SC_UNAUTHORIZED); httpResponse.sendRedirect(httpRequest.getContextPath() + "/index.jsp"); } logger.debug("Fine Filtro Autenticazione"); }
From source file:com.mirth.connect.server.servlets.ChannelServlet.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 {//from w w w.j a v a2s.c o m try { ChannelController channelController = ControllerFactory.getFactory().createChannelController(); ObjectXMLSerializer serializer = new ObjectXMLSerializer(); PrintWriter out = response.getWriter(); Operation operation = Operations.getOperation(request.getParameter("op")); Map<String, Object> parameterMap = new HashMap<String, Object>(); ServerEventContext context = new ServerEventContext(); context.setUserId(getCurrentUserId(request)); if (operation.equals(Operations.CHANNEL_GET)) { response.setContentType(APPLICATION_XML); List<Channel> channels = null; Channel channel = (Channel) serializer.fromXML(request.getParameter("channel")); parameterMap.put("channel", channel); if (!isUserAuthorized(request, parameterMap)) { channels = new ArrayList<Channel>(); } else if (doesUserHaveChannelRestrictions(request)) { channels = redactChannels(request, channelController.getChannel(channel)); } else { channels = channelController.getChannel(channel); } serializer.toXML(channels, out); } else if (operation.equals(Operations.CHANNEL_UPDATE)) { Channel channel = (Channel) serializer.fromXML(request.getParameter("channel")); boolean override = Boolean.valueOf(request.getParameter("override")).booleanValue(); parameterMap.put("channel", channel); parameterMap.put("override", override); if (!isUserAuthorized(request, parameterMap)) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } else { response.setContentType(TEXT_PLAIN); // NOTE: This needs to be print rather than println to // avoid the newline out.print(channelController.updateChannel(channel, context, override)); } } else if (operation.equals(Operations.CHANNEL_REMOVE)) { Channel channel = (Channel) serializer.fromXML(request.getParameter("channel")); parameterMap.put("channel", channel); if (!isUserAuthorized(request, parameterMap)) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } else { channelController.removeChannel(channel, context); } } else if (operation.equals(Operations.CHANNEL_GET_SUMMARY)) { response.setContentType(APPLICATION_XML); List<ChannelSummary> channelSummaries = null; Map<String, Integer> cachedChannels = (Map<String, Integer>) serializer .fromXML(request.getParameter("cachedChannels")); parameterMap.put("cachedChannels", cachedChannels); if (!isUserAuthorized(request, parameterMap)) { channelSummaries = new ArrayList<ChannelSummary>(); } else if (doesUserHaveChannelRestrictions(request)) { channelSummaries = redactChannelSummaries(request, channelController.getChannelSummary(cachedChannels)); } else { channelSummaries = channelController.getChannelSummary(cachedChannels); } serializer.toXML(channelSummaries, out); } } catch (RuntimeIOException rio) { logger.debug(rio); } catch (Throwable t) { logger.error(ExceptionUtils.getStackTrace(t)); throw new ServletException(t); } } }
From source file:eu.freme.broker.security.ManagementEndpointAuthenticationFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = asHttp(request); HttpServletResponse httpResponse = asHttp(response); Optional<String> username = Optional.fromNullable(httpRequest.getHeader("X-Auth-Username")); Optional<String> password = Optional.fromNullable(httpRequest.getHeader("X-Auth-Password")); String resourcePath = new UrlPathHelper().getPathWithinApplication(httpRequest); try {/*from w w w.j a va2 s .c om*/ if (postToManagementEndpoints(resourcePath)) { logger.debug("Trying to authenticate user {} for management endpoint by X-Auth-Username method", username); processManagementEndpointUsernamePasswordAuthentication(username, password); } logger.debug("ManagementEndpointAuthenticationFilter is passing request down the filter chain"); chain.doFilter(request, response); } catch (AuthenticationException authenticationException) { SecurityContextHolder.clearContext(); httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, authenticationException.getMessage()); } }
From source file:org.openmrs.module.clinicalsummary.web.controller.service.PatientIndexController.java
/** * @param patientId/*from w w w . j a v a 2 s. c om*/ * @param response * @should return indexes for the patient * @should return empty list when no index found for the patient */ @RequestMapping(method = RequestMethod.GET) public void searchIndex(@RequestParam(required = false, value = "username") String username, @RequestParam(required = false, value = "password") String password, @RequestParam(required = true, value = "patientId") Integer patientId, HttpServletResponse response) throws IOException { try { if (!Context.isAuthenticated()) Context.authenticate(username, password); List<Index> indexes = Context.getService(IndexService.class) .getIndexes(Context.getPatientService().getPatient(patientId)); // serialize the the search result or seria XStream xStream = new XStream(); xStream.alias("results", List.class); xStream.alias("result", Index.class); xStream.alias("patient", Patient.class); xStream.alias("summary", Summary.class); xStream.registerConverter(new IndexConverter()); xStream.registerConverter(new SummaryConverter()); xStream.registerConverter(new PatientConverter()); xStream.registerConverter(new PatientIdentifierConverter()); xStream.registerConverter(new PersonNameConverter()); xStream.toXML(indexes, response.getOutputStream()); } catch (ContextAuthenticationException e) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } }
From source file:com.salesmanager.core.security.JAASCustomerSecurityFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; resp.setHeader("Cache-Control", "no-cache"); resp.setHeader("Pragma", "no-cache"); resp.setDateHeader("Expires", 0); String url = req.getRequestURI(); if (isEscapeUrlFromFilter(url) || url.endsWith(".css") || url.endsWith(".js")) { chain.doFilter(request, response); return;/*w w w. j av a 2 s . c om*/ } String authToken = request.getParameter(CUSTOMER_AUTH_TOKEN); if (StringUtils.isBlank(authToken)) { HttpSession session = req.getSession(); if (session == null) { resp.sendRedirect(getLogonPage(req)); } else { if (session.getAttribute(SecurityConstants.SM_CUSTOMER_USER) != null) { chain.doFilter(request, response); } else { resp.sendRedirect(getLogonPage(req)); } } } else { if (logonModule.isValidAuthToken(authToken)) { chain.doFilter(request, response); } else { ((HttpServletResponse) response).setStatus(HttpServletResponse.SC_UNAUTHORIZED); return; } } }
From source file:com.oneops.ecv.ws.StatusController.java
@ExceptionHandler(AuthenticationException.class) @ResponseBody//from ww w. j a v a 2 s . c o m public void handleAuthFailure(AuthenticationException e, HttpServletResponse response) throws IOException { ECV_LOGGER.error(e); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.getWriter().write(e.getMessage()); }
From source file:com.zimbra.cs.servlet.util.AuthUtil.java
public static AuthToken getAuthTokenFromHttpReq(HttpServletRequest req, HttpServletResponse resp, boolean isAdminReq, boolean doNotSendHttpError) throws IOException { AuthToken authToken = null;//from ww w. jav a 2 s. co m try { authToken = AuthProvider.getAuthToken(req, isAdminReq); if (authToken == null) { if (!doNotSendHttpError) resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "no authtoken cookie"); return null; } if (authToken.isExpired() || !authToken.isRegistered()) { if (!doNotSendHttpError) resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken expired"); return null; } return authToken; } catch (AuthTokenException e) { if (!doNotSendHttpError) resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "unable to parse authtoken"); return null; } }
From source file:org.callistasoftware.netcare.web.mobile.controller.BankIdController.java
@RequestMapping(value = "/complete", method = RequestMethod.GET, produces = "application/json") @ResponseBody/*from w w w .j av a 2s .c om*/ public UserDetails collect(final HttpServletResponse response) throws IOException { final Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null) { return (UserDetails) auth.getPrincipal(); } log.debug("We have no authentication.. Returning unathorized."); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return null; }
From source file:com.betfair.tornjak.monitor.overlay.AuthUtilsTest.java
@Test public void testNotAuthenticated() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); ServletContext context = mock(ServletContext.class); when(context.getAttribute("com.betfair.tornjak.monitor.overlay.RolePerms")) .thenReturn(new AuthBuilder().role("jmxadmin").allow(".*:.*:.*").getRolePerms()); when(request.getUserPrincipal()).thenReturn(null); Auth auth = AuthUtils.checkAuthorised(request, response, context); assertThat("User should not be authorised", auth, nullValue()); verify(response, times(1)).sendError(HttpServletResponse.SC_UNAUTHORIZED); verifyNoMoreInteractions(response);//from w w w . ja va 2s . c o m }
From source file:monasca.common.middleware.TokenAuth.java
/** * {@inheritDoc}//w w w . jav a2 s .c o m */ public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { // According to CORS spec OPTIONS method does not pass auth info if (((HttpServletRequest) req).getMethod().equals("OPTIONS")) { chain.doFilter(req, resp); return; } Object auth = null; int numberOfTries = 0; if (!appConfig.isInitialized()) { appConfig.initialize(filterConfig, req); } int retries = appConfig.getRetries(); long pauseTime = appConfig.getPauseTime(); // Extract credential String token = ((HttpServletRequest) req).getHeader(TOKEN); if (token == null) { if (!appConfig.isDelayAuthDecision()) { logger.debug(HttpServletResponse.SC_UNAUTHORIZED + " No token found."); ((HttpServletResponse) resp).sendError(HttpServletResponse.SC_UNAUTHORIZED, TOKEN_NOTFOUND); return; } else { logger.info("No token found...Skipping"); } } else { do { try { auth = FilterUtils.getCachedToken(token); } catch (ServiceUnavailableException e) { if (numberOfTries < retries) { FilterUtils.pause(pauseTime); logger.debug("Retrying connection after " + pauseTime + " seconds."); numberOfTries++; continue; } else { logger.debug("Exhausted retries.."); TokenExceptionHandler handler = TokenExceptionHandler .valueOf("ServiceUnavailableException"); handler.onException(e, resp, token); } return; } catch (ClientProtocolException e) { if (numberOfTries < retries) { FilterUtils.pause(pauseTime); logger.debug("Retrying connection after " + pauseTime + " seconds."); numberOfTries++; continue; } else { logger.debug("Exhausted retries.."); TokenExceptionHandler handler = TokenExceptionHandler.valueOf("ClientProtocolException"); handler.onException(e, resp, token); } return; } catch (UncheckedExecutionException e) { final TokenExceptionHandler handler; final Exception toHandle; if ((e.getCause() != null) && e.getCause() instanceof AdminAuthException) { toHandle = (AdminAuthException) e.getCause(); handler = TokenExceptionHandler.valueOf("AdminAuthException"); } else if ((e.getCause() != null) && e.getCause() instanceof AuthException) { toHandle = (AuthException) e.getCause(); handler = TokenExceptionHandler.valueOf("AuthException"); } else { toHandle = e; handler = TokenExceptionHandler.valueOf("UncheckedExecutionException"); } handler.onException(toHandle, resp, token); return; } } while (auth == null && numberOfTries <= retries); } req = FilterUtils.wrapRequest(req, auth); logger.debug("TokenAuth: Forwarding down stream to next filter/servlet"); // Forward downstream... chain.doFilter(req, resp); }