Example usage for javax.servlet.http HttpServletResponse SC_FORBIDDEN

List of usage examples for javax.servlet.http HttpServletResponse SC_FORBIDDEN

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_FORBIDDEN.

Prototype

int SC_FORBIDDEN

To view the source code for javax.servlet.http HttpServletResponse SC_FORBIDDEN.

Click Source Link

Document

Status code (403) indicating the server understood the request but refused to fulfill it.

Usage

From source file:com.att.ajsc.csilogging.common.CSILoggingUtils.java

public void finalizeRequest(HttpServletRequest request, HttpServletResponse response) {

    logger.debug("In...:finalizeRequest");
    String servicename = UtilLib.getServiceName(request);

    PerformanceTrackingBean perfTrackerBean = (PerformanceTrackingBean) request
            .getAttribute(PERFORMANCE_TRACKER_BEAN);
    long startTime = (long) request.getAttribute(CommonNames.START_TIME);
    AuditRecord ar = new AuditRecord();
    try {//  w  w w  .j  av a 2  s  . com
        logger.debug("Starting application specific handling...:finalizeRequest");
        // request.setAttribute(CommonNames.AUDIT_RECORD, ar);
        // request.setAttribute(CommonNames.ATTR_START_TIME,
        // Long.valueOf(startTime).toString());
        perfTrackerBean.setAuditRecord(ar);
        servicename = LoggerNameConverter.convertNormalizedName(request, servicename);

        perfTrackerBean.setServiceName(servicename);

        perfTrackerBean.setRequestContentLen(request.getContentLength());
        perfTrackerBean.setResponseMsgSize(getResponseLength(request));
        perfTrackerBean.setMethod(request.getMethod());

        ar.setInstanceName(SystemParams.instance().getInstanceName());
        ar.setInitiatedTimestamp(UtilLib.epochToXmlGC(startTime));
        ar.setVtier(SystemParams.instance().getVtier());
        ar.setCluster(SystemParams.instance().getCluster());
        ar.setHostName(SystemParams.instance().getHostName());
        ar.setHostIPAddress(SystemParams.instance().getIpAddress());
        ar.setSubject("CW.pub.spm2." + servicename + ".response");
        ar.setMode("");
        ar.setServiceKeyData1("");
        ar.setServiceKeyData2("");
        ar.setSourceClass(CommonNames.SOURCE_CLASS);
        ar.setSourceMethod(CommonNames.AUDIT_LOGGER_NAME);
        ar.setTransactionName(servicename);
        /*
         * ar.setApplicationId(request.getAttribute(CommonNames.
         * CSI_USER_NAME));
         * ar.setConversationId(request.getAttribute(CommonNames.
         * CSI_CONVERSATION_ID));
         * ar.setUniqueTransactionId(request.getAttribute(CommonNames.
         * CSI_UNIQUE_TXN_ID));
         * ar.setOriginalMessageId(request.getAttribute(CommonNames.
         * CSI_MESSAGE_ID));
         * ar.setOriginatorId(request.getAttribute(CommonNames.
         * CSI_ORIGINATOR_ID));
         * ar.setClientApp(UtilLib.ifNullThenEmpty(request.getAttribute(
         * CommonNames.CSI_CLIENT_APP))); ar.setOriginationSystemId("N/A");
         * ar.setOriginationSystemName(request.getAttribute(CommonNames.
         * CSI_USER_NAME));
         * ar.setOriginationSystemVersion(request.getAttribute(CommonNames.
         * CSI_VERSION));
         */

        ar.setApplicationId(perfTrackerBean.getUserName());
        ar.setConversationId(perfTrackerBean.getConversationId());
        ar.setUniqueTransactionId(perfTrackerBean.getUniqueTransactionId());
        ar.setOriginalMessageId(perfTrackerBean.getOriginalMessageId());
        ar.setOriginatorId(perfTrackerBean.getOriginatorId());
        ar.setClientApp(UtilLib.ifNullThenEmpty(perfTrackerBean.getClientApp()));
        ar.setOriginationSystemId("N/A");
        ar.setOriginationSystemName(perfTrackerBean.getUserName());
        ar.setOriginationSystemVersion(perfTrackerBean.getOriginationSystemVersion());

        // new fields added per new schema
        ar.setClientIP(request.getRemoteAddr());
        ar.setHttpMethod(perfTrackerBean.getMethod());
        ar.setRequestURL(request.getPathInfo());

        // PerformanceTracking.initPerfTrack(request,servicename);
        PerformanceTracking.initPerfTrack(perfTrackerBean, servicename);
        // PerformanceTracking.addPerfTrack(request, "Main", "I",
        // startTime.toString(), servicename);

        int httpCode = response.getStatus();

        if (httpCode == HttpServletResponse.SC_UNAUTHORIZED) {
            ar.setResponseCode(CommonNames.CSI_AUTH_ERROR);
            ar.setResponseDescription(CommonErrors.DEF_401_FAULT_DESC);
            ar.setFaultCode(CommonErrors.DEF_401_FAULT_CODE);
            ar.setFaultDescription(CommonErrors.DEF_401_FAULT_DESC);
            ar.setFaultLevel("ERROR");
            ar.setTransactionStatus("E");
            ar.setFaultEntity("CSI");
            ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));
            ar.setExternalFaultCode(String.valueOf(httpCode));
            ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR);
        } else if (httpCode == HttpServletResponse.SC_FORBIDDEN) {
            ar.setResponseCode(CommonNames.CSI_AUTH_ERROR);
            ar.setResponseDescription(CommonErrors.DEF_403_FAULT_DESC);
            ar.setFaultCode(CommonErrors.DEF_403_FAULT_CODE);
            ar.setFaultDescription(CommonErrors.DEF_403_FAULT_DESC);
            ar.setFaultLevel("ERROR");
            ar.setTransactionStatus("E");
            ar.setFaultEntity("CSI");
            ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));
            ar.setExternalFaultCode(String.valueOf(httpCode));
            ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR);
        } else if (httpCode == HttpServletResponse.SC_NOT_IMPLEMENTED) {

            ar.setResponseCode(CommonNames.CSI_SERVICE_UNAVAIL_ERROR);
            ar.setResponseDescription(CommonErrors.DEF_501_FAULT_DESC);
            ar.setFaultCode(CommonErrors.DEF_501_FAULT_CODE);
            ar.setFaultDescription(CommonErrors.DEF_501_FAULT_DESC);
            ar.setFaultLevel("ERROR");
            ar.setTransactionStatus("E");
            ar.setFaultEntity("CSI");
            ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));
            ar.setExternalFaultCode(String.valueOf(httpCode));
            ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR);

        } else if (httpCode == HttpServletResponse.SC_SERVICE_UNAVAILABLE) {
            ar.setResponseCode(CommonNames.CSI_SERVICE_UNAVAIL_ERROR);
            ar.setResponseDescription(CommonErrors.DEF_503_FAULT_DESC);
            ar.setFaultCode(CommonErrors.DEF_503_FAULT_CODE);
            ar.setFaultDescription(CommonErrors.DEF_503_FAULT_DESC);
            ar.setFaultLevel("ERROR");
            ar.setTransactionStatus("E");
            ar.setFaultEntity("CSI");
            ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));
            ar.setExternalFaultCode(String.valueOf(httpCode));
            ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR);
        } else if (400 <= httpCode && httpCode <= 499) {

            ar.setResponseCode(CommonNames.CSI_SERVICE_UNAVAIL_ERROR);
            ar.setResponseDescription(CommonErrors.DEF_4NN_FAULT_DESC);
            ar.setFaultCode(CommonErrors.DEF_4NN_FAULT_CODE);
            ar.setFaultDescription(CommonErrors.DEF_4NN_FAULT_DESC);
            ar.setFaultLevel("ERROR");
            ar.setFaultEntity("CSI");
            ar.setTransactionStatus("E");
            ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));
            ar.setExternalFaultCode(String.valueOf(httpCode));
            ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR);

        } else if (httpCode == 500) {

            ar.setResponseCode(CommonNames.CSI_SERVICE_UNAVAIL_ERROR);
            ar.setResponseDescription(CommonErrors.DEF_500_FAULT_DESC);
            ar.setFaultCode(CommonErrors.DEF_500_FAULT_CODE);
            ar.setFaultDescription(CommonErrors.DEF_500_FAULT_DESC);
            ar.setFaultLevel("ERROR");
            ar.setFaultEntity("CSI");
            ar.setTransactionStatus("E");
            // ar.setFaultTimestamp(UtilLib.epochToXmlGC((new
            // Double(System.nanoTime()/1000000)).longValue()));
            ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));
            ar.setExternalFaultCode(String.valueOf(httpCode));
            ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR);

        }

        else {
            ar.setResponseDescription(CommonNames.CSI_SUCCESS);
            ar.setResponseCode(CommonNames.CSI_SUCCESS_RESPONSE_CODE);
            ar.setTransactionStatus("C");
        }

        // Enhance CSI logging to use the CAET error code

        if (response.getHeader(CommonNames.CAET_RestErrorCode) != null
                || response.getHeader(CommonNames.CAET_CingularErrorCode) != null) {

            // if(request.getHeader("X-CAET-CingularErrorCode") != null){
            if ("Y".equals(request.getAttribute(CommonNames.AJSC_CAET_IS_REST_SERVICE))) {

                ar.setResponseCode(response.getHeader(CommonNames.CAET_CingularErrorCategory));
                ar.setResponseDescription(response.getHeader(CommonNames.CAET_RestErrorDescription));

            } else

            {

                ar.setResponseCode(response.getHeader(CommonNames.CAET_CingularErrorCode));

                ar.setResponseDescription(response.getHeader(CommonNames.CAET_CingularErrorDescription));

            }

            ar.setFaultCode(response.getHeader(CommonNames.CAET_FaultCode));

            ar.setFaultDescription(response.getHeader(CommonNames.CAET_FaultDesc));

            ar.setFaultLevel(CommonNames.ERROR);

            ar.setFaultEntity(response.getHeader(CommonNames.CAET_FaultEntity));

            ar.setTransactionStatus("E");

            ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));

            // ar.setFaultTimestamp(UtilLib.epochToXmlGC((new
            // Double(System.nanoTime()/1000000)).longValue()));

            ar.setExternalFaultCode(String.valueOf(httpCode));

            ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR);

        }

    }

    catch (Exception e) {
        // AuditRecord ar =
        // (AuditRecord)request.getAttribute(CommonNames.AUDIT_RECORD);
        ar.setResponseCode(CommonNames.CSI_GENERIC_UNKNOWN_ERROR);
        ar.setResponseDescription(CommonErrors.DEF_5NN_FAULT_DESC);
        ar.setFaultEntity("CSI");
        ar.setFaultCode(CommonErrors.DEF_5NN_FAULT_CODE);
        ar.setFaultDescription(e.getMessage());
        ar.setFaultLevel("ERROR");
        ar.setFaultSequenceNumber("1");
        ar.setTransactionStatus("E");
        ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));
        // ar.setFaultTimestamp(UtilLib.epochToXmlGC(((Long)System.nanoTime()/1000000).longValue()));
        logger.error("EXCEPTION - " + e.getMessage());
    }

    finally {
        // AuditRecord ar =
        // (AuditRecord)request.getAttribute(CommonNames.AUDIT_RECORD);
        if (ar != null) {

            if (perfTrackerBean != null && !perfTrackerBean.isAsync()) {
                perfTrackerBean.setAuditRecord(ar);
                logger.debug("Before calling completeLogging");
                completeLogging(request, servicename);
            }

        } else {
            logger.debug("Audit Record is null,abort logging");
        }
    }

}

