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.linuxbox.enkive.web.search.SearchFolderServlet.java

@SuppressWarnings("unused")
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
    res.setCharacterEncoding("UTF-8");
    try {/* w w w .  java  2s. c o  m*/

        String searchFolderId = WebScriptUtils.cleanGetParameter(req, "id");
        String action = WebScriptUtils.cleanGetParameter(req, "action");

        if (searchFolderId == null || searchFolderId.isEmpty())
            searchFolderId = "unimplemented";
        /*            searchFolderId = workspaceService.getActiveWorkspace(
          getPermissionService().getCurrentUsername())
          .getSearchFolderID();*/
        if (action == null || action.isEmpty())
            action = VIEW_SEARCH_FOLDER;

        WebPageInfo pageInfo = new WebPageInfo(WebScriptUtils.cleanGetParameter(req, PAGE_POSITION_PARAMETER),
                WebScriptUtils.cleanGetParameter(req, PAGE_SIZE_PARAMETER));

        JSONObject dataJSON = new JSONObject();
        JSONObject jsonResult = new JSONObject();
        dataJSON.put(SEARCH_ID_TAG, searchFolderId);

        if (LOGGER.isInfoEnabled())
            LOGGER.info("Loading " + searchFolderId);

        /*         SearchFolder searchFolder = workspaceService
                       .getSearchFolder(searchFolderId);*/
        SearchFolder searchFolder = null;

        JSONArray resultsJson = new JSONArray();

        if (searchFolder == null) {
            // No search folder
        } else if (action.equalsIgnoreCase(ADD_SEARCH_FOLDER_MESSAGE)) {
            String searchResultId = WebScriptUtils.cleanGetParameter(req, "searchResultId");
            String messageidlist = WebScriptUtils.cleanGetParameter(req, "messageids");
            Collection<String> messageIds = new HashSet<String>(Arrays.asList(messageidlist.split(",")));
            addSearchFolderMessages(searchFolder, searchResultId, messageIds);
        } else if (action.equalsIgnoreCase(EXPORT_SEARCH_FOLDER)) {
            res.setContentType("application/x-gzip; charset=ISO-8859-1");
            exportSearchFolder(searchFolder, res.getOutputStream());
        } else if (action.equalsIgnoreCase(REMOVE_SEARCH_FOLDER_MESSAGE)) {
            String messageidlist = WebScriptUtils.cleanGetParameter(req, "messageids");
            Collection<String> messageIds = new HashSet<String>(Arrays.asList(messageidlist.split(",")));
            removeSearchFolderMessages(searchFolder, messageIds);
        } else if (action.equalsIgnoreCase(VIEW_SEARCH_FOLDER)) {
            resultsJson = viewSearchFolder(searchFolder, pageInfo);
            dataJSON.put(ITEM_TOTAL_TAG, pageInfo.getItemTotal());

            dataJSON.put(RESULTS_TAG, resultsJson);
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Returning search folder messages for folder id " + searchFolderId);

            jsonResult.put(DATA_TAG, dataJSON);
            jsonResult.put(PAGING_LABEL, pageInfo.getPageJSON());
            res.getWriter().write(jsonResult.toString());
        }

    } catch (WorkspaceException e) {
        respondError(HttpServletResponse.SC_UNAUTHORIZED, null, res);
        throw new EnkiveServletException("Could not login to repository to retrieve search", e);
    } catch (JSONException e) {
        respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, res);
        throw new EnkiveServletException("Unable to serialize JSON", e);
    } catch (CannotRetrieveException e) {
        respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, res);
        throw new EnkiveServletException("Unable to retrieve search folder messages", e);
    } finally {

    }
}

