Example usage for javax.servlet.http HttpServletResponse SC_UNAUTHORIZED

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

Introduction

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

Prototype

int SC_UNAUTHORIZED

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

Click Source Link

Document

Status code (401) indicating that the request requires HTTP authentication.

Usage

From source file:com.trendmicro.hdfs.webdav.HDFSWebDAVServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (LOG.isDebugEnabled()) {
        LOG.debug(request.getMethod() + " for '" + request.getRequestURI() + "' from " + request.getRemoteUser()
                + " at " + request.getRemoteAddr());
    }/*from www .j a va 2s  .  c  o m*/
    try {
        super.service(request, response);
    } catch (Exception e) {
        if (e instanceof AccessControlException || e.getCause() instanceof AccessControlException) {
            LOG.info("Insufficient permissions for request for '" + request.getRequestURI() + "' from "
                    + request.getRemoteUser() + " at " + request.getRemoteAddr());
            if (request.getMethod().equalsIgnoreCase("GET")) {
                // Provide a plain 401 response for GETs
                new WebdavResponseImpl(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
            } else {
                // Otherwise send a multistatus response
                MultiStatus ms = new MultiStatus();
                ms.addResponse(new MultiStatusResponse(request.getRequestURL().toString(), 401,
                        "You do not have permission to access this resource."));
                new WebdavResponseImpl(response).sendMultiStatus(ms);
            }
        } else {
            LOG.warn("Exception processing request for '" + request.getRequestURI() + "' from "
                    + request.getRemoteUser() + " at " + request.getRemoteAddr() + " authType "
                    + request.getAuthType(), e);
            new WebdavResponseImpl(response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}

From source file:airport.web.controller.ServicesController.java

@RequestMapping(value = "/service/chat/add", produces = "application/json")
public void serviceChatAdd(HttpServletRequest request, HttpServletResponse response) {
    HttpSession httpSession = request.getSession();
    User user = (User) httpSession.getAttribute("user");

    if (serviceUsers.checkUserOnline(user)) {
        String text = request.getParameter("charText");

        serviceChat.addMessage(user, text);

        if (LOG.isInfoEnabled()) {
            LOG.info("user add message. Session id : " + httpSession.getId() + ". User : " + user
                    + ". URL : /service/chat/add");
        }//from   www  .j ava 2  s. co  m
    } else {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        if (LOG.isInfoEnabled()) {
            LOG.info("the user isn't authorized. Session id : " + httpSession.getId()
                    + ". URL : /service/chat/add");
        }
    }
}

From source file:com.google.gsa.valve.modules.httpbasic.HTTPBasicAuthorizationProcess.java

/**
 * /* w  w w . ja  v a  2s.  co m*/
 * This is the main method that does the authorization and should be 
 * invoked by the classes that would like to check if the user is 
 * priviledged to access to the document (url) against the HTTP Basic 
 * protected source that serves it.
 * <p>
 * The Basic credential is read from the cookie created during the 
 * authentication process. If that cookie does not exist, the process returns 
 * a 401 (Unauthorized) error code.
 * <p>
 * If it is a HEAD request, it means it's not necessary to get the content, 
 * and that's why this process only cares about the HTTP result code. That 
 * result code is returned back to the caller, and if the request is not a 
 * HEAD (i.e. usually GET), the content is sent as well if the overall 
 * result is OK.
 * 
 * @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 {

    logger.debug("HTTP Basic Authorization");

    String loginUrl = null;

    loginUrl = valveConf.getLoginUrl();

    //Get Max connections
    maxConnectionsPerHost = new Integer(valveConf.getMaxConnectionsPerHost()).intValue();
    maxTotalConnections = (new Integer(valveConf.getMaxTotalConnections())).intValue();

    logger.debug("HttpBasic AuthZ maxConnectionsPerHost: " + maxConnectionsPerHost);
    logger.debug("HttpBasic AuthZ maxTotalConnections: " + maxTotalConnections);

    // Protection
    if (webProcessor == null) {
        // Instantiate Web processor
        if ((maxConnectionsPerHost != -1) && (maxTotalConnections != -1)) {
            webProcessor = new WebProcessor(maxConnectionsPerHost, maxTotalConnections);
        } else {
            webProcessor = new WebProcessor();
        }
    }

    //protection
    authHeader = null;
    headers = null;

    //Get the http AuthZ header
    Cookie[] requestCookies = null;

    //add support to authCookies
    requestCookies = authCookies;

    // Protection
    logger.debug("Checking request cookies");
    if (requestCookies != null) {
        // Check if the authentication process already happened by looking at the existing cookie
        // The gsa_basic_auth cookie contains the HTTP Basic AuthZ header
        logger.debug("Number of cookies: " + requestCookies.length);
        for (int i = 0; i < requestCookies.length; i++) {
            // Check cookie name
            logger.debug("request cookie: " + requestCookies[i].getName() + ":" + requestCookies[i].getValue());
            if ((requestCookies[i].getName()).equals(BASIC_COOKIE)) {
                if (requestCookies[i].getValue() != null) {
                    logger.debug(BASIC_COOKIE + ": " + requestCookies[i].getValue());
                    String basicCookie = null;
                    try {
                        basicCookie = URLDecoder.decode(requestCookies[i].getValue(), encoder);
                        if ((basicCookie != null) && (!basicCookie.equals(""))) {
                            authHeader = new Header("Authorization", setBasicAuthNChain(basicCookie));
                        }
                    } catch (Exception ex) {
                        logger.error("Error when getting cookie value: " + ex.getMessage(), ex);
                    }

                }
            }
        }
    }

    //
    // Launch the authorization process
    //

    // Initialize status code
    int statusCode = HttpServletResponse.SC_UNAUTHORIZED;

    if (authHeader == null) {

        // no authZ header, can't auth this URL
        logger.debug("No authZ header");
        return statusCode;

    } else {

        //is a Head request?
        boolean isHead = AuthorizationUtils.isHead(request, valveConf);
        logger.debug("isHead?: " + isHead);
        setHeaders();

        // Protection
        if (webProcessor != null) {

            // Protection
            try {

                // Process authz request
                String requestType = RequestType.GET_REQUEST;

                if (isHead) {
                    requestType = RequestType.HEAD_REQUEST;
                }

                method = webProcessor.sendRequest(null, requestType, headers, null, url);

                // Protection
                if (method != null) {
                    // Cache status code
                    statusCode = method.getStatusCode();
                    logger.debug("statusCode is.... " + statusCode);

                    if (statusCode == HttpServletResponse.SC_OK) {
                        //check if it's a Head request
                        if (!isHead) {
                            //Process content
                            HTTPAuthZProcessor.processResponse(response, method, url, loginUrl);
                        }
                    } else {

                        logger.debug("not AuthZ : should return response Code");
                    }
                }

                // Garbagge collect
                if (method != null) {
                    method.releaseConnection();
                    method = null;
                }

            } catch (Exception e) {

                // Log error
                logger.error("authorization failure: " + e.getMessage(), e);
                statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;

                // Garbagge collect                                   
                method.releaseConnection();
                method = null;
            }

        }

        //
        // End of the authorization process
        //

        // Return status code
        return statusCode;
    }

}

From source file:edu.umd.cs.submitServer.servlets.ReportTestOutcomes.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // will be set by MultipartRequestFilter
    MultipartRequest multipartRequest = (MultipartRequest) request.getAttribute(MULTIPART_REQUEST);

    Timestamp now = new Timestamp(System.currentTimeMillis());

    // Insert test outcomes into database,
    // create new TestRun
    // and update submission as having been tested.
    Connection conn = null;// www  .  ja  va2s.  c om
    boolean transactionSuccess = false;
    try {
        // Get submission pk and the submission
        @Submission.PK
        int submissionPK = Submission.asPK(multipartRequest.getIntParameter("submissionPK"));

        String courses = multipartRequest.getStringParameter("courses");

        // Get the testSetupPK
        int testSetupPK = multipartRequest.getIntParameter("testSetupPK");
        boolean newTestSetup = multipartRequest.getBooleanParameter("newTestSetup");
        boolean isBackgroundRetest = multipartRequest.getBooleanParameter("isBackgroundRetest");
        String load = multipartRequest.getOptionalStringParameter("load");

        if (load == null)
            load = "unknown";
        String kindString = multipartRequest.getOptionalStringParameter("kind");
        Kind kind = Kind.UNKNOWN;
        if (kindString != null) {
            try {
                kind = Kind.valueOf(kindString);
            } catch (RuntimeException e) {
                // ignore
            }

        }

        String remoteHost = SubmitServerFilter.getRemoteHost(request);
        // Get test machine (if specified)
        String testMachine = multipartRequest.getOptionalStringParameter("hostname");
        if (testMachine == null)
            testMachine = multipartRequest.getOptionalStringParameter("testMachine");
        if (testMachine == null)
            testMachine = "unknown";

        CodeMetrics codeMetrics = getCodeMetrics(multipartRequest);
        int testDurationsMillis = multipartRequest.getIntegerParameter("testDurationsMillis", 0);

        // Read into TestOutcomeCollection in memory
        TestOutcomeCollection testOutcomeCollection = TestOutcomeCollection
                .deserialize(getfileItemDataAndDelete(multipartRequest));

        logHotspotErrors(submissionPK, testSetupPK, testMachine, testOutcomeCollection);

        conn = getConnection();

        Submission submission = Submission.lookupBySubmissionPK(submissionPK, conn);

        if (submission == null) {
            throw new ServletException(
                    "submissionPK " + submissionPK + " does not refer to a submission in the database");
        }

        StudentRegistration studentRegistration = StudentRegistration
                .lookupByStudentRegistrationPK(submission.getStudentRegistrationPK(), conn);
        @Student.PK
        Integer studentPK = studentRegistration.getStudentPK();
        Project project = Project.getByProjectPK(submission.getProjectPK(), conn);

        TestSetup testSetup = TestSetup.lookupByTestSetupPK(testSetupPK, conn);
        Integer canonicalTestRunPK = testSetup.getTestRunPK();
        if (newTestSetup && (testSetup.getStatus() == TestSetup.Status.TESTED
                || testSetup.getStatus() == TestSetup.Status.ACTIVE)) {
            newTestSetup = false;
        }
        BuildServer.insertOrUpdateSuccess(conn, testMachine, remoteHost, now, load, submission);

        // Validate buildserver
        Collection<Integer> allowedCourses = RequestSubmission.getCourses(conn, courses);

        if (allowedCourses.isEmpty()) {
            ServerError.insert(conn, ServerError.Kind.BAD_AUTHENTICATION, studentPK, studentPK,
                    project.getCoursePK(), project.getProjectPK(), submission.getSubmissionPK(), "",
                    "Build server " + testMachine
                            + " reporting outcome but does not provide any valid credentials",
                    "", this.getClass().getSimpleName(), "", "", remoteHost, "", "", null);
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Not authorized");
            return;
        }

        if (!allowedCourses.contains(project.getCoursePK())) {
            ServerError.insert(conn, ServerError.Kind.BAD_AUTHENTICATION, studentPK, studentPK,
                    project.getCoursePK(), project.getProjectPK(), submission.getSubmissionPK(), "",
                    "Build server " + testMachine
                            + " reporting outcome for course it is not authorized to do so",
                    "", this.getClass().getSimpleName(), "", "", remoteHost, "", "", null);
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Not authorized");
            return;
        }

        TestRun canonicalTestRun = TestRun.lookupByTestRunPK(canonicalTestRunPK, conn);
        if (!newTestSetup) {
            if (canonicalTestRun == null || canonicalTestRun.getTestSetupPK() != testSetupPK) {
                ServerError.insert(conn, ServerError.Kind.UNKNOWN, studentPK, studentPK, project.getCoursePK(),
                        project.getProjectPK(), submission.getSubmissionPK(), "",
                        "Discarding stale build server result", "", this.getClass().getSimpleName(), "", "",
                        remoteHost, "", "", null);
                response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "not current test setup");
                return;
            }

            // Set point totals

            TestOutcomeCollection canonicalTestOutcomeCollection = TestOutcomeCollection
                    .lookupByTestRunPK(canonicalTestRun.getTestRunPK(), conn);
            Map<String, TestOutcome> canonicalTestOutcomeMap = new HashMap<String, TestOutcome>();
            for (TestOutcome testOutcome : canonicalTestOutcomeCollection.getAllOutcomes()) {
                if (testOutcome.isCardinalTestType())
                    canonicalTestOutcomeMap.put(testOutcome.getTestName(), testOutcome);
            }

            for (TestOutcome testOutcome : testOutcomeCollection.getAllOutcomes())
                if (testOutcome.isCardinalTestType()
                        && !testOutcome.getOutcome().equals(TestOutcome.COULD_NOT_RUN)) {
                    TestOutcome canonicalTestOutcome = canonicalTestOutcomeMap.get(testOutcome.getTestName());
                    if (canonicalTestOutcome == null
                            || !canonicalTestOutcome.getTestType().equals(testOutcome.getTestType())) {
                        String message = "Did not find matching canonical test outcome for "
                                + testOutcome.getTestName() + " with outcome " + testOutcome.getOutcome();
                        ServerError.insert(conn, ServerError.Kind.UNKNOWN, studentPK, studentPK,
                                project.getCoursePK(), project.getProjectPK(), submission.getSubmissionPK(), "",
                                message, "", this.getClass().getSimpleName(), "", "", remoteHost, "", "", null);
                        response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, message);
                        return;
                    }

                    testOutcome.setPointValue(canonicalTestOutcome.getPointValue());

                }
        } else {

            // new test setup

            // set all point values to 1
            for (TestOutcome testOutcome : testOutcomeCollection) {
                testOutcome.setPointValue(1);
            }
        }

        getSubmitServerServletLog().info("Reporting test outcome for submissionPK = " + submissionPK
                + ", testSetupPK = " + testSetupPK + " performed by " + testMachine + ", kind = " + kind);

        // Background Retests:
        // If this was a background re-test, then we need to take special
        // steps.
        // This was a background-retest if:
        // 1) The BuildServer says that this was a background retest
        // 2) or the status has been left as "complete" or has been
        // explicitly marked "background"
        if (isBackgroundRetest
                || !newTestSetup && submission.getBuildStatus().equals(Submission.BuildStatus.COMPLETE)) {

            // Look up current testOutcomeCollection
            TestOutcomeCollection currentTestOutcomeCollection = TestOutcomeCollection
                    .lookupByTestRunPK(submission.getCurrentTestRunPK(), conn);

            // Look up the testRun for the current TestOutcomeCollection
            TestRun currentTestRun = TestRun.lookupByTestRunPK(submission.getCurrentTestRunPK(), conn);
            if (currentTestRun == null)
                getSubmitServerServletLog().warn("Unable to find test run " + submission.getCurrentTestRunPK());
            if (currentTestRun == null || currentTestRun.getTestSetupPK() != testSetupPK) {
                // Retest was against a different jarfile than the current
                // one;
                // for now just ignore this run.

                return;
            }

            // Compare the cardinal test outcomes from the two
            // outcomeCollections
            String differences = compareCardinalOutcomes(currentTestOutcomeCollection, testOutcomeCollection,
                    submissionPK, testSetupPK, testMachine);

            if (differences == null) {
                // If the results are the same, great! We have more
                // confidence that this result is correct.
                submission.incrementNumSuccessfulBackgroundRetests();

                getSuccessfulBackgroundRetestLog().info("Corroborating run for submissionPK = " + submissionPK
                        + ", testSetupPK = " + testSetupPK + " performed by " + testMachine);
            } else if (differences.equals("skip")) {
                // There may have been differences but we don't care
                // We don't re-test "could_not_run" results
                return;
            } else {
                // If the results differ, log which test cases were
                // different
                submission.incrementNumFailedBackgroundRetests();
                // TODO: RSS feed
                getFailedBackgroundRetestLog().warn(differences);
                // XXX Should I insert differing outcomes into the database
                // as re-tests?
                if (currentTestOutcomeCollection.getValuePassedOverall() < testOutcomeCollection
                        .getValuePassedOverall())
                    isBackgroundRetest = false;

            }
            submission.update(conn);

            // If there were no differences, commit what we've done and
            // exit.
            if (differences == null)
                return;
        } // isBackgroundRetest

        conn = switchToTransaction(conn);

        // * Create new TestRun row
        // * increment numTestOutcomes in submissions table
        // * set currentTestRunPK in submissions table
        // * set testRunPK in all the testOutcomes
        // * write the testoutcomes to the disk

        // Create new TestRun row.
        TestRun testRun = createTestRun(submissionPK, testSetupPK, testMachine, testOutcomeCollection,
                codeMetrics, now, testDurationsMillis);

        // perform insert
        testRun.insert(conn);
        BuildServer.updateLastTestRun(conn, testMachine, testRun);

        // Insert a new codeMetrics row if we have codeMetrics data to
        // insert
        // codeMetrics data is keyed to the testRunPK
        if (codeMetrics.getCodeSegmentSize() > 0) {
            codeMetrics.setTestRunPK(testRun.getTestRunPK());
            codeMetrics.insert(conn);
        }

        // update the testRunPK of the testOutcomes we've been sent from the
        // BuildServer
        // with the testRunPK of the row we just inserted
        testOutcomeCollection.updateTestRunPK(testRun.getTestRunPK());

        // increment the number of test outcomes
        submission.setNumTestRuns(submission.getNumTestRuns() + 1);

        // Next, insert the test outcomes
        testOutcomeCollection.insert(conn);

        // if this was a new project jarfile being tested against the
        // canonical account
        if (newTestSetup) {
            getSubmitServerServletLog().info("Ran new test setup, submissionPK = " + submissionPK
                    + ", testSetupPK = " + testSetupPK + " performed by " + testMachine + ", kind = " + kind);

            // lookup the pending project

            testSetup.setValueTotalTests(testOutcomeCollection.getValuePassedOverall());
            testSetup.setValuePublicTests(testOutcomeCollection.getValuePublicTests());
            testSetup.setValueReleaseTests(testOutcomeCollection.getValueReleaseTests());
            testSetup.setValueSecretTests(testOutcomeCollection.getValueSecretTests());

            testSetup.setTestRunPK(testRun.getTestRunPK());

            if (!testOutcomeCollection.isCompileSuccessful() || testOutcomeCollection.getNumFailedOverall() > 0
                    || testOutcomeCollection.getCouldNotRunAnyCardinalTests()) {
                // If any tests have failed, then set status to failed
                testSetup.setStatus(TestSetup.Status.FAILED);
            } else {
                testSetup.setStatus(TestSetup.Status.TESTED);
            }
            getSubmitServerServletLog().info("Ran new test setup, submissionPK = " + submissionPK
                    + ", testSetupPK = " + testSetupPK + " performed by " + testMachine + ", kind = " + kind
                    + ", status = " + testSetup.getStatus());

            // update pending testSetup to reflect the changes just
            // made
            testSetup.update(conn);
        }

        // Only change information about the current test_run if this
        // run used the most recent testSetup
        if (!isBackgroundRetest && (newTestSetup || testRun.getTestSetupPK() == project.getTestSetupPK())) {
            // update the pass/fail/warning stats
            submission.setCurrentTestRunPK(testRun.getTestRunPK());

            // Ensure that submission is not release eligible if the
            // student_submit_status.can_release_test is false
            StudentSubmitStatus submitStatus = StudentSubmitStatus.lookupByStudentRegistrationPKAndProjectPK(
                    submission.getStudentRegistrationPK(), submission.getProjectPK(), conn);
            boolean canReleaseTest = (submitStatus == null) || submitStatus.getCanReleaseTest();
            submission.setReleaseEligible(testOutcomeCollection.isReleaseEligible() && canReleaseTest);

            // if project's release policy is anytime, then make it release
            // eligible
            if (Project.ANYTIME.equals(project.getReleasePolicy()))
                submission.setReleaseEligible(canReleaseTest);

            submission.setValuePassedOverall(testOutcomeCollection.getValuePassedOverall());
            submission.setCompileSuccessful(testOutcomeCollection.isCompileSuccessful());
            submission.setValuePublicTestsPassed(testOutcomeCollection.getValuePublicTestsPassed());
            submission.setValueReleaseTestsPassed(testOutcomeCollection.getValueReleaseTestsPassed());
            submission.setValueSecretTestsPassed(testOutcomeCollection.getValueSecretTestsPassed());
            submission.setNumFindBugsWarnings(testOutcomeCollection.getNumFindBugsWarnings());

            // If we're re-setting the currentTestRunPK, then find any
            // existing
            // backgroundRetests and clear them. Background re-tests are
            // always compared
            // to the current set of testOutcomes.
            submission.setNumFailedBackgroundRetests(0);
            submission.setNumSuccessfulBackgroundRetests(0);
            submission.setNumPendingBuildRequests(0);

        }
        // perform update
        // Update the status of the submission
        submission.setBuildStatus(Submission.BuildStatus.COMPLETE);
        submission.update(conn);
        getSubmitServerServletLog().info("Completed testing submissionPK = " + submissionPK + ", testSetupPK = "
                + testSetupPK + " performed by " + testMachine + ", kind = " + kind + ", status = "
                + testSetup.getStatus());

        conn.commit();
        transactionSuccess = true;
    } catch (InvalidRequiredParameterException e) {
        throw new ServletException(e);
    } catch (SQLException e) {
        throw new ServletException(e);
    } finally {
        rollbackIfUnsuccessfulAndAlwaysReleaseConnection(transactionSuccess, request, conn);
    }
}