From source file:eu.dasish.annotation.backend.rest.AnnotationResource.java

/**
 * /*from   ww  w .  j av  a 2  s. c o m*/
 * @param externalIdentifier the external UUID of the annotation to be deleted.
 * @return the message telling if the annotation is deleted or not.
 * @throws IOException if sending an error fails.
 */
@DELETE
@Path("{annotationid: " + BackendConstants.regExpIdentifier + "}")
public String deleteAnnotation(@PathParam("annotationid") String externalIdentifier) throws IOException {
    Map params = new HashMap();
    try {
        int[] result = (int[]) (new RequestWrappers(this)).wrapRequestResource(params, new DeleteAnnotation(),
                Resource.ANNOTATION, Access.ALL, externalIdentifier);
        if (result != null) {
            return result[0] + " annotation(s) is(are) deleted.";
        } else {
            return "Nothing is deleted.";
        }
    } catch (NotInDataBaseException e1) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, e1.getMessage());
        return e1.getMessage();
    } catch (ForbiddenException e2) {
        httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN, e2.getMessage());
        return e2.getMessage();
    }
}

From source file:org.imsglobal.lti2.LTI2Servlet.java

@SuppressWarnings({ "unchecked", "unused", "rawtypes" })
public void registerToolProviderProfile(HttpServletRequest request, HttpServletResponse response,
        String profile_id) throws java.io.IOException {
    // Normally we would look up the deployment descriptor
    if (!TEST_KEY.equals(profile_id)) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;// w w w.  j  a  va 2  s  .  c o  m
    }

    String key = TEST_KEY;
    String secret = TEST_SECRET;

    IMSJSONRequest jsonRequest = new IMSJSONRequest(request);

    if (!jsonRequest.valid) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "Request is not in a valid format", null);
        return;
    }

    System.out.println(jsonRequest.getPostBody());

    // Lets check the signature
    if (key == null || secret == null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        doErrorJSON(request, response, jsonRequest, "Deployment is missing credentials", null);
        return;
    }

    jsonRequest.validateRequest(key, secret, request);
    if (!jsonRequest.valid) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        doErrorJSON(request, response, jsonRequest, "OAuth signature failure", null);
        return;
    }

    JSONObject providerProfile = (JSONObject) JSONValue.parse(jsonRequest.getPostBody());
    // System.out.println("OBJ:"+providerProfile);
    if (providerProfile == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "JSON parse failed", null);
        return;
    }

    JSONObject default_custom = (JSONObject) providerProfile.get(LTI2Constants.CUSTOM);

    JSONObject security_contract = (JSONObject) providerProfile.get(LTI2Constants.SECURITY_CONTRACT);
    if (security_contract == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "JSON missing security_contract", null);
        return;
    }

    String shared_secret = (String) security_contract.get(LTI2Constants.SHARED_SECRET);
    System.out.println("shared_secret=" + shared_secret);
    if (shared_secret == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "JSON missing shared_secret", null);
        return;
    }

    // Make sure that the requested services are a subset of the offered services
    ToolConsumer consumer = buildToolConsumerProfile(request, null, profile_id);

    JSONArray tool_services = (JSONArray) security_contract.get(LTI2Constants.TOOL_SERVICE);
    String retval = LTI2Util.validateServices(consumer, providerProfile);
    if (retval != null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, retval, null);
        return;
    }

    // Parse the tool profile bit and extract the tools with error checking
    retval = LTI2Util.validateCapabilities(consumer, providerProfile);
    if (retval != null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, retval, null);
        return;
    }

    // Pass the profile to the launch process
    PERSIST.put("profile", providerProfile.toString());

    // Share our happiness with the Tool Provider
    Map jsonResponse = new TreeMap();
    jsonResponse.put(LTI2Constants.CONTEXT, StandardServices.TOOLPROXY_ID_CONTEXT);
    jsonResponse.put(LTI2Constants.TYPE, StandardServices.TOOLPROXY_ID_TYPE);
    jsonResponse.put(LTI2Constants.JSONLD_ID, getServiceURL(request) + SVC_tc_registration + "/" + profile_id);
    jsonResponse.put(LTI2Constants.TOOL_PROXY_GUID, profile_id);
    jsonResponse.put(LTI2Constants.CUSTOM_URL,
            getServiceURL(request) + SVC_Settings + "/" + LTI2Util.SCOPE_ToolProxy + "/" + profile_id);
    response.setContentType(StandardServices.TOOLPROXY_ID_FORMAT);
    response.setStatus(HttpServletResponse.SC_CREATED);
    String jsonText = JSONValue.toJSONString(jsonResponse);
    M_log.log(Level.FINE, jsonText);
    PrintWriter out = response.getWriter();
    out.println(jsonText);
}

