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.bosch.cr.integration.hello_world_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 CR\""); resp.sendError(HttpServletResponse.SC_UNAUTHORIZED); return;//from ww w . j a va 2s . c o m } 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( new sun.misc.BASE64Decoder().decodeBuffer(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.ericsson.eif.hansoft.utils.HttpUtils.java
/** * @param response/*from ww w . ja v a 2 s . c om*/ * @param e - unauthorized exception * @throws IOException * @throws ServletException */ public static void sendUnauthorizedResponse(HttpServletResponse response, UnauthorizedException e) throws IOException, ServletException { if (e instanceof HansoftOAuthException) { OAuthServlet.handleException(response, e, HansoftManager.REALM); } else { // Accept basic access or OAuth authentication. response.addHeader(WWW_AUTHENTICATE_HEADER, OAUTH_AUTHENTICATION_CHALLENGE); response.addHeader(WWW_AUTHENTICATE_HEADER, BASIC_AUTHENTICATION_CHALLENGE); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } }
From source file:com.google.gsa.valve.modules.httpbasic.HTTPBasicAuthenticationProcess.java
/** * This is the main method that does the authentication and should be * invoked by the classes that would like to open a new authentication * process against an HTTP Basic protected source. * <p>// ww w. j a v a2 s .c om * The username and password for the source are assumed to be the ones * captured during the authentication. These are stored in creds and in * this case the root parameters. creds is an array of credentials for * all external sources. The first element is 'root' which contains the * credentials captured from the login page. This method reviews if there * is a credential id identical to the name associated to this module * in the config file. If so, these credentials are used to authenticate * against this HTTP Basic source, and if not 'root' one will be used * instead. * <p> * If the HTTP Basic authentication result is OK, it creates an * authentication cookie containing the HTTP Basic credentials * to be reused during authorization. The content returned back from the * remote secure backend system is sent as well. Anyway, the HTTP * response code is returned in this method to inform the caller on the * status. * * @param request HTTP request * @param response HTTP response * @param authCookies vector that contains the authentication cookies * @param url the document url * @param creds an array of credentials for all external sources * @param id the default credential id to be retrieved from creds * @return the HTTP error code * @throws HttpException * @throws IOException */ public int authenticate(HttpServletRequest request, HttpServletResponse response, Vector<Cookie> authCookies, String url, Credentials creds, String id) throws HttpException, IOException { Cookie[] cookies = null; //Credentials UsernamePasswordCredentials credentials = null; // Initialize status code int statusCode = HttpServletResponse.SC_UNAUTHORIZED; // Read cookies cookies = request.getCookies(); // Debug logger.debug("HTTP Basic authentication start"); //First read the u/p the credentails store, in this case using the same as the root login logger.debug("HttpBasic: trying to get creds from repository ID: " + id); Credential httpBasicCred = null; try { httpBasicCred = creds.getCredential(id); } catch (NullPointerException npe) { logger.error("NPE while reading credentials of ID: " + id); } if (httpBasicCred != null) { credentials = new UsernamePasswordCredentials(httpBasicCred.getUsername(), httpBasicCred.getPassword()); } else { logger.debug("HttpBasic: trying to get creds from repository \"root\""); httpBasicCred = creds.getCredential("root"); if (httpBasicCred != null) { logger.info("Trying with root credentails"); credentials = new UsernamePasswordCredentials(httpBasicCred.getUsername(), httpBasicCred.getPassword()); } } logger.debug("Authenticating"); Header[] headers = null; HttpMethodBase method = null; //Get Max connections int maxConnectionsPerHost = 30; int maxTotalConnections = 100; //Cookie Max Age int authMaxAge = -1; try { maxConnectionsPerHost = new Integer(valveConf.getMaxConnectionsPerHost()).intValue(); maxTotalConnections = (new Integer(valveConf.getMaxTotalConnections())).intValue(); authMaxAge = Integer.parseInt(valveConf.getAuthMaxAge()); } catch (NumberFormatException nfe) { logger.error( "Configuration error: chack the configuration file as the numbers set for any of the following parameters are not OK:"); logger.error(" * maxConnectionsPerHost * maxTotalConnections * authMaxAge"); } // Protection if (webProcessor == null) { // Instantiate Web processor if ((maxConnectionsPerHost != -1) && (maxTotalConnections != -1)) { webProcessor = new WebProcessor(maxConnectionsPerHost, maxTotalConnections); } else { webProcessor = new WebProcessor(); } } // // Launch the authentication process // // A fixed URL in the repository that all users have access to which can be used to authN a user // and capture the HTTP Authorization Header String authURL = valveConf.getRepository(id).getParameterValue("HTTPAuthPage"); try { // Set HTTP headers headers = new Header[1]; // Set User-Agent headers[0] = new Header("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8) Gecko/20051111 Firefox/1.5"); // Request page, testing if credentials are valid if (credentials != null) { logger.debug("Username: " + credentials.getUserName()); logger.debug("URL: " + authURL); } //HTTP request method = webProcessor.sendRequest(credentials, RequestType.GET_REQUEST, headers, null, authURL); //Read the auth header and store in the cookie, the authZ class will use this later headers = method.getRequestHeaders(); Header authHeader = null; authHeader = method.getRequestHeader("Authorization"); // Cache status code if (method != null) statusCode = method.getStatusCode(); if (statusCode == HttpServletResponse.SC_OK) { //Authentication worked, so create the auth cookie to indicate it has worked Cookie extAuthCookie = null; extAuthCookie = new Cookie(BASIC_COOKIE, ""); if (authHeader != null) { String basicCookie = null; try { basicCookie = URLEncoder.encode(getBasicAuthNChain(authHeader.getValue()), encoder); if (basicCookie == null) { basicCookie = ""; } } catch (Exception ex) { logger.error("Error when setting Basic cookie value: " + ex.getMessage(), ex); basicCookie = ""; } extAuthCookie.setValue(basicCookie); } String authCookieDomain = null; String authCookiePath = null; // Cache cookie properties authCookieDomain = valveConf.getAuthCookieDomain(); authCookiePath = valveConf.getAuthCookiePath(); // Set extra cookie parameters extAuthCookie.setDomain(authCookieDomain); extAuthCookie.setPath(authCookiePath); extAuthCookie.setMaxAge(authMaxAge); // Log info if (logger.isDebugEnabled()) logger.debug("Adding " + BASIC_COOKIE + " cookie: " + extAuthCookie.getName() + ":" + extAuthCookie.getValue() + ":" + extAuthCookie.getPath() + ":" + extAuthCookie.getDomain() + ":" + extAuthCookie.getSecure()); //sendCookies support boolean isSessionEnabled = new Boolean(valveConf.getSessionConfig().isSessionEnabled()) .booleanValue(); boolean sendCookies = false; if (isSessionEnabled) { sendCookies = new Boolean(valveConf.getSessionConfig().getSendCookies()).booleanValue(); } if ((!isSessionEnabled) || ((isSessionEnabled) && (sendCookies))) { logger.debug("Adding cookie to response"); response.addCookie(extAuthCookie); } //Add cookies to the Cookie array to support sessions authCookies.add(extAuthCookie); logger.debug("Cookie added to the array"); } // Clear webProcessor cookies webProcessor.clearCookies(); } catch (Exception e) { // Log error logger.error("HTTP Basic authentication failure: " + e.getMessage(), e); // Garbagge collect method = null; // Update status code statusCode = HttpServletResponse.SC_UNAUTHORIZED; } // End of the authentication process logger.debug("HTTP Basic Authentication completed (" + statusCode + ")"); // Return status code return statusCode; }
From source file:eu.trentorise.smartcampus.permissionprovider.controller.CASController.java
/** * Retrieve the with the user data: currently on the username is added. * @return/*from w ww. j av a2s . c o m*/ */ @RequestMapping("/cas/serviceValidate") public @ResponseBody String validateService(HttpServletRequest req, HttpServletResponse res, @RequestParam String service, @RequestParam String ticket) { try { res.setContentType("application/xml"); checkService(req, res, service); Ticket obj = ticketManager.checkTicket(service, ticket); User user = userRepository.findOne(Long.parseLong(obj.getId())); return generateSuccess(user, obj.isFromNewLogin());//new ModelAndView("redirect:"+service); } catch (CASException e) { logger.error("CAS login error: " + e.getMessage()); res.setStatus(HttpServletResponse.SC_UNAUTHORIZED); try { return generateFailure(e.getCode().toString(), e.getMessage()); } catch (Exception e1) { logger.error("CAS login error: " + e.getMessage()); res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return null; } } catch (Exception e) { e.printStackTrace(); logger.error("CAS login error: " + e.getMessage()); res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return null; } }
From source file:com.linuxbox.enkive.web.KeyNameServlet.java
public void doGet(HttpServletRequest req, HttpServletResponse resp) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("KeyNameServlet doGet started"); }/*from ww w . j a va2 s . c o m*/ try { try { Set<GathererAttributes> attributes = client.getAttributes(); JSONArray result = new JSONArray(); for (GathererAttributes attribute : attributes) { if (!attribute.getName().equals("CollectionStatsGatherer")) { Map<String, Object> keyMethods = new HashMap<String, Object>(); for (ConsolidationKeyHandler key : attribute.getKeys()) { String builtKey = ""; for (String keyPart : key.getKey()) { builtKey = builtKey + keyPart + "."; } builtKey = builtKey.substring(0, builtKey.length() - 1); if (key.getMethods() != null) { Map<String, Object> methodsMap = new HashMap<String, Object>(); Map<String, Object> innerKeyMap = new HashMap<String, Object>(); innerKeyMap.put("methods", (String[]) key.getMethods().toArray()); innerKeyMap.put("units", key.getUnits()); methodsMap.put(builtKey, innerKeyMap); keyMethods.put(key.getHumanKey(), methodsMap); } } Map<String, Object> dataTemp = new HashMap<String, Object>(); dataTemp.put(attribute.getName(), keyMethods); Map<String, Object> humanKeyWrapper = new HashMap<String, Object>(); humanKeyWrapper.put(attribute.getHumanName(), dataTemp); result.put(humanKeyWrapper); } } try { JSONObject statistics = new JSONObject(); statistics.put("results", result); resp.getWriter().write(statistics.toString()); } catch (IOException e) { // FIXME: NOAHCODE Why is this calling respondError and // throwing an exception, the catch of which calls // respondError again? respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, resp); throw new CannotRetrieveException("could not create JSON for message attachment", e); } catch (JSONException e) { // FIXME: NOAHCODE Why is this calling respondError and // throwing an exception, the catch of which calls // respondError again? respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, resp); throw new CannotRetrieveException("could not create JSON for message attachment", e); } } catch (CannotRetrieveException e) { respondError(HttpServletResponse.SC_UNAUTHORIZED, null, resp); LOGGER.error("CannotRetrieveException", e); } catch (NullPointerException e) { respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, resp); LOGGER.error("NullException thrown", e); } } catch (IOException e) { LOGGER.error("IOException thrown", e); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("StatsServlet doGet finished"); } }
From source file:com.ecyrd.jspwiki.dav.WikiDavServlet.java
@Override protected void doPost(HttpServletRequest arg0, HttpServletResponse response) throws ServletException, IOException { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "JSPWiki is read-only."); }
From source file:com.erudika.para.security.RestAuthFilter.java
private boolean userAuthRequestHandler(HttpServletRequest request, HttpServletResponse response) { Authentication userAuth = SecurityContextHolder.getContext().getAuthentication(); User user = SecurityUtils.getAuthenticatedUser(userAuth); String reqUri = request.getRequestURI(); String method = request.getMethod(); if (user != null && user.getActive()) { App parentApp;//from www . j av a2 s . c om if (userAuth instanceof JWTAuthentication) { parentApp = ((JWTAuthentication) userAuth).getApp(); } else { parentApp = Para.getDAO().read(App.id(user.getAppid())); } if (parentApp != null) { String resource = RestUtils.extractResourceName(request); if (!parentApp.isAllowedTo(user.getId(), resource, request.getMethod())) { RestUtils .returnStatusResponse(response, HttpServletResponse.SC_FORBIDDEN, Utils.formatMessage( "You don't have permission to access this resource. " + "[user: {0}, resource: {1} {2}]", user.getId(), method, reqUri)); return false; } } else { RestUtils.returnStatusResponse(response, HttpServletResponse.SC_NOT_FOUND, "App not found."); return false; } } else { RestUtils.returnStatusResponse(response, HttpServletResponse.SC_UNAUTHORIZED, Utils .formatMessage("You don't have permission to access this resource. [{0} {1}]", method, reqUri)); return false; } return true; }
From source file:com.vmware.identity.samlservice.impl.AuthnRequestStateRsaAmAuthenticationFilter.java
@Override public void authenticate(AuthnRequestState t) throws SamlServiceException { log.debug("AuthnRequestStateRsaAmAuthenticationFilter.authenticate is called"); Validate.notNull(t);/*from w ww . j a v a 2s.co m*/ IdmAccessor accessor = t.getIdmAccessor(); Validate.notNull(accessor); HttpServletRequest request = t.getRequest(); Validate.notNull(request); AuthnRequest authnRequest = t.getAuthnRequest(); Validate.notNull(authnRequest); // extract auth data String authData = getAuthData(request); Validate.notNull(authData); // byte[] decodedAuthData = Base64.decode(authData); RSAAMResult result = null; // call IDM to perform SecureID auth String authParam = request.getParameter(Shared.REQUEST_AUTH_PARAM); Validate.notNull(authParam); String[] parts = authData.split(" "); assert parts.length == 1 || parts.length == 2; byte[] decodedAuthData; byte[] decodedSessionID = null; String rsaSessionID = null; if (parts.length == 1) { decodedAuthData = Base64.decode(authData); } else if (parts.length == 2) { decodedSessionID = Base64.decode(parts[0]); decodedAuthData = Base64.decode(parts[1]); } else { throw new SamlServiceException( "Wrong castle parameter. Extra parameter found in " + Shared.REQUEST_AUTH_PARAM); } try { // extract username and passcode from the auth data String unp = new String(decodedAuthData, "UTF-8"); if (decodedSessionID != null) { rsaSessionID = new String(decodedSessionID, "UTF-8"); } int idx = unp.indexOf(':'); String username = idx > 0 ? unp.substring(0, idx) : null; String passcode = idx > 0 && unp.length() > idx + 1 ? unp.substring(idx + 1) : null; // call authenticate result = accessor.authenticatebyPasscode(rsaSessionID, username, passcode); Validate.notNull(result); } catch (IDMSecureIDNewPinException e) { // failed to authenticate with passcode. ValidationResult vr = new ValidationResult(HttpServletResponse.SC_UNAUTHORIZED, WebSSOError.UNAUTHORIZED, WebSSOError.SECUREID_NEWPIN_REQUIRED); t.setValidationResult(vr); throw new SamlServiceException("Failed to authenticate by passcode. ", e); } catch (Exception e) { // failed to authenticate with passcode. ValidationResult vr = new ValidationResult(HttpServletResponse.SC_UNAUTHORIZED, WebSSOError.UNAUTHORIZED, null); t.setValidationResult(vr); throw new SamlServiceException("Failed to authenticate by passcode. ", e); } //Next code mode. We include header "CastleAuthorizatin=RSAAM sessionID" in the error response. if (result != null) { if (!result.complete()) { // need additional auth exchange log.debug("Requesting next passcode."); String encodedRsaSessionID = Shared.encodeBytes(result.getRsaSessionID().getBytes()); t.setWwwAuthenticate(Shared.RSAAM_AUTH_PREFIX + " " + encodedRsaSessionID); ValidationResult vr = new ValidationResult(HttpServletResponse.SC_UNAUTHORIZED, WebSSOError.UNAUTHORIZED, WebSSOError.SECUREID_NEXTCODE_MODE); t.setValidationResult(vr); throw new SamlServiceException("Require next passcode to finish the authentication."); } PrincipalId principalId = result.getPrincipalId(); Validate.notNull(principalId); t.setPrincipalId(principalId); t.setAuthnMethod(AuthnMethod.TIMESYNCTOKEN); } }
From source file:org.infinispan.server.test.rest.security.RESTCertSecurityTest.java
@Test @InSequence(1)//w w w. j av a 2 s . c om public void testSecuredWriteOperations() throws Exception { try { controller.start(CONTAINER1); //correct alias for the certificate put(securedClient(testAlias), keyAddress(KEY_A), HttpServletResponse.SC_OK); //test wrong authorization, 1. wrong alias for the certificate put(securedClient(test2Alias), keyAddress(KEY_B), HttpServletResponse.SC_FORBIDDEN); //2. access over 8080 put(securedClient(testAlias), keyAddressUnsecured(KEY_B), HttpServletResponse.SC_UNAUTHORIZED); post(securedClient(testAlias), keyAddress(KEY_C), HttpServletResponse.SC_OK); post(securedClient(test2Alias), keyAddress(KEY_D), HttpServletResponse.SC_FORBIDDEN); //get is not secured, should be working over 8080 HttpResponse resp = get(securedClient(test2Alias), keyAddressUnsecured(KEY_A), HttpServletResponse.SC_OK); String content = new BufferedReader(new InputStreamReader(resp.getEntity().getContent())).readLine(); assertEquals("data", content); head(securedClient(test2Alias), keyAddressUnsecured(KEY_A), HttpServletResponse.SC_OK); delete(securedClient(test2Alias), keyAddress(KEY_A), HttpServletResponse.SC_FORBIDDEN); delete(securedClient(testAlias), keyAddress(KEY_A), HttpServletResponse.SC_OK); delete(securedClient(testAlias), keyAddress(KEY_C), HttpServletResponse.SC_OK); } finally { controller.stop(CONTAINER1); } }
From source file:org.eclipse.userstorage.tests.util.USSServer.java
protected void login(HttpServletRequest request, HttpServletResponse response) throws IOException { Map<String, Object> requestObject = JSONUtil.parse(request.getInputStream(), null); String username = (String) requestObject.get("username"); String password = (String) requestObject.get("password"); User user = users.get(username);/*from w w w . java2 s . co m*/ if (user == null || password == null || !password.equals(user.getPassword())) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } response.setStatus(HttpServletResponse.SC_OK); response.setContentType("application/json"); Session session = addSession(user); Cookie cookie = new Cookie("SESSION", session.getID()); cookie.setPath("/"); response.addCookie(cookie); Map<String, Object> responseObject = new LinkedHashMap<String, Object>(); responseObject.put("sessid", session.getID()); responseObject.put("token", session.getCSRFToken()); InputStream body = JSONUtil.build(responseObject); try { ServletOutputStream out = response.getOutputStream(); IOUtil.copy(body, out); out.flush(); } finally { IOUtil.closeSilent(body); } }