From source file:com.datatorrent.stram.security.StramWSFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {
    if (!(req instanceof HttpServletRequest)) {
        throw new ServletException("This filter only works for HTTP/HTTPS");
    }//from  w w w  .jav  a  2  s .com

    HttpServletRequest httpReq = (HttpServletRequest) req;
    HttpServletResponse httpResp = (HttpServletResponse) resp;
    if (LOG.isDebugEnabled()) {
        LOG.debug("Remote address for request is: " + httpReq.getRemoteAddr());
    }
    String requestURI = httpReq.getRequestURI();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Request path " + requestURI);
    }
    boolean authenticate = true;
    String user = null;
    if (getProxyAddresses().contains(httpReq.getRemoteAddr())) {
        if (httpReq.getCookies() != null) {
            for (Cookie c : httpReq.getCookies()) {
                if (WEBAPP_PROXY_USER.equals(c.getName())) {
                    user = c.getValue();
                    break;
                }
            }
        }
        if (requestURI.equals(WebServices.PATH) && (user != null)) {
            String token = createClientToken(user, httpReq.getLocalAddr());
            if (LOG.isDebugEnabled()) {
                LOG.debug("Create token " + token);
            }
            Cookie cookie = new Cookie(CLIENT_COOKIE, token);
            httpResp.addCookie(cookie);
        }
        authenticate = false;
    }
    if (authenticate) {
        Cookie cookie = null;
        if (httpReq.getCookies() != null) {
            for (Cookie c : httpReq.getCookies()) {
                if (c.getName().equals(CLIENT_COOKIE)) {
                    cookie = c;
                    break;
                }
            }
        }
        boolean valid = false;
        if (cookie != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Verifying token " + cookie.getValue());
            }
            user = verifyClientToken(cookie.getValue());
            valid = true;
            if (LOG.isDebugEnabled()) {
                LOG.debug("Token valid");
            }
        }
        if (!valid) {
            httpResp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
    }

    if (user == null) {
        LOG.warn("Could not find " + WEBAPP_PROXY_USER + " cookie, so user will not be set");
        chain.doFilter(req, resp);
    } else {
        final StramWSPrincipal principal = new StramWSPrincipal(user);
        ServletRequest requestWrapper = new StramWSServletRequestWrapper(httpReq, principal);
        chain.doFilter(requestWrapper, resp);
    }
}

From source file:org.openrepose.filters.clientauth.common.AuthenticationHandler.java

private FilterDirector authenticate(HttpServletRequest request) {
    final FilterDirector filterDirector = new FilterDirectorImpl();
    filterDirector.setResponseStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
    filterDirector.setFilterAction(FilterAction.RETURN);
    int offset = getCacheOffset();

    final String tracingHeader = request.getHeader(CommonHttpHeader.TRACE_GUID.toString());
    final String authToken = request.getHeader(CommonHttpHeader.AUTH_TOKEN.toString());
    ExtractorResult<String> account = null;
    AuthToken token = null;/*  w w  w .j  a  va  2  s . c om*/
    String contactId = null;

    if (tenanted) {
        account = extractAccountIdentification(request);
    }

    final boolean allow = allowAccount(account);

    String endpointsInBase64 = "";
    List<AuthGroup> groups = new ArrayList<AuthGroup>();
    try {
        if (!StringUtilities.isBlank(authToken) && allow) {
            token = checkToken(account, authToken);

            if (token == null) {
                token = validateToken(account, StringUriUtilities.encodeUri(authToken), tracingHeader);
                cacheUserInfo(token, offset);
            }
        }

        if (token != null) {
            groups = getAuthGroups(token, offset, tracingHeader);
            contactId = token.getContactId();

            //getting the encoded endpoints to pass into the header, if the endpoints config is not null
            if (endpointsConfiguration != null) {
                endpointsInBase64 = getEndpointsInBase64(token, tracingHeader);
            }
        }
    } catch (AuthServiceOverLimitException ex) {
        LOG.error(FAILURE_AUTH_N + REASON + ex.getMessage());
        LOG.trace("", ex);
        filterDirector.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();
        }
        filterDirector.responseHeaderManager().appendHeader(HttpHeaders.RETRY_AFTER, retry);
        delegationMessage.set(FAILURE_AUTH_N);
    } catch (AuthServiceException ex) {
        LOG.error(FAILURE_AUTH_N + REASON + ex.getMessage());
        LOG.trace("", ex);
        if (ex.getCause() instanceof AkkaServiceClientException
                && ex.getCause().getCause() instanceof TimeoutException) {
            filterDirector.setResponseStatusCode(HttpServletResponse.SC_GATEWAY_TIMEOUT);
        } else {
            filterDirector.setResponseStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
        delegationMessage.set(FAILURE_AUTH_N);
    } catch (Exception ex) {
        LOG.error(FAILURE_AUTH_N, ex);
        filterDirector.setResponseStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        delegationMessage.set(FAILURE_AUTH_N + REASON + ex.getMessage());
    }

    setFilterDirectorValues(authToken, token, delegable, delegableQuality, delegationMessage.get(),
            filterDirector, account == null ? null : account.getResult(), groups, endpointsInBase64, contactId,
            sendAllTenantIds, sendTenantIdQuality);

    delegationMessage.remove();

    return filterDirector;
}