From source file:com.sonicle.webtop.core.app.servlet.ResourceRequest.java

private LookupResult lookupLicense(HttpServletRequest request, URL targetUrl) {
    String targetPath = targetUrl.getPath();
    URL fileUrl = null;/*ww  w .  j  ava 2  s .  c  om*/

    try {
        WebTopApp wta = WebTopApp.get(request);
        WebTopManager wtMgr = wta.getWebTopManager();
        if (wtMgr != null) {
            String internetName = ServletUtils.getInternetName(request);
            String domainId = wtMgr.internetNameToDomain(internetName);
            if (!StringUtils.isBlank(domainId)) {
                String pathname = wta.getHomePath(domainId) + "license.html";
                File file = new File(pathname);
                if (file.exists()) {
                    fileUrl = file.toURI().toURL();
                }
            }
        }

        if (fileUrl == null) {
            fileUrl = getResURL(targetPath);
        }

        Resource resFile = getFile(wta, fileUrl);
        return new StaticFile(fileUrl.toString(), getMimeType(targetPath), ClientCaching.NO, resFile);

    } catch (MalformedURLException | ForbiddenException ex) {
        return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
    } catch (NotFoundException ex) {
        return new Error(HttpServletResponse.SC_NOT_FOUND, "Not Found");
    } catch (InternalServerException ex) {
        return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
    } catch (ServletException ex) {
        return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
    }
}

