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:io.github.howiefh.jeews.modules.oauth2.controller.AccessTokenController.java
private HttpEntity<String> buildInvalidClientSecretResponse() throws OAuthSystemException { OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED) .setError(OAuthError.TokenResponse.UNAUTHORIZED_CLIENT) .setErrorDescription(Constants.INVALID_CLIENT_DESCRIPTION).buildJSONMessage(); return new ResponseEntity<String>(response.getBody(), HttpStatus.valueOf(response.getResponseStatus())); }
From source file:com.google.gsa.valve.rootAuth.RootAuthorizationProcess.java
/** * /*from ww w . j av a2 s . c o m*/ * This is the default root authorize method that manages the whole * authorization lifecycle when accessing the backend repositories. * <p> * Based on the information included in the config file, it uses that * information to manage the authorization process. If there is any URL * pattern defined in the config file that matches with the url sent to * the authorize() method, a new authorization class of that kind is created. * <p> * At the end, it collects the error message coming from the specific * authorization class' authorize() method. If there is any problem during * the processing, it's returned as well. * * @param request HTTP request * @param response HTTP response * @param authCookies vector that contains the authentication cookies * @param url the document url * @param id the default credential id * * @return the HTTP error code * * @throws HttpException * @throws IOException */ public int authorize(HttpServletRequest request, HttpServletResponse response, Cookie[] authCookies, String url, String id) throws HttpException, IOException, nonValidSessionException { logger.debug("Authorize"); // Initialize status code int statusCode = HttpServletResponse.SC_UNAUTHORIZED; boolean patternMatch = false; boolean rootIDExists = false; //UserSession UserSession userSession = null; //GSA cookie Cookie gsaAuthCookie = null; //Encoding support String newURL = null; //Try to avoid the double encoding problem try { newURL = URLDecoder.decode(url, ENCODING); } catch (IllegalArgumentException e) { logger.error("Illegal Argument when decoding/encoding URL"); newURL = url; } URLUTF8Encoder encoder = new URLUTF8Encoder(); url = encoder.encodeURL(new URL(newURL)); //read vars if (valveConf != null) { //Set config vars setValveConf(); } else { logger.error("Configuration error: Config file is not present"); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Configuration error - Kerberos is not set properly"); return HttpServletResponse.SC_INTERNAL_SERVER_ERROR; } //set auth Cookie Cookie[] cookies = request.getCookies(); //SAML if (cookies == null) { cookies = authCookies; } if (cookies != null) { logger.debug("authCookieName is: " + authCookieName); for (int i = 0; i < cookies.length; i++) { logger.debug("Cookie found: " + cookies[i].getName() + "; value=" + cookies[i].getValue()); if (cookies[i].getName().equals(authCookieName)) { gsaAuthCookie = cookies[i]; logger.debug("Auth Cookie found!"); break; } } } //manage Sessions if (isSessionEnabled) { logger.debug("Session is enabled. Getting session instance"); try { //Session Support. Get Sessions instance sessions = Sessions.getInstance(); //Get user session userSession = manageSessions(gsaAuthCookie); } catch (nonValidSessionException nVS) { //throw Exception throw nVS; } catch (Exception e) { logger.error("Error when geting session: " + e.getMessage(), e); } } //setting auth cookies if ((!isSessionEnabled) || ((isSessionEnabled) && (sendCookies) && (!isSAML))) { //send auth cookies as those coming straight from the browser authCookies = request.getCookies(); } else { //auth cookies are those that are in the session authCookies = userSession.getCookies(); } logger.debug("Authz authorizing [" + url + "]"); //protection if (repositoryConfigurations == null) { logger.error("Authorization Repository Vector has not been initialized"); return HttpServletResponse.SC_UNAUTHORIZED; } //Pattern of the host that has been confiogured that needs to be macthed to the URL that is being authorized. RE authZHost = null; //The host of the GSA, need to detect a request from this host and skip past it RE queryHostRE = null; try { queryHostRE = new RE("/search", RE.MATCH_CASEINDEPENDENT); } catch (RESyntaxException reSynTaxExp) { logger.error("Failed to created queryHost RE: " + reSynTaxExp.getMessage()); } ValveRepositoryConfiguration repository = null; logger.debug("Repository length: " + repositoryConfigurations.size()); for (int i = 0; i < repositoryConfigurations.size(); i++) { repository = repositoryConfigurations.elementAt(i); logger.debug("Repository ID: " + repository.getId()); //Pattern for this repository that needs to be macthed try { authZHost = new RE(repository.getPattern(), RE.MATCH_CASEINDEPENDENT); } catch (RESyntaxException reSynTaxExp) { logger.error("Failed to created authZHost RE: " + reSynTaxExp.getMessage()); logger.error("Pattern trying to use: " + repository.getPattern()); } if (queryHostRE.match(url)) { logger.debug("Query AuthZ"); statusCode = HttpServletResponse.SC_OK; patternMatch = true; } else { if (authZHost.match(url)) { //Need the correct authZProcess implementation for this repository ID AuthorizationProcessImpl authZProcess = getAuthorizationProcess(repository); if (authZProcess != null) { //URL matches a pattern if (repository.getId().equals("root")) { //If this is a match for the root id then it's the internal host used to test valve/test.html, so should just return valid logger.debug("Internal AuthZ"); statusCode = HttpServletResponse.SC_OK; patternMatch = true; rootIDExists = true; } else { logger.info("Authorizing with " + repository.getId()); patternMatch = true; //Add credentials try { addCredentials(authZProcess, userSession); } catch (Exception e) { logger.error("Error during Kerberos authZ treatment : " + e.getMessage(), e); } try { String repoID = repository.getId(); statusCode = authZProcess.authorize(request, response, authCookies, url, repoID); //If statusCode is UNAUTHORIZED, then the process has to stop here if (statusCode == HttpServletResponse.SC_UNAUTHORIZED) { break; } } catch (Exception e) { logger.error("Error during authorization: " + e.getMessage(), e); } } } else { logger.debug("The URL matches with the pattern defined for repository " + "[" + repository.getId() + "] but could not instantiate the class"); } } } } if (!patternMatch) { //check if "root" repository was created in the config file //if not: check if the URL is a Valve one. If so, return SC_OK if (!rootIDExists) { RE internalRE = new RE(new URL(internalURL).getHost(), RE.MATCH_CASEINDEPENDENT); boolean samePorts = (((new URL(internalURL)).getPort()) == ((new URL(url)).getPort())); if ((internalRE.match(url)) && (samePorts)) { logger.debug("This is an internal URL"); statusCode = HttpServletResponse.SC_OK; } else { logger.debug("No pattern has been defined at any repository for this URL"); //Set Status Code equal to "-1", so we do know there was no pattern found statusCode = -1; } } else { logger.debug("No pattern has been defined at any repository for this URL"); //Set Status Code equal to "-1", so we do know there was no pattern found statusCode = -1; } } //protection userSession = null; return statusCode; }
From source file:com.sjtu.icare.modules.sys.utils.security.FormAuthenticationFilter.java
private void onLoginFail(ServletResponse response, String errorString) throws IOException { HttpServletResponse httpResponse = (HttpServletResponse) response; httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // JSONObject errorJsonObject = new JSONObject(); // errorJsonObject.put("errno", HttpServletResponse.SC_UNAUTHORIZED+""); // errorJsonObject.put("error", errorString); BasicReturnedJson result = new BasicReturnedJson(); result.setError(errorString);//from ww w.j a v a 2s. c om result.setStatus(HttpServletResponse.SC_UNAUTHORIZED); httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); httpResponse.getWriter().write(result.toString()); }
From source file:de.logicline.splash.controller.UserController.java
/** * user login with captcha verification//from w ww. j a va2 s . co m * needs configured heroku connector add on * returns specific error if auth failed or config not don * * @param userInput * @param request * @param response * @return */ @RequestMapping(value = "/user/clogin", method = RequestMethod.POST) public @ResponseBody Map<String, String> userLoginWithCaptcha(@RequestBody Map<String, String> userInput, HttpServletRequest request, HttpServletResponse response) { String username = userInput.get("username"); String password = userInput.get("password"); String challenge = userInput.get("recaptcha_challenge_field"); String uresponse = userInput.get("recaptcha_response_field"); ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(request.getRemoteAddr(), challenge, uresponse); if (reCaptchaResponse.isValid()) { response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED); return null; } UserEntity userEntityTmp = userService.getUserByName(username); if (userEntityTmp == null || BCrypt.checkpw(password, userEntityTmp.getPassword())) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return null; } // TODO merge with normal login Map<String, String> responseMap = new HashMap<String, String>(); String token = userEntityTmp.getToken(); responseMap.put("token", token); responseMap.put("userId", String.valueOf(userEntityTmp.getUserId())); responseMap.put("role", userEntityTmp.getRole()); ContactEntity contactEntity = userService.getContact(token); if (contactEntity != null) { responseMap.put("firstName", contactEntity.getFirstName()); responseMap.put("lastName", contactEntity.getLastName()); } return responseMap; }
From source file:org.ngrinder.script.controller.DavSvnController.java
/** * Request Handler./*from ww w . j ava2s . c om*/ * * @param request * request * @param response * response * @throws ServletException * occurs when servlet has a problem. * @throws IOException * occurs when file system has a problem. */ @Override public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (LOGGER.isTraceEnabled()) { logRequest(request); } try { final String head = DAVPathUtil.head(request.getPathInfo()); final User currentUser = userContext.getCurrentUser(); // check the security. If the other user tries to the other user's // repo, deny it. if (!StringUtils.equals(currentUser.getUserId(), head)) { SecurityContextHolder.getContext().setAuthentication(null); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, head + " is not accessible by " + currentUser.getUserId()); return; } // To make it understand Asian Language.. request = new MyHttpServletRequestWrapper(request); DAVRepositoryManager repositoryManager = new DAVRepositoryManager(getDAVConfig(), request); ServletDAVHandler handler = DAVHandlerExFactory.createHandler(repositoryManager, request, response); handler.execute(); } catch (DAVException de) { response.setContentType(XML_CONTENT_TYPE); handleError(de, response); } catch (SVNException svne) { StringWriter sw = new StringWriter(); svne.printStackTrace(new PrintWriter(sw)); /** * truncate status line if it is to long */ String msg = sw.getBuffer().toString(); if (msg.length() > 128) { msg = msg.substring(0, 128); } SVNErrorCode errorCode = svne.getErrorMessage().getErrorCode(); if (errorCode == SVNErrorCode.FS_NOT_DIRECTORY || errorCode == SVNErrorCode.FS_NOT_FOUND || errorCode == SVNErrorCode.RA_DAV_PATH_NOT_FOUND) { response.sendError(HttpServletResponse.SC_NOT_FOUND, msg); } else if (errorCode == SVNErrorCode.NO_AUTH_FILE_PATH) { response.sendError(HttpServletResponse.SC_FORBIDDEN, msg); } else if (errorCode == SVNErrorCode.RA_NOT_AUTHORIZED) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, msg); } else { String errorBody = generateStandardizedErrorBody(errorCode.getCode(), null, null, svne.getMessage()); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setContentType(XML_CONTENT_TYPE); response.getWriter().print(errorBody); } } catch (Throwable th) { StringWriter sw = new StringWriter(); th.printStackTrace(new PrintWriter(sw)); String msg = sw.getBuffer().toString(); LOGGER.debug("Error in DavSVN Controller", th); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); } finally { response.flushBuffer(); } }
From source file:com.vmware.identity.samlservice.impl.AuthnRequestStateTLSClientAuthenticationFilter.java
@Override public void authenticate(AuthnRequestState t) throws SamlServiceException { log.debug("AuthnRequestStateTLSClientAuthenticationFilter.authenticate is called"); Validate.notNull(t);/*ww w . j a v a2s .c o m*/ IdmAccessor accessor = t.getIdmAccessor(); Validate.notNull(accessor); HttpServletRequest request = t.getRequest(); Validate.notNull(request); AuthnRequest authnRequest = t.getAuthnRequest(); Validate.notNull(authnRequest); PrincipalId principalId = null; X509Certificate certChain[] = null; //Get from the custom header first. String certStr = request.getHeader(AuthnRequestStateTLSClientAuthenticationFilter.clientCertHeader); if (certStr != null && certStr.length() > 0 && request.getAuthType() == SecurityRequestWrapper.VMWARE_CLIENT_CERT_AUTH) { ByteArrayInputStream bais = null; CertificateFactory cf; try { cf = CertificateFactory.getInstance("X.509"); bais = new ByteArrayInputStream(Base64.decode(certStr)); X509Certificate cert = (X509Certificate) cf.generateCertificate(bais); certChain = new X509Certificate[] { cert }; } catch (CertificateException e1) { log.error("Error reading client certificate from http header. ", e1); ValidationResult vr = new ValidationResult(HttpServletResponse.SC_UNAUTHORIZED, WebSSOError.UNAUTHORIZED, WebSSOError.INVALID_CREDENTIAL); t.setValidationResult(vr); throw new SamlServiceException("Client Certificate error.", e1); } } // Get from standard place of sl client cert location if (certChain == null || certChain.length == 0) { certChain = (X509Certificate[]) request .getAttribute(AuthnRequestStateTLSClientAuthenticationFilter.clientCertAttributeName); } if (certChain == null || certChain.length == 0) { ValidationResult vr = new ValidationResult(HttpServletResponse.SC_UNAUTHORIZED, WebSSOError.UNAUTHORIZED, WebSSOError.NO_CLIENT_CERT); t.setValidationResult(vr); } else { try { principalId = accessor.authenticate(certChain); Validate.notNull(principalId, "principalId"); } catch (Exception ex) { // could not authenticate with the certificate ValidationResult vr = new ValidationResult(HttpServletResponse.SC_UNAUTHORIZED, WebSSOError.UNAUTHORIZED, WebSSOError.INVALID_CREDENTIAL); t.setValidationResult(vr); } } if (principalId != null) { t.setPrincipalId(principalId); t.setAuthnMethod(AuthnMethod.TLSCLIENT); } }
From source file:com.ecyrd.jspwiki.dav.WikiDavServlet.java
@Override protected void doPut(HttpServletRequest arg0, HttpServletResponse response) throws ServletException, IOException { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "JSPWiki is read-only."); }
From source file:de.perdoctus.synology.jdadapter.controller.JdAdapter.java
public void handleClassicRequest(final String jk, final String crypted, final HttpServletResponse resp) throws IOException { LOG.debug("Configuration: " + drClient.toString()); try {/* ww w .ja va2 s . c o m*/ final String key = extractKey(jk); final List<URI> targets = Decrypter.decryptDownloadUri(crypted, key); final List<URI> fixedTargets = fixURIs(targets); LOG.debug("Sending download URLs to Synology NAS. Number of URIs: " + targets.size()); for (URI target : fixedTargets) { drClient.addDownloadUrl(target); } resp.setStatus(HttpServletResponse.SC_OK); analyticsTracker.trackEvent(ANALYTICS_EVENT_CATEGORY, "Classic Request", "added targets", targets.size()); } catch (ScriptException ex) { LOG.error(ex.getMessage(), ex); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Failed to evaluate script:\n" + ex.getMessage()); } catch (SynoException ex) { LOG.error(ex.getMessage(), ex); if (ex instanceof LoginException) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, ex.getMessage()); } else { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage()); } } catch (URISyntaxException ex) { LOG.error("Decrypted URL seems to be corrupt.", ex); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage()); } }
From source file:com.janrain.backplane.provision.ProvisioningController.java
/** * Handle auth errors/* w w w . j a v a 2 s . c o m*/ */ @ExceptionHandler @ResponseBody public Map<String, String> handle(final AuthException e, HttpServletResponse response) { logger.error("Provisioning authentication error: " + e.getMessage()); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return new HashMap<String, String>() { { put(ERR_MSG_FIELD, e.getMessage()); } }; }
From source file:dk.dma.msinm.user.security.SecurityServletFilter.java
/** * Main filter method// ww w . j a va2 s . c o m */ @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; // As of Wildfly 8.1, once a request has executed a successful request.login(), // subsequent requests will stay logged in. Surely this is an error(?). // Hence, we ensure that the request is logged out by default: try { request.logout(); } catch (ServletException e) { log.debug("Failed logging request out"); } // Check if the security filter needs to process this requested resource if (securityConf.checkResource(request)) { // Handle JWT if (securityConf.supportsJwtAuth()) { // Check if the request is a user-pwd or auth token login attempt if (securityConf.isJwtAuthEndpoint(request)) { handleJwtUserCredentialsOrAuthTokenLogin(request, response); return; } // If the request contains a JWT token header, attempt a login on the request request = attemptJwtAuthLogin(request, response); } // Handle Basic Authentication if (securityConf.supportsBasicAuth()) { // If the request contains a Basic authentication header, attempt a login request = attemptBasicAuthLogin(request); } // Check if the request resource specifies a required role CheckedResource errorResource = securityConf.lacksRequiredRole(request); if (errorResource != null) { log.error("User must have role " + errorResource.getRequiredRoles() + " for resource " + errorResource.getUri()); if (StringUtils.isNotBlank(errorResource.getRedirect())) { response.sendRedirect(errorResource.getRedirect()); } else { response.setStatus(getErrorStatusCode(request, HttpServletResponse.SC_UNAUTHORIZED)); } return; } } // Propagate the request chain.doFilter(request, response); }