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.codenvy.ide.git.VFSPermissionsFilterTest.java
@Test public void shouldRespondUnauthorizedIfProjectHasPermissionsToSpecificUserAndUserIsEmpty() throws IOException, ServletException, UnauthorizedException, ForbiddenException, ConflictException, NotFoundException, ServerException { //given/* w w w. j a va 2 s. c o m*/ when(httpJsonHelper.requestString(anyString(), eq("GET"), any())) .thenThrow(new UnauthorizedException("NO")); //when filter.doFilter(request, response, filterChain); //then verify(response).sendError(eq(HttpServletResponse.SC_UNAUTHORIZED)); }
From source file:com.devicehive.application.security.WebSecurityConfig.java
@Bean public AuthenticationEntryPoint unauthorizedEntryPoint() { return (request, response, authException) -> { Optional<String> authHeader = Optional.ofNullable(request.getHeader(HttpHeaders.AUTHORIZATION)); if (authHeader.isPresent() && authHeader.get().startsWith(Constants.TOKEN_SCHEME)) { response.addHeader(HttpHeaders.WWW_AUTHENTICATE, Messages.OAUTH_REALM); } else {/* ww w . j ava2 s .c o m*/ response.addHeader(HttpHeaders.WWW_AUTHENTICATE, Messages.BASIC_REALM); } response.setContentType(MediaType.APPLICATION_JSON_VALUE); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.getOutputStream().println(gson .toJson(new ErrorResponse(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()))); }; }
From source file:eu.freme.broker.security.AuthenticationFilter.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")); Optional<String> token = Optional.fromNullable(httpRequest.getHeader("X-Auth-Token")); if (httpRequest.getParameter("token") != null) { token = Optional.fromNullable(httpRequest.getParameter("token")); }// www.j ava2s . co m String resourcePath = new UrlPathHelper().getPathWithinApplication(httpRequest); try { if (postToAuthenticate(httpRequest, resourcePath)) { logger.debug("Trying to authenticate user {} by X-Auth-Username method", username); processUsernamePasswordAuthentication(httpResponse, username, password); return; } if (token.isPresent()) { logger.debug("Trying to authenticate user by X-Auth-Token method. Token: {}", token); processTokenAuthentication(token); } logger.debug("AuthenticationFilter is passing request down the filter chain"); addSessionContextToLogging(); chain.doFilter(request, response); } catch (InternalAuthenticationServiceException internalAuthenticationServiceException) { SecurityContextHolder.clearContext(); logger.error("Internal authentication service exception", internalAuthenticationServiceException); httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (AuthenticationException authenticationException) { SecurityContextHolder.clearContext(); httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, authenticationException.getMessage()); } finally { MDC.remove(TOKEN_SESSION_KEY); MDC.remove(USER_SESSION_KEY); } }
From source file:com.haulmont.restapi.idp.IdpAuthLifecycleManager.java
@Order(Events.HIGHEST_PLATFORM_PRECEDENCE + 100) @EventListener// www . j a v a2 s.c o m public void handleBeforeRestInvocationEvent(BeforeRestInvocationEvent event) { if (idpConfig.getIdpEnabled()) { if (idpConfig.getIdpPingSessionOnRequest() && event.getAuthentication() instanceof OAuth2Authentication) { IdpSessionStatus status = pingIdpSession(event.getAuthentication()); if (status == IdpSessionStatus.EXPIRED) { Object details = event.getAuthentication().getDetails(); String accessToken = ((OAuth2AuthenticationDetails) details).getTokenValue(); oAuthTokenRevoker.revokeAccessToken(accessToken); log.info("IDP session is expired. REST token {} revoked", accessToken); event.preventInvocation(); String idpLoginUrl = getIdpLoginUrl(idpConfig.getIdpDefaultRedirectUrl()); Gson gson = new Gson(); String body = gson.toJson(new IdpSessionExpiredResponse("idp_session_expired", idpLoginUrl)); HttpServletResponse response = (HttpServletResponse) event.getResponse(); try { response.setHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8"); response.getWriter().write(body); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } catch (IOException e) { throw new RuntimeException("Unable to send status to client", e); } } } } }
From source file:eu.freme.common.security.AuthenticationFilter.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")); Optional<String> token = Optional.fromNullable(httpRequest.getHeader("X-Auth-Token")); if (httpRequest.getParameter("token") != null) { token = Optional.fromNullable(httpRequest.getParameter("token")); }/* w w w . j av a2 s. co m*/ String resourcePath = new UrlPathHelper().getPathWithinApplication(httpRequest); try { // if (postToAuthenticate(httpRequest, resourcePath)) { // logger.debug("Trying to authenticate user {} by X-Auth-Username method", username); // processUsernamePasswordAuthentication(httpResponse, username, password); // return; // } if (token.isPresent()) { logger.debug("Trying to authenticate user by X-Auth-Token method. Token: {}", token); processTokenAuthentication(token); } logger.debug("AuthenticationFilter is passing request down the filter chain"); addSessionContextToLogging(); chain.doFilter(request, response); } catch (InternalAuthenticationServiceException internalAuthenticationServiceException) { SecurityContextHolder.clearContext(); logger.error("Internal authentication service exception", internalAuthenticationServiceException); httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (AuthenticationException authenticationException) { SecurityContextHolder.clearContext(); httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, authenticationException.getMessage()); } finally { MDC.remove(TOKEN_SESSION_KEY); MDC.remove(USER_SESSION_KEY); } }
From source file:com.ecyrd.jspwiki.dav.WikiDavServlet.java
@Override public void doMove(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "JSPWiki is read-only."); }
From source file:org.jboss.as.test.clustering.cluster.web.authentication.BasicAuthenticationWebFailoverTestCase.java
@Test public void test(@ArquillianResource(SecureServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1, @ArquillianResource(SecureServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2) throws IOException, URISyntaxException { CredentialsProvider provider = new BasicCredentialsProvider(); HttpClient client = HttpClients.custom().setDefaultCredentialsProvider(provider).build(); URI uri1 = SecureServlet.createURI(baseURL1); URI uri2 = SecureServlet.createURI(baseURL2); try {/*from w w w. j a v a2 s. c om*/ // Valid login, invalid role setCredentials(provider, "forbidden", "password", baseURL1, baseURL2); HttpResponse response = client.execute(new HttpGet(uri1)); try { Assert.assertEquals(HttpServletResponse.SC_FORBIDDEN, response.getStatusLine().getStatusCode()); } finally { HttpClientUtils.closeQuietly(response); } // Invalid login, valid role setCredentials(provider, "allowed", "bad", baseURL1, baseURL2); response = client.execute(new HttpGet(uri1)); try { Assert.assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); } finally { HttpClientUtils.closeQuietly(response); } // Valid login, valid role setCredentials(provider, "allowed", "password", baseURL1, baseURL2); String sessionId = null; response = client.execute(new HttpGet(uri1)); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertNotNull(response.getFirstHeader(SecureServlet.SESSION_ID_HEADER)); sessionId = response.getFirstHeader(SecureServlet.SESSION_ID_HEADER).getValue(); } finally { HttpClientUtils.closeQuietly(response); } undeploy(DEPLOYMENT_1); response = client.execute(new HttpGet(uri2)); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals(sessionId, response.getFirstHeader(SecureServlet.SESSION_ID_HEADER).getValue()); } finally { HttpClientUtils.closeQuietly(response); } deploy(DEPLOYMENT_1); response = client.execute(new HttpGet(uri1)); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals(sessionId, response.getFirstHeader(SecureServlet.SESSION_ID_HEADER).getValue()); } finally { HttpClientUtils.closeQuietly(response); } } finally { HttpClientUtils.closeQuietly(client); } }
From source file:fr.gael.dhus.api.UploadController.java
@SuppressWarnings("unchecked") @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)) { User user = (User) ((UsernamePasswordAuthenticationToken) principal).getPrincipal(); // 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 w ww .j av a 2 s . c o m*/ ArrayList<Long> 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(new Long(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(user.getId(), 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:airport.web.controller.ServicesController.java
@RequestMapping(value = "/service/dispatcher/typeMachine", produces = "application/json") public FlyingMachineType serviceDispatcherTypeMachine(@RequestParam(name = "typeMachine") String typeMachine, HttpServletRequest request, HttpServletResponse response) { HttpSession httpSession = request.getSession(); User user = (User) httpSession.getAttribute("user"); if (!serviceUsers.checkUserOnline(user)) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); if (LOG.isInfoEnabled()) { LOG.info("the user isn't authorized. Session id : " + httpSession.getId() + ". URL : /service/dispatcher/typeMachine"); }//from ww w. j a v a2s . c o m return null; } if (LOG.isInfoEnabled()) { LOG.info("user get dispatcher type machine. Session id : " + httpSession.getId() + ". User : " + user + ". URL : /service/dispatcher/typeMachine"); } return serviceFlyingType.getFlyingMachineType(typeMachine); }