From source file:contestWebsite.Data.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    UserCookie userCookie = UserCookie.getCookie(req);
    boolean loggedIn = userCookie != null && userCookie.authenticate();
    if (loggedIn && userCookie.isAdmin()) {
        String choice = req.getPathInfo();
        if (choice == null) {
            resp.sendRedirect("/data/overview");
        } else if (choice.equals("/overview")) {
            resp.sendRedirect("/data/overview");
        } else if (choice.equals("/registrations")) {
            String edit = req.getParameter("edit");
            if (edit != null) {
                resp.sendRedirect("/editRegistration?key=" + req.getParameter("edit"));
            } else {
                resp.sendRedirect("/data/registrations");
            }/* w w w .j  a va  2s  .  co  m*/
        } else if (choice.equals("/questions")) {
            Map<String, String[]> params = req.getParameterMap();
            DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
            Transaction txn = datastore.beginTransaction(TransactionOptions.Builder.withXG(true));
            try {
                for (String paramName : params.keySet()) {
                    if (!paramName.equals("choice") && !paramName.equals("updated")) {
                        Key key = KeyFactory.createKey("feedback", Long.parseLong(paramName));
                        String option = params.get(paramName)[0];
                        if (option.equals("r")) {
                            Entity q = datastore.get(key);
                            q.setProperty("resolved", true);
                            datastore.put(q);
                        } else if (option.equals("d")) {
                            datastore.delete(key);
                        } else {
                            resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                                    "Invalid option (must be 'r' or 'q'): " + option);
                        }
                    }
                }
                txn.commit();
            } catch (Exception e) {
                e.printStackTrace();
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
                return;
            } finally {
                if (txn.isActive()) {
                    txn.rollback();
                }
            }

            resp.sendRedirect("/data/questions?updated=1");
        } else if (choice.equals("/scores")) {
            try {
                JSONArray testsGradedJSON = new JSONArray(req.getParameter("testsGraded"));
                ArrayList<String> testsGraded = new ArrayList<String>();
                for (int i = 0; i < testsGradedJSON.length(); i++) {
                    testsGraded.add(testsGradedJSON.get(i).toString());
                }

                DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
                Transaction txn = datastore.beginTransaction(TransactionOptions.Builder.withXG(true));
                try {
                    Entity contestInfo = Retrieve.contestInfo();
                    contestInfo.setProperty("testsGraded", testsGraded);
                    datastore.put(contestInfo);
                    txn.commit();
                } catch (Exception e) {
                    e.printStackTrace();
                    resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
                } finally {
                    if (txn.isActive()) {
                        txn.rollback();
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.toString());
            }
        } else {
            resp.sendRedirect("/data/overview");
        }
    } else {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN,
                "Contest Administrator privileges required for that operation");
    }
}

