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.bosch.cr.examples.inventorybrowser.server.ProxyServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String auth = req.getHeader("Authorization");
    if (auth == null) {
        resp.setHeader("WWW-Authenticate", "BASIC realm=\"Proxy for Bosch IoT Things\"");
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;//  w ww.ja va  2s.  c  o m
    }

    try {
        long time = System.currentTimeMillis();
        CloseableHttpClient c = getHttpClient();

        String targetUrl = URL_PREFIX + req.getPathInfo()
                + (req.getQueryString() != null ? ("?" + req.getQueryString()) : "");
        BasicHttpRequest targetReq = new BasicHttpRequest(req.getMethod(), targetUrl);

        String user = "";
        if (auth.toUpperCase().startsWith("BASIC ")) {
            String userpassDecoded = new String(
                    new sun.misc.BASE64Decoder().decodeBuffer(auth.substring("BASIC ".length())));
            user = userpassDecoded.substring(0, userpassDecoded.indexOf(':'));
            String pass = userpassDecoded.substring(userpassDecoded.indexOf(':') + 1);
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);
            targetReq.addHeader(new BasicScheme().authenticate(creds, targetReq, null));
        }

        targetReq.addHeader("x-cr-api-token", props.getProperty("apiToken"));
        CloseableHttpResponse targetResp = c.execute(targetHost, targetReq);

        System.out.println("Request: " + targetHost + targetUrl + ", user " + user + " -> "
                + (System.currentTimeMillis() - time) + " msec: " + targetResp.getStatusLine());

        resp.setStatus(targetResp.getStatusLine().getStatusCode());
        targetResp.getEntity().writeTo(resp.getOutputStream());

    } catch (IOException | AuthenticationException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.craftercms.cstudio.publishing.servlet.FileUploadServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    if (ServletFileUpload.isMultipartContent(request)) {
        ServletFileUpload servletFileUpload = createServletFileUpload();
        List<FileItem> fileItemsList = null;
        Map<String, String> parameters = new HashMap<String, String>(11);
        Map<String, InputStream> files = new HashMap<String, InputStream>(11);
        try {/*from   w w  w.jav a 2  s .  c  o  m*/
            fileItemsList = servletFileUpload.parseRequest(request);
            for (FileItem fileItem : fileItemsList) {
                if (fileItem.isFormField()) {
                    parameters.put(fileItem.getFieldName(), fileItem.getString());
                } else {
                    files.put(fileItem.getFieldName(), fileItem.getInputStream());
                }
            }

            if (LOGGER.isDebugEnabled()) {

                StringBuilder parametersLog = new StringBuilder("Request Parameters : ");

                for (Entry<String, String> entry : parameters.entrySet()) {

                    String key = entry.getKey();
                    String value = entry.getValue();

                    if (key.equals(PARAM_PASSWORD)) {
                        value = "********";
                    }
                    parametersLog.append(" " + key + " = " + value);
                }

                LOGGER.debug(parametersLog.toString());
            }

            String password = parameters.get(PARAM_PASSWORD);
            if (password != null && password.equalsIgnoreCase(this.password)) {
                deployFiles(parameters, files);
                response.setStatus(HttpServletResponse.SC_OK);
            } else {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                if (LOGGER.isWarnEnabled()) {
                    LOGGER.warn(
                            "Illegal publish request received. Password parameter does not match configured password for deployer.");
                }
            }
        } catch (Exception e) {
            handleErrorCase(files, response, e);
        }
    }
}

From source file:org.jasig.cas.support.spnego.web.flow.SpnegoCredentialsAction.java

private void setResponseHeader(final RequestContext context, final Credentials credentials) {
    if (credentials == null) {
        return;/*from w  w  w .ja  v a2  s  .  c om*/
    }

    final HttpServletResponse response = WebUtils.getHttpServletResponse(context);
    final SpnegoCredentials spnegoCredentials = (SpnegoCredentials) credentials;
    final byte[] nextToken = spnegoCredentials.getNextToken();
    if (nextToken != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Obtained output token: " + new String(nextToken));
        }
        response.setHeader(SpnegoConstants.HEADER_AUTHENTICATE,
                (this.ntlm ? SpnegoConstants.NTLM : SpnegoConstants.NEGOTIATE) + " "
                        + Base64.encode(nextToken));
    } else {
        logger.debug("Unable to obtain the output token required.");
    }

    if ((spnegoCredentials.getPrincipal() == null) && send401OnAuthenticationFailure) {
        logger.debug("Setting HTTP Status to 401");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}

