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:org.openmrs.module.clinicalsummary.web.controller.service.PatientSearchController.java

/**
 * @param term/*from  w ww . ja va 2s. co m*/
 * @param response
 * @should should return patients with name search term
 * @should should return patients with identifier search term
 * @should should return empty list when no patient match search term
 */
@RequestMapping(method = RequestMethod.GET)
public void searchPatient(@RequestParam(required = false, value = "username") String username,
        @RequestParam(required = false, value = "password") String password,
        @RequestParam(required = true, value = "term") String term, HttpServletResponse response)
        throws IOException {
    try {
        if (!Context.isAuthenticated())
            Context.authenticate(username, password);

        // search for patients with the matching search term
        List<Patient> patients = Context.getPatientService().getPatients(term);
        // serialize the the search result
        XStream xStream = new XStream();
        xStream.alias("results", List.class);
        xStream.alias("patient", Patient.class);
        xStream.registerConverter(new PatientConverter());
        xStream.registerConverter(new PatientIdentifierConverter());
        xStream.registerConverter(new PersonNameConverter());
        xStream.toXML(patients, response.getOutputStream());
    } catch (ContextAuthenticationException e) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
}

From source file:org.jboss.as.test.integration.web.security.servlet.methods.DenyUncoveredHttpMethodsTestCase.java

@Test
public void testHeadMethod() throws Exception {
    HttpHead httpHead = new HttpHead(getURL());
    HttpResponse response = getHttpResponse(httpHead);

    assertThat(statusCodeOf(response), is(HttpServletResponse.SC_UNAUTHORIZED));
}

From source file:org.openmrs.module.clinicalsummary.web.controller.service.PatientSummaryController.java

/**
 * @param patientId//from   w ww  .ja  va  2 s .co m
 * @param summaryId
 * @param response
 * @should return summary data for patient and summary
 * @should return empty data when no index found for the patient and summary
 */
@RequestMapping(method = RequestMethod.GET)
public void searchSummary(@RequestParam(required = false, value = "username") String username,
        @RequestParam(required = false, value = "password") String password,
        @RequestParam(required = false, value = "patientId") String patientId,
        @RequestParam(required = false, value = "summaryId") Integer summaryId, HttpServletResponse response)
        throws IOException {

    try {
        if (!Context.isAuthenticated())
            Context.authenticate(username, password);

        Summary summary = Context.getService(SummaryService.class).getSummary(summaryId);

        File outputDirectory = EvaluatorUtils.getOutputDirectory(summary);
        File summaryFile = new File(outputDirectory,
                StringUtils.join(Arrays.asList(patientId, Evaluator.FILE_TYPE_XML), "."));
        if (summaryFile.exists()) {
            FileInputStream inputStream = new FileInputStream(summaryFile);
            FileCopyUtils.copy(inputStream, response.getOutputStream());
        }
    } catch (ContextAuthenticationException e) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
}

From source file:org.cloudfoundry.identity.uaa.error.JsonAwareAuthenticationEntryPointTests.java

@Test
public void testCommenceWithHtmlAndJsonAccept() throws Exception {
    request.addHeader("Accept", String.format("%s,%s", MediaType.TEXT_HTML_VALUE, MediaType.APPLICATION_JSON));
    entryPoint.commence(request, response, new BadCredentialsException("Bad"));
    assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
    assertEquals(null, response.getErrorMessage());
}

From source file:com.cloudera.alfredo.server.TestKerberosAuthenticationHandler.java

public void testRequestWithoutAuthorization() throws Exception {
    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

    assertNull(handler.authenticate(request, response));
    Mockito.verify(response).setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE);
    Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}

From source file:org.sakaiproject.tool.section.filter.AuthnFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpSession session = ((HttpServletRequest) request).getSession(true);
    Authn authnService = (Authn) WebApplicationContextUtils
            .getWebApplicationContext(session.getServletContext()).getBean(authnBean);
    String userUid = null;//w  w w  . j a v  a2 s .  c o  m
    try {
        userUid = authnService.getUserUid(request);
    } catch (Exception e) {
        if (log.isDebugEnabled())
            log.debug("Could not get user uuid from authn service.");
    }
    if (log.isDebugEnabled())
        log.debug("userUid=" + userUid);
    if (userUid == null) {
        if (authnRedirect != null) {
            if (authnRedirect.equals(((HttpServletRequest) request).getRequestURI())) {
                // Don't redirect to the same spot.
                chain.doFilter(request, response);
            } else {
                ((HttpServletResponse) response).sendRedirect(authnRedirect);
            }
        } else {
            ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
    } else {
        chain.doFilter(request, response);
    }
}

From source file:de.undercouch.gradle.tasks.download.AuthenticationTest.java