From source file:io.druid.security.kerberos.KerberosAuthenticator.java

@Override
public Filter getFilter() {
    return new AuthenticationFilter() {
        private Signer mySigner;

        @Override//from ww w  . ja va2 s .c om
        public void init(FilterConfig filterConfig) throws ServletException {
            ClassLoader prevLoader = Thread.currentThread().getContextClassLoader();
            try {
                // AuthenticationHandler is created during Authenticationfilter.init using reflection with thread context class loader.
                // In case of druid since the class is actually loaded as an extension and filter init is done in main thread.
                // We need to set the classloader explicitly to extension class loader.
                Thread.currentThread().setContextClassLoader(AuthenticationFilter.class.getClassLoader());
                super.init(filterConfig);
                String configPrefix = filterConfig.getInitParameter(CONFIG_PREFIX);
                configPrefix = (configPrefix != null) ? configPrefix + "." : "";
                Properties config = getConfiguration(configPrefix, filterConfig);
                String signatureSecret = config.getProperty(configPrefix + SIGNATURE_SECRET);
                if (signatureSecret == null) {
                    signatureSecret = Long.toString(new Random().nextLong());
                    log.warn("'signature.secret' configuration not set, using a random value as secret");
                }
                final byte[] secretBytes = StringUtils.toUtf8(signatureSecret);
                SignerSecretProvider signerSecretProvider = new SignerSecretProvider() {
                    @Override
                    public void init(Properties config, ServletContext servletContext, long tokenValidity)
                            throws Exception {

                    }

                    @Override
                    public byte[] getCurrentSecret() {
                        return secretBytes;
                    }

                    @Override
                    public byte[][] getAllSecrets() {
                        return new byte[][] { secretBytes };
                    }
                };
                mySigner = new Signer(signerSecretProvider);
            } finally {
                Thread.currentThread().setContextClassLoader(prevLoader);
            }
        }

        // Copied from hadoop-auth's AuthenticationFilter, to allow us to change error response handling in doFilterSuper
        @Override
        protected AuthenticationToken getToken(HttpServletRequest request)
                throws IOException, AuthenticationException {
            AuthenticationToken token = null;
            String tokenStr = null;
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals(AuthenticatedURL.AUTH_COOKIE)) {
                        tokenStr = cookie.getValue();
                        try {
                            tokenStr = mySigner.verifyAndExtract(tokenStr);
                        } catch (SignerException ex) {
                            throw new AuthenticationException(ex);
                        }
                        break;
                    }
                }
            }
            if (tokenStr != null) {
                token = AuthenticationToken.parse(tokenStr);
                if (!token.getType().equals(getAuthenticationHandler().getType())) {
                    throw new AuthenticationException("Invalid AuthenticationToken type");
                }
                if (token.isExpired()) {
                    throw new AuthenticationException("AuthenticationToken expired");
                }
            }
            return token;
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
                throws IOException, ServletException {
            HttpServletRequest httpReq = (HttpServletRequest) request;

            // If there's already an auth result, then we have authenticated already, skip this.
            if (request.getAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT) != null) {
                filterChain.doFilter(request, response);
                return;
            }

            if (loginContext == null) {
                initializeKerberosLogin();
            }

            String path = ((HttpServletRequest) request).getRequestURI();
            if (isExcluded(path)) {
                filterChain.doFilter(request, response);
            } else {
                String clientPrincipal = null;
                try {
                    Cookie[] cookies = httpReq.getCookies();
                    if (cookies == null) {
                        clientPrincipal = getPrincipalFromRequestNew((HttpServletRequest) request);
                    } else {
                        clientPrincipal = null;
                        for (Cookie cookie : cookies) {
                            if ("hadoop.auth".equals(cookie.getName())) {
                                Matcher matcher = HADOOP_AUTH_COOKIE_REGEX.matcher(cookie.getValue());
                                if (matcher.matches()) {
                                    clientPrincipal = matcher.group(1);
                                    break;
                                }
                            }
                        }
                    }
                } catch (Exception ex) {
                    clientPrincipal = null;
                }

                if (clientPrincipal != null) {
                    request.setAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT,
                            new AuthenticationResult(clientPrincipal, authorizerName, null));
                }
            }

            doFilterSuper(request, response, filterChain);
        }

        // Copied from hadoop-auth's AuthenticationFilter, to allow us to change error response handling
        private void doFilterSuper(ServletRequest request, ServletResponse response, FilterChain filterChain)
                throws IOException, ServletException {
            boolean unauthorizedResponse = true;
            int errCode = HttpServletResponse.SC_UNAUTHORIZED;
            AuthenticationException authenticationEx = null;
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            boolean isHttps = "https".equals(httpRequest.getScheme());
            try {
                boolean newToken = false;
                AuthenticationToken token;
                try {
                    token = getToken(httpRequest);
                } catch (AuthenticationException ex) {
                    log.warn("AuthenticationToken ignored: " + ex.getMessage());
                    // will be sent back in a 401 unless filter authenticates
                    authenticationEx = ex;
                    token = null;
                }
                if (getAuthenticationHandler().managementOperation(token, httpRequest, httpResponse)) {
                    if (token == null) {
                        if (log.isDebugEnabled()) {
                            log.debug("Request [{%s}] triggering authentication", getRequestURL(httpRequest));
                        }
                        token = getAuthenticationHandler().authenticate(httpRequest, httpResponse);
                        if (token != null && token.getExpires() != 0
                                && token != AuthenticationToken.ANONYMOUS) {
                            token.setExpires(System.currentTimeMillis() + getValidity() * 1000);
                        }
                        newToken = true;
                    }
                    if (token != null) {
                        unauthorizedResponse = false;
                        if (log.isDebugEnabled()) {
                            log.debug("Request [{%s}] user [{%s}] authenticated", getRequestURL(httpRequest),
                                    token.getUserName());
                        }
                        final AuthenticationToken authToken = token;
                        httpRequest = new HttpServletRequestWrapper(httpRequest) {

                            @Override
                            public String getAuthType() {
                                return authToken.getType();
                            }

                            @Override
                            public String getRemoteUser() {
                                return authToken.getUserName();
                            }

                            @Override
                            public Principal getUserPrincipal() {
                                return (authToken != AuthenticationToken.ANONYMOUS) ? authToken : null;
                            }
                        };
                        if (newToken && !token.isExpired() && token != AuthenticationToken.ANONYMOUS) {
                            String signedToken = mySigner.sign(token.toString());
                            createAuthCookie(httpResponse, signedToken, getCookieDomain(), getCookiePath(),
                                    token.getExpires(), isHttps);
                        }
                        doFilter(filterChain, httpRequest, httpResponse);
                    }
                } else {
                    unauthorizedResponse = false;
                }
            } catch (AuthenticationException ex) {
                // exception from the filter itself is fatal
                errCode = HttpServletResponse.SC_FORBIDDEN;
                authenticationEx = ex;
                if (log.isDebugEnabled()) {
                    log.debug("Authentication exception: " + ex.getMessage(), ex);
                } else {
                    log.warn("Authentication exception: " + ex.getMessage());
                }
            }
            if (unauthorizedResponse) {
                if (!httpResponse.isCommitted()) {
                    createAuthCookie(httpResponse, "", getCookieDomain(), getCookiePath(), 0, isHttps);
                    // If response code is 401. Then WWW-Authenticate Header should be
                    // present.. reset to 403 if not found..
                    if ((errCode == HttpServletResponse.SC_UNAUTHORIZED) && (!httpResponse.containsHeader(
                            org.apache.hadoop.security.authentication.client.KerberosAuthenticator.WWW_AUTHENTICATE))) {
                        errCode = HttpServletResponse.SC_FORBIDDEN;
                    }
                    if (authenticationEx == null) {
                        // Don't send an error response here, unlike the base AuthenticationFilter implementation.
                        // This request did not use Kerberos auth.
                        // Instead, we will send an error response in PreResponseAuthorizationCheckFilter to allow
                        // other Authenticator implementations to check the request.
                        filterChain.doFilter(request, response);
                    } else {
                        // Do send an error response here, we attempted Kerberos authentication and failed.
                        httpResponse.sendError(errCode, authenticationEx.getMessage());
                    }
                }
            }
        }
    };
}