From source file:com.sg.rest.SpringSecurityTest.java

@Test
public void testSecureResourceWithoutAuthToken() throws IOException, Exception {
    mockMvc.perform(get(RequestPath.TEST_SECURE_REQUEST))
            .andExpect(status().is(HttpServletResponse.SC_UNAUTHORIZED))
            .andExpect(content().contentType(CustomMediaTypes.APPLICATION_JSON_UTF8.getMediatype()))
            .andExpect(jsonPath("$.eventRef.id", not(isEmptyOrNullString()))).andExpect(jsonPath("$.status",
                    is(AuthentificationFailureStatus.TOKEN_AUTHENTICATION_NO_TOKEN.name())));
}

From source file:org.openrepose.filters.authz.RequestAuthorizationHandler.java

@Override
public FilterDirector handleRequest(HttpServletRequest request, ReadableHttpServletResponse response) {
    final FilterDirector myDirector = new FilterDirectorImpl();
    myDirector.setFilterAction(FilterAction.RETURN);
    myDirector.setResponseStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    String message = "Failure in authorization component";

    final String tracingHeader = request.getHeader(CommonHttpHeader.TRACE_GUID.toString());
    final String authenticationToken = request.getHeader(CommonHttpHeader.AUTH_TOKEN.toString());

    try {/*from   w  w  w  .j  av  a  2 s  .  co m*/
        if (StringUtilities.isBlank(authenticationToken)) {
            // Reject if no token
            message = "Authentication token not found in X-Auth-Token header. Rejecting request.";
            LOG.debug(message);
            myDirector.setResponseStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
        } else if (adminRoleMatchIgnoringCase(request.getHeaders(OpenStackServiceHeader.ROLES.toString()))
                || isEndpointAuthorizedForToken(authenticationToken, tracingHeader)) {
            myDirector.setFilterAction(FilterAction.PASS);
        } else {
            message = "User token: " + authenticationToken
                    + ": The user's service catalog does not contain an endpoint that matches "
                    + "the endpoint configured in openstack-authorization.cfg.xml: \""
                    + configuredEndpoint.getHref() + "\".  User not authorized to access service.";
            LOG.info(message);
            myDirector.setResponseStatusCode(HttpServletResponse.SC_FORBIDDEN);
        }
    } catch (AuthServiceOverLimitException ex) {
        LOG.error(message);
        LOG.trace("", ex);
        myDirector.setResponseStatusCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); // (503)
        String retry = ex.getRetryAfter();
        if (retry == null) {
            Calendar retryCalendar = new GregorianCalendar();
            retryCalendar.add(Calendar.SECOND, 5);
            retry = new HttpDate(retryCalendar.getTime()).toRFC1123();
        }
        myDirector.responseHeaderManager().appendHeader(HttpHeaders.RETRY_AFTER, retry);
    } catch (AuthServiceException ex) {
        LOG.error(message);
        LOG.trace("", ex);
        if (ex.getCause() instanceof AkkaServiceClientException
                && ex.getCause().getCause() instanceof TimeoutException) {
            myDirector.setResponseStatusCode(HttpServletResponse.SC_GATEWAY_TIMEOUT);
        } else {
            myDirector.setResponseStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    } catch (Exception ex) {
        LOG.error(message);
        LOG.trace("", ex);
        myDirector.setResponseStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    if (delegating != null && myDirector.getFilterAction() != FilterAction.PASS) {
        myDirector.setFilterAction(FilterAction.PASS);
        for (Map.Entry<String, List<String>> mapHeaders : JavaDelegationManagerProxy
                .buildDelegationHeaders(myDirector.getResponseStatusCode(), CLIENT_AUTHORIZATION, message,
                        delegating.getQuality())
                .entrySet()) {
            List<String> value = mapHeaders.getValue();
            myDirector.requestHeaderManager().appendHeader(mapHeaders.getKey(),
                    value.toArray(new String[value.size()]));
        }
    }
    return myDirector;
}

From source file:com.cloudbees.servlet.filters.PrivateAppFilterIntegratedTest.java

@Test
public void unauthenticated_request_is_redirected_to_login_page() throws Exception {
    System.out.println("unauthenticated_request_is_redirected_to_login_page");

    privateAppFilter.setAuthenticationEntryPoint(PrivateAppFilter.AuthenticationEntryPoint.BASIC_AUTH);

    HttpResponse response = httpClient.execute(httpHost, new HttpGet("/"));

    assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpServletResponse.SC_UNAUTHORIZED));
    assertThat(response.containsHeader("WWW-Authenticate"), is(true));

    dumpHttpResponse(response);/*from   www.ja  v a2s . c  om*/

    EntityUtils.consumeQuietly(response.getEntity());

}

