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.cloudera.alfredo.server.TestKerberosAuthenticationHandler.java
public void testRequestWithInvalidAuthorization() throws Exception { HttpServletRequest request = Mockito.mock(HttpServletRequest.class); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Mockito.when(request.getHeader(KerberosAuthenticator.AUTHORIZATION)).thenReturn("invalid"); assertNull(handler.authenticate(request, response)); Mockito.verify(response).setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE); Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED); }
From source file:com.versatus.jwebshield.filter.SessionCheckFilter.java
/** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) *///ww w . j a va2 s. com @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpReq = (HttpServletRequest) request; HttpServletResponse httpRes = (HttpServletResponse) response; String reqInfo = "J-WebShield Alert: Session check failed! request URL=" + httpReq.getRequestURL().toString() + "| from IP address=" + httpReq.getRemoteAddr(); logger.debug("doFilter: RequestURL=" + httpReq.getRequestURL().toString()); UrlExclusionList exclList = (UrlExclusionList) request.getServletContext() .getAttribute(SecurityConstant.SESSION_CHECK_URL_EXCL_LIST_ATTR_NAME); try { if (!exclList.isEmpty() && exclList.isMatch(httpReq.getRequestURI())) { logger.info("doFilter: request (" + httpReq.getRequestURL().toString() + " matches exclusion pattern, skipping session check"); chain.doFilter(request, response); return; } } catch (Exception e) { logger.error("doFilter", e); } HttpSession session = httpReq.getSession(false); logger.debug("doFilter: session=" + session); logger.debug("doFilter: session attr. " + attributeToCheck + "=" + (session != null ? session.getAttribute(attributeToCheck) : "")); if (session == null || session.getAttribute(attributeToCheck) == null) { if (send401) { // TODO this is not working for regular requests, only for WS // calls httpRes.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } else { logger.info(reqInfo + " redirecting to " + redirectPage); RequestDispatcher rd = httpReq.getRequestDispatcher(redirectPage); if (rd != null) { rd.forward(request, response); } return; } } logger.info("doFilter: session check complete"); // pass the request along the filter chain chain.doFilter(request, response); }
From source file:com.linuxbox.enkive.web.MessageAttachmentDetailServlet.java
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { final String messageId = req.getParameter(PARAM_MSG_ID); final MessageRetrieverService retriever = getMessageRetrieverService(); try {//from w w w . ja va 2 s .co m final Message message = retriever.retrieve(messageId); JSONArray attachments = new JSONArray(); for (AttachmentSummary attachment : message.getContentHeader().getAttachmentSummaries()) { JSONObject attachmentObject = new JSONObject(); String filename = attachment.getFileName(); if (filename == null || filename.isEmpty()) { final String positionString = attachment.getPositionString(); // TODO: revisit this logic; best to assume first attachment // is body? if (positionString.isEmpty() || positionString.equals("1")) { filename = "Message-Body"; } else { filename = "attachment-" + positionString; } } String mimeType = attachment.getMimeType(); if (mimeType == null) { mimeType = ""; } attachmentObject.put(KEY_UUID, attachment.getUuid()); attachmentObject.put(KEY_FILE_NAME, filename); attachmentObject.put(KEY_MIME_TYPE, mimeType); attachments.put(attachmentObject); } JSONObject jObject = new JSONObject(); jObject.put(WebConstants.DATA_TAG, attachments); String jsonString = jObject.toString(); resp.getWriter().write(jsonString); } catch (CannotRetrieveException e) { respondError(HttpServletResponse.SC_UNAUTHORIZED, null, resp); LOGGER.error("Could not retrieve attachment", e); } catch (JSONException e) { respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, resp); LOGGER.error("Could not retrieve attachment", e); } }
From source file:eu.trentorise.smartcampus.permissionprovider.auth.fb.FBController.java
/** * This rest web service is the one that google called after login (callback * url). First it retrieve code and token that google sends back. It checks * if code and token are not null, then if token is the same that was saved * in session. If it is not response status is UNAUTHORIZED, otherwise it * retrieves user data. If user is not already saved in db, then user is * added in db, iff email is not already used, otherwise it sends an * UNAUTHORIZED status and redirect user to home page without authenticating * him/her. If it is all ok, then it authenticates user in spring security * and create cookie user. Then redirects authenticated user to home page * where user can access protected resources. * //from ww w . j a va 2 s . c o m * @param request * : instance of {@link HttpServletRequest} * @param response * : instance of {@link HttpServletResponse} * @return redirect to home page */ @RequestMapping(value = "/callback", method = RequestMethod.GET) public String confirmStateToken(HttpServletRequest request, HttpServletResponse response) { String code = request.getParameter("code"); // compare state token in session and state token in response of google // if equals return to home // if not error page if (code == null) { logger.error("Error in google authentication flow"); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return ""; } else { try { FBUser userInfo = auth.getUserInfoJson(code); response.setStatus(HttpServletResponse.SC_OK); request.getSession().setAttribute(FBAuthHelper.SESSION_FB_CHECK, "true"); return String.format("redirect:/eauth/facebook?target=%s&id=%s&email=%s&first_name=%s&last_name=%s", URLEncoder.encode((String) request.getSession().getAttribute("redirect"), "UTF8"), userInfo.getId(), userInfo.getEmail(), userInfo.getFirst_name(), userInfo.getLast_name()); } catch (IOException e) { logger.error("IOException .. Problem in reading user data.", e); response.setStatus(HttpServletResponse.SC_NOT_FOUND); } } return "redirect:/"; }
From source file:eu.eubrazilcc.lvl.oauth2.rest.OAuth2TokenRevocation.java
@POST @Consumes("application/x-www-form-urlencoded") @Produces("application/json") public Response revoke(final @Context HttpServletRequest request, final MultivaluedMap<String, String> form) throws OAuthSystemException { try {//from w w w . ja v a2s .co m final OAuthTokenRevocationRequest oauthRequest = new OAuthTokenRevocationRequest( new OAuth2RequestWrapper(request, form, null)); // check if client id is valid if (!CLIENT_APP_DAO.isValid(oauthRequest.getClientId())) { final OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST) .setError(OAuthError.TokenResponse.INVALID_CLIENT) .setErrorDescription(INVALID_CLIENT_DESCRIPTION).buildJSONMessage(); return Response.status(response.getResponseStatus()).entity(response.getBody()).build(); } // check if client secret is valid if (!CLIENT_APP_DAO.isValid(oauthRequest.getClientId(), oauthRequest.getClientSecret())) { final OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED) .setError(OAuthError.TokenResponse.UNAUTHORIZED_CLIENT) .setErrorDescription(INVALID_CLIENT_DESCRIPTION).buildJSONMessage(); return Response.status(response.getResponseStatus()).entity(response.getBody()).build(); } // do revoking for different token types if (isEmpty(oauthRequest.getParam(OAuthTokenRevocationRequest.TOKEN_TYPE_HINT)) || oauthRequest.getParam(OAuthTokenRevocationRequest.TOKEN_TYPE_HINT) .equals(OAuthTokenRevocationRequest.ACCESS_TOKEN)) { TOKEN_DAO.delete(oauthRequest.getParam(OAuthTokenRevocationRequest.TOKEN)); } else if (oauthRequest.getParam(OAuthTokenRevocationRequest.TOKEN_TYPE_HINT) .equals(OAuthTokenRevocationRequest.REFRESH_TOKEN)) { // refresh token is not supported in this implementation final OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST) .setError(UNSUPPORTED_TOKEN_TYPE_ERROR) .setErrorDescription("refresh token is not supported in this implementation") .buildJSONMessage(); return Response.status(response.getResponseStatus()).entity(response.getBody()).build(); } else { final OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST) .setError(UNSUPPORTED_TOKEN_TYPE_ERROR) .setErrorDescription("unsupported token type: " + oauthRequest.getParam(OAuthTokenRevocationRequest.TOKEN_TYPE_HINT)) .buildJSONMessage(); return Response.status(response.getResponseStatus()).entity(response.getBody()).build(); } return Response.status(HttpServletResponse.SC_OK).build(); } catch (OAuthProblemException e) { final OAuthResponse res = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).error(e) .buildJSONMessage(); return Response.status(res.getResponseStatus()).entity(res.getBody()).build(); } }
From source file:it.smartcommunitylab.aac.auth.fb.FBController.java
/** * This rest web service is the one that google called after login (callback * url). First it retrieve code and token that google sends back. It checks * if code and token are not null, then if token is the same that was saved * in session. If it is not response status is UNAUTHORIZED, otherwise it * retrieves user data. If user is not already saved in db, then user is * added in db, iff email is not already used, otherwise it sends an * UNAUTHORIZED status and redirect user to home page without authenticating * him/her. If it is all ok, then it authenticates user in spring security * and create cookie user. Then redirects authenticated user to home page * where user can access protected resources. * //from ww w .j av a2 s .c o m * @param request * : instance of {@link HttpServletRequest} * @param response * : instance of {@link HttpServletResponse} * @return redirect to home page */ @RequestMapping(value = "/callback", method = RequestMethod.GET) public String confirmStateToken(HttpServletRequest request, HttpServletResponse response) { String code = request.getParameter("code"); // compare state token in session and state token in response of google // if equals return to home // if not error page if (code == null) { logger.error("Error in google authentication flow"); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return ""; } else { try { FBUser userInfo = auth.getUserInfoJson(code); response.setStatus(HttpServletResponse.SC_OK); request.getSession().setAttribute(FBAuthHelper.SESSION_FB_CHECK, "true"); String res = String.format( "redirect:/eauth/facebook?" + "target=%s" + "&id=%s" + "&first_name=%s" + "&last_name=%s", URLEncoder.encode((String) request.getSession().getAttribute("redirect"), "UTF8"), userInfo.getId(), userInfo.getFirst_name(), userInfo.getLast_name()); if (StringUtils.hasText(userInfo.getEmail())) { res += "&email=" + userInfo.getEmail(); } return res; } catch (IOException e) { logger.error("IOException .. Problem in reading user data.", e); response.setStatus(HttpServletResponse.SC_NOT_FOUND); } } return "redirect:/"; }
From source file:de.mpg.escidoc.pubman.sword.PubManServiceDocumentServlet.java
/** * Process the GET request./* w w w .java 2 s.co m*/ * @param HttpServletRequest * @param HttpServletResponse * @throws ServletException * @throws IOException */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Create the ServiceDocumentRequest ServiceDocumentRequest sdr = new ServiceDocumentRequest(); SwordUtil util = new SwordUtil(); AccountUserVO user = null; String usernamePassword = this.getUsernamePassword(request); if ((usernamePassword != null) && (!usernamePassword.equals(""))) { int p = usernamePassword.indexOf(":"); if (p != -1) { sdr.setUsername(usernamePassword.substring(0, p)); sdr.setPassword(usernamePassword.substring(p + 1)); user = util.getAccountUser(sdr.getUsername(), sdr.getPassword()); this.currentUser = user; } } else { String s = "Basic realm=\"SWORD\""; response.setHeader("WWW-Authenticate", s); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return; } try { String doc = this.swordServer.doServiceDocument(sdr); this.currentUser = null; // Print out the Service Document response.setCharacterEncoding("UTF-8"); response.setContentType("application/xml"); PrintWriter out = response.getWriter(); out.write(doc); out.flush(); } catch (SWORDAuthenticationException sae) { response.setHeader("WWW-Authenticate", sae.getLocalizedMessage()); response.setStatus(401); response.setCharacterEncoding("UTF-8"); this.currentUser = null; } catch (Exception e) { this.log.error(e); } }
From source file:eu.trentorise.smartcampus.permissionprovider.controller.CASController.java
/** * After the user authenticated redirect to the requested service URL with the ticket. * @return/*from w w w. j a va 2s. c o m*/ */ @RequestMapping("/cas/loginsuccess") public ModelAndView casLoginsuccess(HttpServletRequest req, HttpServletResponse res, @RequestParam(required = false) String service) { try { if (service == null) { service = (String) req.getSession().getAttribute("_service"); if (service == null) { logger.error("CAS login error: no service URL specified"); res.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return new ModelAndView("cas_error"); } } checkService(req, res, service); User user = userRepository.findOne(getUserId()); String ticket = ticketManager.getTicket(user.getId().toString(), service); return new ModelAndView("redirect:" + service + "?ticket=" + ticket); } catch (CASException e) { logger.error("CAS login error: " + e.getMessage()); res.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return new ModelAndView("redirect:" + service); } }
From source file:org.netxilia.server.security.ExcludeAjaxExceptionTranslationFilter.java
private void handleException(HttpServletRequest request, HttpServletResponse response, FilterChain chain, RuntimeException exception) throws IOException { if (request.getHeader(AJAX_HEADER) == null) { throw new RuntimeException(exception); }//ww w . ja v a2s .c o m if (exception instanceof AuthenticationException) { logger.debug("Returning AJAX CALL"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } else if (exception instanceof AccessDeniedException) { if (authenticationTrustResolver.isAnonymous(SecurityContextHolder.getContext().getAuthentication())) { logger.debug("Returning AJAX CALL"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } } throw new RuntimeException(exception); }