From source file:com.janrain.backplane2.server.Backplane2Controller.java

/**
 * Retrieve a single message from the server.
 *
 * @param request/*from w ww  .j  a v a2 s.  c om*/
 * @param response
 * @return
 */
@RequestMapping(value = "/message/{msg_id:.*}", method = { RequestMethod.GET })
public @ResponseBody Map<String, Object> message(HttpServletRequest request, HttpServletResponse response,
        @PathVariable final String msg_id,
        @RequestParam(value = OAUTH2_ACCESS_TOKEN_PARAM_NAME, required = false) String access_token,
        @RequestParam(required = false) String callback,
        @RequestHeader(value = "Authorization", required = false) String authorizationHeader)
        throws BackplaneServerException, SimpleDBException {

    ServletUtil.checkSecure(request);

    TimerContext context = v2GetSingleMessageTimer.time();

    try {
        new MessageRequest(callback, null, "0"); // validate callback only, if present
    } catch (InvalidRequestException e) {
        return handleInvalidRequest(e, response);
    }

    try {
        Token token = Token.fromRequest(daoFactory, request, access_token, authorizationHeader);
        if (token.getType().isRefresh()) {
            throw new TokenException("Invalid token type: " + token.getType(),
                    HttpServletResponse.SC_FORBIDDEN);
        }

        BackplaneMessage message = daoFactory.getBackplaneMessageDAO().retrieveBackplaneMessage(msg_id, token);

        if (message != null) {
            Map<String, Object> result = message.asFrame(request.getServerName(),
                    token.getType().isPrivileged());
            aniLogGetMessage(request, message, token);
            return result;
        } else {
            return returnMessage(OAuth2.OAUTH2_TOKEN_INVALID_REQUEST, "Message id '" + msg_id + "' not found",
                    HttpServletResponse.SC_NOT_FOUND, response);
        }
    } catch (TokenException te) {
        return handleTokenException(te, response);
    } finally {
        context.stop();
    }
}