From source file:com.ecyrd.jspwiki.dav.WikiDavServlet.java

@Override
protected void doDelete(HttpServletRequest arg0, HttpServletResponse response)
        throws ServletException, IOException {
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "JSPWiki is read-only.");
}

From source file:org.gc.GoogleController.java

/**
 * This rest web service is the one that google called after login (callback url).
 * First it retrieve code and token that google sends back. 
 * It checks if code and token are not null, then if token is the same as the one saved in session.
 * If it is not then response status is UNAUTHORIZED, otherwise it retrieves user data.
 * //w  ww . j  av  a 2 s . c o m
 * Then redirects authenticated user to home page where user can access protected resources.
 * 
 * @param request : instance of {@link HttpServletRequest}
 * @param response : instance of {@link HttpServletResponse}
 * @return redirect to home page
 */
@RequestMapping(value = "/callback", method = RequestMethod.GET, produces = "application/json")
public String confirmStateToken(HttpServletRequest request, HttpServletResponse response) {

    logger.info("****** Google callback ******");
    String code = request.getParameter("code");
    String token = request.getParameter("state");
    String session_token = "";
    if (request.getSession().getAttribute("state") != null) {
        session_token = request.getSession().getAttribute("state").toString();
    }

    logger.info("request code: " + code);
    logger.info("request token: " + token);
    logger.info("request session token: " + session_token);

    //compare state token in session and state token in response of google
    //if equals return to home
    //if not error page
    if ((code == null || token == null) && (!token.equals(session_token))) {
        logger.info("Error: You have to sign in!");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    } else {
        try {
            //init analytics
            auth.getUserAnalytics(code);

            response.setStatus(HttpServletResponse.SC_OK);

        } catch (IOException e) {
            logger.info("IOException .. Problem in reading user data.");
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    return "redirect:/";
}

From source file:eu.trentorise.smartcampus.communicatorservice.controller.NotificationController.java

@RequestMapping(method = RequestMethod.GET, value = "/app/{capp:.*}/notification/{id}")
public @ResponseBody Notification getNotificationByApp(HttpServletRequest request, HttpServletResponse response,
        HttpSession session, @PathVariable("id") String id, @PathVariable("capp") String capp)
        throws DataException, IOException, NotFoundException, SmartCampusException {

    if (capp == null) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return null;
    }/*from ww  w  . j a  v a  2  s.c  o  m*/

    return notificationManager.getByIdAndApp(id, capp);
}

From source file:com.bosch.cr.integration.helloworld.ProxyServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String auth = req.getHeader("Authorization");
    if (auth == null) {
        resp.setHeader("WWW-Authenticate", "BASIC realm=\"Proxy for Bosch IoT Things\"");
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;//from   w  w w .j  a  v a2 s. c o m
    }

    try {
        long time = System.currentTimeMillis();
        CloseableHttpClient c = getHttpClient();

        String targetUrl = URL_PREFIX + req.getPathInfo()
                + (req.getQueryString() != null ? ("?" + req.getQueryString()) : "");
        BasicHttpRequest targetReq = new BasicHttpRequest(req.getMethod(), targetUrl);

        String user = "";
        if (auth.toUpperCase().startsWith("BASIC ")) {
            String userpassDecoded = new String(
                    new sun.misc.BASE64Decoder().decodeBuffer(auth.substring("BASIC ".length())));
            user = userpassDecoded.substring(0, userpassDecoded.indexOf(':'));
            String pass = userpassDecoded.substring(userpassDecoded.indexOf(':') + 1);
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);
            targetReq.addHeader(new BasicScheme().authenticate(creds, targetReq, null));
        }

        targetReq.addHeader("x-cr-api-token", req.getHeader("x-cr-api-token"));
        CloseableHttpResponse targetResp = c.execute(targetHost, targetReq);

        System.out.println("Request: " + targetHost + targetUrl + ", user " + user + " -> "
                + (System.currentTimeMillis() - time) + " msec: " + targetResp.getStatusLine());

        resp.setStatus(targetResp.getStatusLine().getStatusCode());
        targetResp.getEntity().writeTo(resp.getOutputStream());
    } catch (IOException | AuthenticationException ex) {
        throw new RuntimeException(ex);
    }
}