@Override
protected Handler[] makeHandlers() throws IOException {
    ContextHandler authenticationHandler = new ContextHandler("/" + AUTHENTICATE) {
        @Override/*from ww  w  .  ja  va  2 s .com*/
        public void handle(String target, HttpServletRequest request, HttpServletResponse response,
                int dispatch) throws IOException, ServletException {
            String ahdr = request.getHeader("Authorization");
            if (ahdr == null) {
                if (!basic) {
                    response.setHeader("WWW-Authenticate",
                            "Digest realm=\"" + REALM + "\"," + "nonce=\"" + NONCE + "\"");
                }
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "No authorization header given");
                return;
            }

            if (basic) {
                checkBasic(ahdr, response);
            } else {
                checkDigest(ahdr, response);
            }
        }

        private void checkBasic(String ahdr, HttpServletResponse response) throws IOException {
            if (!ahdr.startsWith("Basic ")) {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                        "Authorization header does not start with 'Basic '");
                return;
            }

            ahdr = ahdr.substring(6);
            ahdr = new String(Base64.decodeBase64(ahdr));
            String[] userAndPass = ahdr.split(":");
            if (!USERNAME.equals(userAndPass[0]) || !PASSWORD.equals(userAndPass[1])) {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Wrong credentials");
                return;
            }

            response.setStatus(200);
            PrintWriter rw = response.getWriter();
            rw.write("auth: " + ahdr);
            rw.close();
        }

        private void checkDigest(String ahdr, HttpServletResponse response) throws IOException {
            if (!ahdr.startsWith("Digest ")) {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                        "Authorization header does not start with 'Digest '");
                return;
            }

            String expectedResponse = USERNAME + ":" + REALM + ":" + PASSWORD;
            expectedResponse = DigestUtils.md5Hex(expectedResponse);

            ahdr = ahdr.substring(7);
            String[] parts = ahdr.split(",");
            for (String p : parts) {
                if (p.startsWith("username") && !p.equals("username=\"" + USERNAME + "\"")) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Wrong username");
                    return;
                } else if (p.startsWith("nonce") && !p.equals("nonce=\"" + NONCE + "\"")) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Wrong nonce");
                    return;
                } else if (p.startsWith("realm") && !p.equals("realm=\"" + REALM + "\"")) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Wrong realm");
                    return;
                } else if (p.startsWith("response") && !p.equals("response=\"" + expectedResponse + "\"")) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Wrong response");
                    return;
                }
            }

            response.setStatus(200);
            PrintWriter rw = response.getWriter();
            rw.close();
        }
    };
    return new Handler[] { authenticationHandler };
}

From source file:cz.muni.fi.dndtroopsweb.security.ProtectFilter.java

private void response401(HttpServletResponse response) throws IOException {
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    response.setHeader("WWW-Authenticate", "Basic realm=\"type name and password\"");
    response.getWriter()//from   www.ja v a 2s. co m
            .println("<html><body><h1>401 Unauthorized Access</h1> Destruction in 5..4..3..</body></html>");
}

From source file:org.codehaus.groovy.grails.plugins.springsecurity.GrailsNtlmProcessingFilterEntryPoint.java

/**
 * {@inheritDoc}/*from w ww  .  j  av  a 2 s .  c  o  m*/
 * @see org.springframework.security.ui.ntlm.NtlmProcessingFilterEntryPoint#commence(
 *    javax.servlet.ServletRequest, javax.servlet.ServletResponse,
 *    org.springframework.security.AuthenticationException)
 */
@Override
public void commence(final ServletRequest req, final ServletResponse res,
        final AuthenticationException authException) throws IOException, ServletException {

    // start authentication, if necessary and forceIdentification in NtlmProcessingFilter is false
    if (!(authException instanceof NtlmBaseException || authException instanceof BadCredentialsException)) {

        HttpServletRequest request = (HttpServletRequest) req;
        request.getSession().setAttribute(STATE_ATTR, BEGIN);

        HttpServletResponse response = (HttpServletResponse) res;

        response.setHeader("WWW-Authenticate", new NtlmBeginHandshakeException().getMessage());
        response.setHeader("Connection", "Keep-Alive");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentLength(0);
        response.flushBuffer();
    } else {
        super.commence(req, res, authException);
    }
}

From source file:com.stormpath.spring.config.StormpathAuthenticationEntryPoint.java

@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {
    log.debug("Pre-authenticated entry point called. Rejecting access");
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    String bearerRealm = String.format("Bearer realm=\"%s\"", applicationName);
    response.addHeader("WWW-Authenticate", bearerRealm);
    if (isJsonPreferred(request, response)) {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        om.writeValue(response.getOutputStream(),
                new Error(ErrorConstants.ERR_ACCESS_DENIED, authException.getMessage()));
    } else {// www  . j  a  v  a 2 s .  c  o  m
        sendRedirect(request, response);
    }
}