From source file:com.zimbra.cs.service.AutoDiscoverServlet.java

private Account authenticate(HttpServletRequest req, HttpServletResponse resp, String responseSchema)
        throws ServletException, IOException {
    //The basic auth header looks like this:
    //Authorization: Basic emltYnJhXFx1c2VyMTp0ZXN0MTIz
    //The base64 encoded credentials can be either <domain>\<user>:<pass> or just <user>:<pass>
    String auth = req.getHeader(BASIC_AUTH_HEADER);
    log.debug("auth header: %s", auth);

    if (auth == null || !auth.toLowerCase().startsWith("basic ")) {
        log.warn("No basic auth header in the request");
        resp.addHeader(WWW_AUTHENTICATE_HEADER, WWW_AUTHENTICATE_VALUE);
        //            resp.addHeader(WWW_AUTHENTICATE_HEADER, NTLM);
        //            resp.addHeader(WWW_AUTHENTICATE_HEADER, NEGOTIATE);
        sendError(resp, HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
        return null;
    }/*from   www .jav a 2s . c om*/

    // 6 comes from "Basic ".length();
    String cred = new String(Base64.decodeBase64(auth.substring(6).getBytes()));

    int bslash = cred.indexOf('\\');

    int colon = cred.indexOf(':');
    if (colon == -1 || colon <= bslash + 1) {
        log.warn("Invalid basic auth credentials");
        sendError(resp, HttpServletResponse.SC_BAD_REQUEST, "Invalid basic auth credentials");
        return null;
    }

    String domain = bslash > 0 ? cred.substring(0, bslash) : "";
    String userPassedIn = cred.substring(bslash + 1, colon);
    String user = cred.substring(bslash + 1, colon);
    String pass = cred.substring(colon + 1);

    log.debug("user=%s, domain=%s", user, domain);
    if (pass.length() == 0) {
        log.warn("Empty password");
        sendError(resp, HttpServletResponse.SC_BAD_REQUEST, "Empty password");
        return null;
    }

    if (domain.length() > 0 && user.indexOf('@') == -1) {
        if (domain.charAt(0) != '@') {
            user += '@';
        }
        user += domain;
    }

    try {
        Provisioning prov = Provisioning.getInstance();
        if (user.indexOf('@') == -1) {
            String defaultDomain = prov.getConfig().getAttr(Provisioning.A_zimbraDefaultDomainName, null);
            if (defaultDomain == null) {
                log.warn("Ldap access error; user=" + user);
                sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "ldap access error");
                return null;
            }
            user = user + "@" + defaultDomain;
        }

        Account account = prov.get(AccountBy.name, user);
        if (account == null) {
            log.warn("User not found; user=" + user);
            resp.addHeader(WWW_AUTHENTICATE_HEADER, WWW_AUTHENTICATE_VALUE);
            sendError(resp, HttpServletResponse.SC_UNAUTHORIZED, "Invalid username or password");
            return null;
        }

        try {
            Map<String, Object> authCtxt = new HashMap<String, Object>();
            authCtxt.put(AuthContext.AC_ORIGINATING_CLIENT_IP, ZimbraServlet.getOrigIp(req));
            authCtxt.put(AuthContext.AC_REMOTE_IP, ZimbraServlet.getClientIp(req));
            authCtxt.put(AuthContext.AC_ACCOUNT_NAME_PASSEDIN, userPassedIn);
            authCtxt.put(AuthContext.AC_USER_AGENT, req.getHeader("User-Agent"));
            prov.authAccount(account, pass, AuthContext.Protocol.zsync, authCtxt);
        } catch (ServiceException x) {
            log.warn("User password mismatch; user=" + user);
            resp.addHeader(WWW_AUTHENTICATE_HEADER, WWW_AUTHENTICATE_VALUE);
            sendError(resp, HttpServletResponse.SC_UNAUTHORIZED, "Invalid username or password");
            return null;
        }

        if (isEwsClient(responseSchema)
                && !account.getBooleanAttr(Provisioning.A_zimbraFeatureEwsEnabled, false)) {
            log.info("User account not enabled for ZimbraEWS; user=" + user);
            sendError(resp, HttpServletResponse.SC_FORBIDDEN, "Account not enabled for ZimbraEWS");
            return null;
        }

        if (!isEwsClient(responseSchema)
                && !account.getBooleanAttr(Provisioning.A_zimbraFeatureMobileSyncEnabled, false)) {
            log.info("User account not enabled for ZimbraSync; user=" + user);
            sendError(resp, HttpServletResponse.SC_FORBIDDEN, "Account not enabled for ZimbraSync");
            return null;
        }

        return account;
    } catch (ServiceException x) {
        log.warn("Account access error; user=" + user, x);
        sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Account access error; user=" + user);
        return null;
    }
}