From source file:org.jasig.portlet.emailpreview.controller.EmailAccountSummaryController.java

@ResourceMapping(value = "accountSummary")
public ModelAndView getAccountSummary(ResourceRequest req, ResourceResponse res,
        @RequestParam("pageStart") int start, @RequestParam("numberOfMessages") int max,
        @RequestParam(value = "inboxFolder", required = false) String folder) throws IOException {

    // Define view and generate model
    Map<String, Object> model = new HashMap<String, Object>();

    String username = req.getRemoteUser();
    try {/*  w  w  w.  j a  v a  2 s  . c o  m*/

        // Force a re-load from the data source if called for by the UI.
        boolean refresh = Boolean.valueOf(req.getParameter(FORCE_REFRESH_PARAMETER));

        // Or because of a change in settings.
        if (req.getPortletSession().getAttribute(FORCE_REFRESH_PARAMETER) != null) {
            // Doesn't matter what the value is;  this calls for a refresh...
            refresh = true;
            req.getPortletSession().removeAttribute(FORCE_REFRESH_PARAMETER);
        }

        PortletPreferences prefs = req.getPreferences();

        if ((folder == null) || (folder.equals(INBOX_NAME_UNDEFINED))) {
            folder = prefs.getValue(EmailAccountSummaryController.INBOX_NAME_PREFERENCE, INBOX_NAME_DEFAULT);
        }

        String prefFolder = prefs.getValue(EmailAccountSummaryController.INBOX_NAME_PREFERENCE,
                INBOX_NAME_DEFAULT);
        if ((!prefs.isReadOnly(INBOX_NAME_PREFERENCE)) && (!folder.equals(prefFolder))) {
            prefs.setValue(INBOX_NAME_PREFERENCE, folder);
            prefs.store();
        }

        // Get current user's account information
        AccountSummary accountSummary = getEmailAccountService(req).getAccountSummary(req, start, max, refresh,
                folder);

        // Check for AuthN failure...
        if (accountSummary.isValid()) {
            model.put(KEY_ACCOUNT_SUMMARY, accountSummary);
            model.put(KEY_INBOX_URL, accountSummary.getInboxUrl());
            if (accountSummary.getQuota() == null) {
                model.put(KEY_EMAIL_QUOTA_USAGE, "-1");
            } else {
                model.put(KEY_EMAIL_QUOTA_USAGE, accountSummary.getQuota().getUsageAsPercentage());
                model.put(KEY_EMAIL_QUOTA_LIMIT, accountSummary.getQuota().getLimitAsString());
            }
        } else {
            Throwable cause = accountSummary.getErrorCause();
            if (MailAuthenticationException.class.isAssignableFrom(cause.getClass())) {
                log.info("Authentication Failure (username='" + username + "') : " + cause.getMessage());
                res.setProperty(ResourceResponse.HTTP_STATUS_CODE,
                        Integer.toString(HttpServletResponse.SC_UNAUTHORIZED));
                model.put(KEY_ERROR, "Not authorized");
            } else {
                log.error("Unanticipated Error", cause);
                res.setProperty(ResourceResponse.HTTP_STATUS_CODE,
                        Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
                model.put(KEY_ERROR, "Unanticipated Error");
            }
        }

    } catch (MailTimeoutException ex) {
        log.error("Mail Service Timeout", ex);
        res.setProperty(ResourceResponse.HTTP_STATUS_CODE,
                Integer.toString(HttpServletResponse.SC_GATEWAY_TIMEOUT));
        model.put(KEY_ERROR, "Mail Service Timeout");
    } catch (Exception ex) {
        /* ********************************************************
        In the case of an unknown error we want to send the
        exception's message back to the portlet. This will
        let implementers write specific instructions for
        their service desks to follow for specific errors.
        ******************************************************** */
        log.error("Unanticipated Error", ex);
        res.setProperty(ResourceResponse.HTTP_STATUS_CODE,
                Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
        model.put(KEY_ERROR, "ex.getMessage()");
    }

    return new ModelAndView("json", model);

}

From source file:org.infinispan.server.test.rest.security.RESTCertSecurityTest.java

@Test
@InSequence(2)/* w  ww .  j  a  va2 s .co m*/
public void testSecuredReadWriteOperations() throws Exception {
    try {
        controller.start(CONTAINER1, new Config().add(SERVER_CONFIG_PROPERTY, CONFIG_READ_WRITE_SECURED).map());
        //correct alias for the certificate
        put(securedClient(testAlias), keyAddress(KEY_A), HttpServletResponse.SC_OK);
        //test wrong authorization, 1. wrong alias for the certificate
        put(securedClient(test2Alias), keyAddress(KEY_B), HttpServletResponse.SC_FORBIDDEN);
        //2. access over 8080
        put(securedClient(testAlias), keyAddressUnsecured(KEY_B), HttpServletResponse.SC_UNAUTHORIZED);
        post(securedClient(testAlias), keyAddress(KEY_C), HttpServletResponse.SC_OK);
        post(securedClient(test2Alias), keyAddress(KEY_D), HttpServletResponse.SC_FORBIDDEN);
        //get is secured too
        HttpResponse resp = get(securedClient(testAlias), keyAddress(KEY_A), HttpServletResponse.SC_OK);
        String content = new BufferedReader(new InputStreamReader(resp.getEntity().getContent())).readLine();
        assertEquals("data", content);
        //test wrong authorization, 1. wrong alias for the certificate
        get(securedClient(test2Alias), keyAddress(KEY_A), HttpServletResponse.SC_FORBIDDEN);
        //2. access over 8080
        get(securedClient(testAlias), keyAddressUnsecured(KEY_A), HttpServletResponse.SC_UNAUTHORIZED);
        head(securedClient(test2Alias), keyAddress(KEY_A), HttpServletResponse.SC_FORBIDDEN);
        //access over 8080
        head(securedClient(testAlias), keyAddressUnsecured(KEY_A), HttpServletResponse.SC_UNAUTHORIZED);
        head(securedClient(testAlias), keyAddress(KEY_A), HttpServletResponse.SC_OK);
        delete(securedClient(test2Alias), keyAddress(KEY_A), HttpServletResponse.SC_FORBIDDEN);
        delete(securedClient(testAlias), keyAddress(KEY_A), HttpServletResponse.SC_OK);
        delete(securedClient(testAlias), keyAddress(KEY_C), HttpServletResponse.SC_OK);
    } finally {
        controller.stop(CONTAINER1);
    }
}

From source file:waffle.spring.NegotiateSecurityFilter.java

/**
 * Send a 401 Unauthorized along with protocol authentication headers.
 * /*from w  w  w .  j a va  2 s.  c  o m*/
 * @param response
 *            HTTP Response
 * @param close
 *            Close connection.
 */
protected void sendUnauthorized(final HttpServletResponse response, final boolean close) {
    try {
        this.provider.sendUnauthorized(response);
        if (close) {
            response.setHeader("Connection", "close");
        } else {
            response.setHeader("Connection", "keep-alive");
        }
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        response.flushBuffer();
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:io.druid.server.initialization.JettyTest.java

@Test
public void testExtensionAuthFilter() throws Exception {
    URL url = new URL("http://localhost:" + port + "/default");
    HttpURLConnection get = (HttpURLConnection) url.openConnection();
    get.setRequestProperty(DummyAuthFilter.AUTH_HDR, DummyAuthFilter.SECRET_USER);
    Assert.assertEquals(HttpServletResponse.SC_OK, get.getResponseCode());

    get = (HttpURLConnection) url.openConnection();
    get.setRequestProperty(DummyAuthFilter.AUTH_HDR, "hacker");
    Assert.assertEquals(HttpServletResponse.SC_UNAUTHORIZED, get.getResponseCode());
}

From source file:ee.ria.xroad.proxy.clientproxy.AsicContainerClientRequestProcessor.java

private void verifyClientAuthentication(ClientId clientId) throws Exception {
    log.trace("verifyClientAuthentication({})", clientId);
    try {/*from  ww w .  j a  va 2 s. co m*/
        IsAuthentication.verifyClientAuthentication(clientId, getIsAuthenticationData(servletRequest));
    } catch (CodedException ex) {
        throw new CodedExceptionWithHttpStatus(HttpServletResponse.SC_UNAUTHORIZED, ex);
    }
}

From source file:io.fabric8.maven.impl.MavenSecureHttpContext.java

public boolean authenticate(HttpServletRequest request, HttpServletResponse response) {
    // Return immediately if the header is missing
    String authHeader = request.getHeader(HEADER_AUTHORIZATION);
    if (authHeader != null && authHeader.length() > 0) {

        // Get the authType (Basic, Digest) and authInfo (user/password)
        // from the header
        authHeader = authHeader.trim();//  ww  w .j av a 2  s  .  c om
        int blank = authHeader.indexOf(' ');
        if (blank > 0) {
            String authType = authHeader.substring(0, blank);
            String authInfo = authHeader.substring(blank).trim();

            // Check whether authorization type matches
            if (authType.equalsIgnoreCase(AUTHENTICATION_SCHEME_BASIC)) {
                try {
                    String srcString = base64Decode(authInfo);
                    int i = srcString.indexOf(':');
                    String username = srcString.substring(0, i);
                    String password = srcString.substring(i + 1);

                    // authenticate
                    Subject subject = doAuthenticate(username, password);
                    if (subject != null) {
                        // as per the spec, set attributes
                        request.setAttribute(HttpContext.AUTHENTICATION_TYPE, HttpServletRequest.BASIC_AUTH);
                        request.setAttribute(HttpContext.REMOTE_USER, username);
                        // succeed
                        return true;
                    }
                } catch (Exception e) {
                    // Ignore
                }
            }
        }
    }

    // request authentication
    try {
        response.setHeader(HEADER_WWW_AUTHENTICATE,
                AUTHENTICATION_SCHEME_BASIC + " realm=\"" + this.realm + "\"");
        // must response with status and flush as Jetty may report org.eclipse.jetty.server.Response Committed before 401 null
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentLength(0);
        response.flushBuffer();
    } catch (IOException ioe) {
        // failed sending the response ... cannot do anything about it
    }

    // inform HttpService that authentication failed
    return false;
}

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

@RequestMapping(method = RequestMethod.GET, value = "/user/notification")
public @ResponseBody Notifications getNotificationsByUser(HttpServletRequest request,
        HttpServletResponse response, HttpSession session, @RequestParam("since") Long since,
        @RequestParam("position") Integer position, @RequestParam("count") Integer count)
        throws DataException, IOException, SmartCampusException {

    String userId = getUserId();/*from  w w w . j  a  v a  2 s.com*/
    if (userId == null) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return null;
    }

    Notifications result = new Notifications();
    result.setNotifications(notificationManager.get(userId, null, since, position, count, null));

    return result;
}