From source file:com.hortonworks.registries.auth.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");
    Assert.assertNull(handler.authenticate(request, response));
    Mockito.verify(response).setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE);
    Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}

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

@Override
public AuthenticationToken authenticate(HttpServletRequest request, final HttpServletResponse response)
        throws IOException, AuthenticationException {
    AuthenticationToken token = null;//from  w w  w  .  j  av  a2 s  .co m
    String authorization = request
            .getHeader(org.apache.hadoop.security.authentication.client.KerberosAuthenticator.AUTHORIZATION);

    if (authorization == null || !authorization
            .startsWith(org.apache.hadoop.security.authentication.client.KerberosAuthenticator.NEGOTIATE)) {
        return null;
    } else {
        authorization = authorization.substring(
                org.apache.hadoop.security.authentication.client.KerberosAuthenticator.NEGOTIATE.length())
                .trim();
        final Base64 base64 = new Base64(0);
        final byte[] clientToken = base64.decode(authorization);
        final String serverName = request.getServerName();
        try {
            token = Subject.doAs(serverSubject, new PrivilegedExceptionAction<AuthenticationToken>() {

                @Override
                public AuthenticationToken run() throws Exception {
                    AuthenticationToken token = null;
                    GSSContext gssContext = null;
                    GSSCredential gssCreds = null;
                    try {
                        gssCreds = gssManager.createCredential(
                                gssManager.createName(KerberosUtil.getServicePrincipal("HTTP", serverName),
                                        KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL")),
                                GSSCredential.INDEFINITE_LIFETIME,
                                new Oid[] { KerberosUtil.getOidInstance("GSS_SPNEGO_MECH_OID"),
                                        KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID") },
                                GSSCredential.ACCEPT_ONLY);
                        gssContext = gssManager.createContext(gssCreds);
                        byte[] serverToken = gssContext.acceptSecContext(clientToken, 0, clientToken.length);
                        if (serverToken != null && serverToken.length > 0) {
                            String authenticate = base64.encodeToString(serverToken);
                            response.setHeader(
                                    org.apache.hadoop.security.authentication.client.KerberosAuthenticator.WWW_AUTHENTICATE,
                                    org.apache.hadoop.security.authentication.client.KerberosAuthenticator.NEGOTIATE
                                            + " " + authenticate);
                        }
                        if (!gssContext.isEstablished()) {
                            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                            log.trace("SPNEGO in progress");
                        } else {
                            String clientPrincipal = gssContext.getSrcName().toString();
                            KerberosName kerberosName = new KerberosName(clientPrincipal);
                            String userName = kerberosName.getShortName();
                            token = new AuthenticationToken(userName, clientPrincipal, getType());
                            response.setStatus(HttpServletResponse.SC_OK);
                            log.trace("SPNEGO completed for principal [%s]", clientPrincipal);
                        }
                    } finally {
                        if (gssContext != null) {
                            gssContext.dispose();
                        }
                        if (gssCreds != null) {
                            gssCreds.dispose();
                        }
                    }
                    return token;
                }
            });
        } catch (PrivilegedActionException ex) {
            if (ex.getException() instanceof IOException) {
                throw (IOException) ex.getException();
            } else {
                throw new AuthenticationException(ex.getException());
            }
        }
    }
    return token;
}

From source file:com.erudika.para.security.RestAuthFilter.java

private boolean appAuthRequestHandler(String appid, BufferedRequestWrapper request,
        HttpServletResponse response) {/*from  www .j a va 2s  .c  o m*/
    String date = RestUtils.extractDate(request);
    Date d = Signer.parseAWSDate(date);
    String reqUri = request.getRequestURI();
    String method = request.getMethod();
    boolean requestExpired = (d != null)
            && (System.currentTimeMillis() > (d.getTime() + (Config.REQUEST_EXPIRES_AFTER_SEC * 1000)));

    if (!StringUtils.isBlank(appid)) {
        if (!StringUtils.isBlank(date)) {
            if (!requestExpired) {
                App app = Para.getDAO().read(App.id(appid));

                if (app != null) {
                    if (app.getActive()) {
                        if (!(app.getReadOnly() && isWriteRequest(request))) {
                            if (signer.isValidSignature(request, app.getSecret())) {
                                SecurityContextHolder.getContext()
                                        .setAuthentication(new AppAuthentication(app));
                            } else {
                                RestUtils.returnStatusResponse(response, HttpServletResponse.SC_FORBIDDEN,
                                        "Request signature is invalid.");
                                return false;
                            }
                        } else {
                            RestUtils.returnStatusResponse(response, HttpServletResponse.SC_FORBIDDEN,
                                    Utils.formatMessage("App is in read-only mode. [{0}]", appid));
                            return false;
                        }
                    } else {
                        RestUtils.returnStatusResponse(response, HttpServletResponse.SC_FORBIDDEN,
                                Utils.formatMessage("App not active. [{0}]", appid));
                        return false;
                    }
                } else {
                    RestUtils.returnStatusResponse(response, HttpServletResponse.SC_NOT_FOUND,
                            Utils.formatMessage("App not found. [{0}]", appid));
                    return false;
                }
            } else {
                RestUtils.returnStatusResponse(response, HttpServletResponse.SC_BAD_REQUEST,
                        "Request has expired.");
                return false;
            }
        } else {
            RestUtils.returnStatusResponse(response, HttpServletResponse.SC_BAD_REQUEST,
                    "'X-Amz-Date' header or parameter is not set!");
            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:eu.trentorise.smartcampus.communicatorservice.controller.NotificationController.java

@RequestMapping(method = RequestMethod.DELETE, value = "user/notification/{id}")
public @ResponseBody boolean deleteByUser(HttpServletRequest request, HttpServletResponse response,
        HttpSession session, @PathVariable("id") String id)
        throws DataException, IOException, NotFoundException, SmartCampusException {

    String userId = getUserId();/* ww w  .  j  a  va  2  s .c  om*/
    if (userId == null) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }

    return notificationManager.deleteByUser(id, userId);
}

From source file:com.mercer.cpsg.swarm.oidc.deployment.OIDCAuthenticationMechanism.java

@Override
public ChallengeResult sendChallenge(HttpServerExchange exchange, SecurityContext securityContext) {
    OIDCContext oidcContext = exchange.getAttachment(OIDCContext.ATTACHMENT_KEY);
    // NOT_AUTHENTICATED and NOT_ATTEMPTED always send challenges
    if (oidcContext.isError()) {
        return new ChallengeResult(false, HttpServletResponse.SC_UNAUTHORIZED);
    }//from  ww w .  j  ava 2 s  .  co m

    String redirectURL = buildAuthorizationURL(exchange);
    LOG.fine("Challenge redirect:" + redirectURL);
    exchange.getResponseHeaders().put(Headers.LOCATION, redirectURL);
    return new ChallengeResult(true, HttpServletResponse.SC_FOUND);
}

From source file:com.erudika.para.security.JWTRestfulAuthFilter.java

private boolean refreshTokenHandler(HttpServletRequest request, HttpServletResponse response) {
    JWTAuthentication jwtAuth = getJWTfromRequest(request);
    if (jwtAuth != null) {
        try {/*from w w  w  .j a va  2 s. c o  m*/
            User user = SecurityUtils.getAuthenticatedUser(jwtAuth);
            if (user != null) {
                // check and reissue token
                jwtAuth = (JWTAuthentication) authenticationManager.authenticate(jwtAuth);
                if (jwtAuth != null && jwtAuth.getApp() != null) {
                    SignedJWT newToken = SecurityUtils.generateJWToken(user, jwtAuth.getApp());
                    if (newToken != null) {
                        succesHandler(response, user, newToken);
                        return true;
                    }
                }
            }
        } catch (Exception ex) {
            logger.debug(ex);
        }
    }
    response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Bearer error=\"invalid_token\"");
    RestUtils.returnStatusResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "User must reauthenticate.");
    return false;
}