From source file:org.jetbrains.webdemo.sessions.MyHttpSession.java

private void sendDeleteFileResult() {
    try {/*from  ww  w.j a  va 2  s  .  c  om*/
        sessionInfo.setType(SessionInfo.TypeOfRequest.DELETE_FILE);
        boolean modifiable = Boolean.parseBoolean(request.getParameter("modifiable"));
        if (modifiable) {
            String publicId = request.getParameter("fileId");
            MySqlConnector.getInstance().deleteFile(sessionInfo.getUserInfo(), publicId);
        } else {
            String fileName = request.getParameter("fileName");
            String projectId = request.getParameter("projectId");
            MySqlConnector.getInstance().deleteUnmodifiableFile(sessionInfo.getUserInfo(), fileName, projectId);
        }
        writeResponse(HttpServletResponse.SC_OK);
    } catch (NullPointerException e) {
        writeResponse("Can't get parameters", HttpServletResponse.SC_BAD_REQUEST);
    } catch (DatabaseOperationException e) {
        writeResponse(e.getMessage(), HttpServletResponse.SC_FORBIDDEN);
    }
}

From source file:com.sonicle.webtop.core.app.servlet.ResourceRequest.java

private LookupResult lookupJs(HttpServletRequest request, URL targetUrl, boolean debugVersion) {
    String targetPath = targetUrl.getPath();
    URL fileUrl = null;//from  w  w  w .  j av a2 s .  c o  m

    try {
        if (debugVersion) {
            String dpath = targetPath.substring(0, targetPath.length() - 3) + "-debug.js";
            fileUrl = getResURL(dpath);
            if (fileUrl != null)
                targetPath = dpath;
        }
        if (fileUrl == null) {
            fileUrl = getResURL(targetPath);
        }

        Resource resFile = getFile(WebTopApp.get(request), fileUrl);
        return new StaticFile(fileUrl.toString(), getMimeType(targetPath), ClientCaching.YES, resFile);

    } catch (ForbiddenException ex) {
        return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
    } catch (NotFoundException ex) {
        return new Error(HttpServletResponse.SC_NOT_FOUND, "Not Found");
    } catch (InternalServerException ex) {
        return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
    } catch (ServletException ex) {
        return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
    }
}