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.mirth.connect.server.servlets.EventServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // MIRTH-1745
    response.setCharacterEncoding("UTF-8");

    if (!isUserLoggedIn(request)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    } else {//  w w  w  . j  a  v a2s  .co  m
        try {
            EventController eventController = ControllerFactory.getFactory().createEventController();
            ObjectXMLSerializer serializer = new ObjectXMLSerializer();
            PrintWriter out = response.getWriter();
            Operation operation = Operations.getOperation(request.getParameter("op"));
            String uid = null;
            boolean useNewTempTable = false;
            Map<String, Object> parameterMap = new HashMap<String, Object>();

            if (StringUtils.isNotBlank(request.getParameter("uid"))) {
                uid = request.getParameter("uid");
                useNewTempTable = true;
            } else {
                uid = request.getSession().getId();
            }

            if (operation.equals(Operations.EVENT_CREATE_TEMP_TABLE)) {
                EventFilter eventFilter = (EventFilter) serializer.fromXML(request.getParameter("filter"));
                parameterMap.put("filter", eventFilter);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    response.setContentType(TEXT_PLAIN);
                    out.println(eventController.createTempTable(eventFilter, uid, useNewTempTable));
                }
            } else if (operation.equals(Operations.EVENT_REMOVE_FILTER_TABLES)) {
                if (!isUserAuthorized(request, null)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    eventController.removeFilterTable(uid);
                }
            } else if (operation.equals(Operations.EVENT_GET_BY_PAGE)) {
                if (!isUserAuthorized(request, null)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    int page = Integer.parseInt(request.getParameter("page"));
                    int pageSize = Integer.parseInt(request.getParameter("pageSize"));
                    int max = Integer.parseInt(request.getParameter("maxEvents"));
                    response.setContentType(APPLICATION_XML);
                    serializer.toXML(eventController.getEventsByPage(page, pageSize, max, uid), out);
                }
            } else if (operation.equals(Operations.EVENT_GET_BY_PAGE_LIMIT)) {
                EventFilter eventFilter = (EventFilter) serializer.fromXML(request.getParameter("filter"));
                parameterMap.put("filter", eventFilter);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    int page = Integer.parseInt(request.getParameter("page"));
                    int pageSize = Integer.parseInt(request.getParameter("pageSize"));
                    int max = Integer.parseInt(request.getParameter("maxEvents"));
                    response.setContentType(APPLICATION_XML);
                    serializer.toXML(
                            eventController.getEventsByPageLimit(page, pageSize, max, uid, eventFilter), out);
                }
            } else if (operation.equals(Operations.EVENT_REMOVE_ALL)) {
                if (!isUserAuthorized(request, null)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    eventController.removeAllEvents();

                    // Audit after removal
                    isUserAuthorized(request, null);
                }
            } else if (operation.equals(Operations.EVENT_EXPORT_ALL)) {
                if (!isUserAuthorized(request, null)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    response.setContentType(TEXT_PLAIN);
                    out.println(eventController.exportAllEvents());
                }
            } else if (operation.equals(Operations.EVENT_EXPORT_AND_REMOVE_ALL)) {
                if (!isUserAuthorized(request, null)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    response.setContentType(TEXT_PLAIN);

                    // Add file path of export and audit after removal
                    String exportPath = eventController.exportAndRemoveAllEvents();
                    parameterMap.put("file", exportPath);
                    isUserAuthorized(request, parameterMap);

                    out.println(exportPath);
                }
            }
        } catch (RuntimeIOException rio) {
            logger.debug(rio);
        } catch (Throwable t) {
            logger.error(ExceptionUtils.getStackTrace(t));
            throw new ServletException(t);
        }
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.FileDownload.java

@Override
public ActionForward execute(final ActionMapping mapping, final ActionForm actionForm,
        final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    final String oid = request.getParameter("oid");
    final File file = FenixFramework.getDomainObject(oid);
    if (file == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_BAD_REQUEST));
        response.getWriter().close();//w  w w  .j a v a 2s .co  m
    } else {
        final Person person = AccessControl.getPerson();
        if (!file.isPrivate() || file.isPersonAllowedToAccess(person)) {
            response.setContentType(file.getContentType());
            response.addHeader("Content-Disposition", "attachment; filename=" + file.getFilename());
            response.setContentLength(file.getSize().intValue());
            final DataOutputStream dos = new DataOutputStream(response.getOutputStream());
            dos.write(file.getContents());
            dos.close();
        } else if (file.isPrivate() && person == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_UNAUTHORIZED));
            response.getWriter().close();
        } else {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_FORBIDDEN));
            response.getWriter().close();
        }
    }
    return null;
}

From source file:com.example.getstarted.auth.Oauth2CallbackServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

    // Ensure that this is no request forgery going on, and that the user
    // sending us this connect request is the user that was supposed to.
    if (req.getSession().getAttribute("state") == null
            || !req.getParameter("state").equals((String) req.getSession().getAttribute("state"))) {
        resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        logger.log(Level.WARNING, "Invalid state parameter, expected "
                + (String) req.getSession().getAttribute("state") + " got " + req.getParameter("state"));
        resp.sendRedirect("/books");
        return;/*from w  w  w.  j av  a  2 s.c o m*/
    }

    req.getSession().removeAttribute("state"); // Remove one-time use state.

    flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
            getServletContext().getInitParameter("bookshelf.clientID"),
            getServletContext().getInitParameter("bookshelf.clientSecret"), SCOPES).build();

    final TokenResponse tokenResponse = flow.newTokenRequest(req.getParameter("code"))
            .setRedirectUri(getServletContext().getInitParameter("bookshelf.callback")).execute();

    req.getSession().setAttribute("token", tokenResponse.toString()); // Keep track of the token.
    final Credential credential = flow.createAndStoreCredential(tokenResponse, null);
    final HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(credential);

    final GenericUrl url = new GenericUrl(USERINFO_ENDPOINT); // Make an authenticated request.
    final HttpRequest request = requestFactory.buildGetRequest(url);
    request.getHeaders().setContentType("application/json");

    final String jsonIdentity = request.execute().parseAsString();
    @SuppressWarnings("unchecked")
    HashMap<String, String> userIdResult = new ObjectMapper().readValue(jsonIdentity, HashMap.class);
    // From this map, extract the relevant profile info and store it in the session.
    req.getSession().setAttribute("userEmail", userIdResult.get("email"));
    req.getSession().setAttribute("userId", userIdResult.get("sub"));
    req.getSession().setAttribute("userImageUrl", userIdResult.get("picture"));
    logger.log(Level.INFO,
            "Login successful, redirecting to " + (String) req.getSession().getAttribute("loginDestination"));
    resp.sendRedirect((String) req.getSession().getAttribute("loginDestination"));
}

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

@ResourceMapping(value = "updatePageSize")
public ModelAndView updatePageSize(ResourceRequest req, ResourceResponse res,
        @RequestParam("newPageSize") int newPageSize) throws Exception {

    PortletPreferences prefs = req.getPreferences();

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

    if (!prefs.isReadOnly(EmailSummaryController.PAGE_SIZE_PREFERENCE)) {
        prefs.setValue(EmailSummaryController.PAGE_SIZE_PREFERENCE, Integer.toString(newPageSize));
        prefs.store();//from w  ww. ja  v  a  2  s  .com
        model.put(STATUS_KEY, true);
    } else {
        if (log.isDebugEnabled()) {
            String msg = "Ignoring change to pageSize for the following "
                    + "user because the preference is read only:  " + req.getRemoteUser();
            log.debug(msg);
        }
        res.setProperty(ResourceResponse.HTTP_STATUS_CODE,
                Integer.toString(HttpServletResponse.SC_UNAUTHORIZED));
        model.put("error", "Not authorized");
    }

    return new ModelAndView("json", model);

}

From source file:de.hybris.platform.assistedservicestorefront.controllers.CustomerListController.java

/**
 * Method responsible for getting available customer list for agent and return a popup with the data
 *
 * @param model/*from   www .  j a v  a  2  s  .c  o m*/
 *           model to hold the populated data
 * @return the popup with list of customers list populated
 */
@RequestMapping(value = "/availableCustomerLists", method = RequestMethod.GET)
public String getCustomersListPopup(final Model model, final HttpServletResponse response) {
    if (!assistedServiceFacade.isAssistedServiceAgentLoggedIn()) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        assistedServiceFacade.getAsmSession().setFlashErrorMessage("asm.emulate.error.agent_missed");
        return null;
    }

    final List<UserGroupData> customerLists = customerListFacade
            .getCustomerListsForEmployee(assistedServiceFacade.getAsmSession().getAgent().getUid());

    // Handle paged search results
    if (!CollectionUtils.isEmpty(customerLists)) {
        model.addAttribute(AVAILABLE_CUSTOMER_LIST, customerLists);
        model.addAttribute(DEFAULT_CUSTOMER_LIST, customerLists.get(0).getUid());
    }

    return AssistedservicestorefrontControllerConstants.Views.Fragments.CustomerListComponent.ASMCustomerListPopup;
}

From source file:it.geosolutions.geostore.services.rest.security.RestAuthenticationEntryPoint.java

@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {
    URI url = null;//from   w  ww .  jav  a 2 s. co m
    try {
        url = new URI(request.getRequestURI());
    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        LOGGER.error("Invalid URI:" + request.getRequestURI());
        super.commence(request, response, authException);
        return;
    }
    if (url == null) {
        super.commence(request, response, authException);
        return;
    }
    if (url.getPath().contains(LOGIN_PATH)) {
        response.setHeader("WWW-Authenticate", "FormBased");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    } else {
        super.commence(request, response, authException);

    }

}

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

@Test
public void testCorrectUserAndPassword() throws Exception {
    HttpGet httpGet = new HttpGet(getURL());
    HttpResponse response = getHttpResponse(httpGet);

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

From source file:ch.ge.ve.protopoc.jwt.JwtAuthenticationEntryPoint.java

@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException {
    // This is invoked when user tries to access a secured REST resource without supplying any credentials
    // We should just send a 401 Unauthorized response because there is no 'login page' to redirect to
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}

From source file:com.vmware.identity.samlservice.impl.AuthnRequestStateKerbAuthenticationFilter.java

@Override
public void preAuthenticate(AuthnRequestState t) throws SamlServiceException {
    log.debug("AuthnRequestStateKerbAuthenticationFilter.preAuthenticate is called");

    Validate.notNull(t);/*from ww w.  j  av  a  2 s . co m*/
    HttpServletRequest request = t.getRequest();
    Validate.notNull(request);
    IdmAccessor accessor = t.getIdmAccessor();
    Validate.notNull(accessor);

    // then check if required auth header is present
    if (request.getParameter(Shared.REQUEST_AUTH_PARAM) == null) {
        // authentication not possible
        log.debug("REQUEST_AUTH_HEADER is missing, requesting KERB_AUTH_PREFIX");
        t.setWwwAuthenticate(Shared.KERB_AUTH_PREFIX);
        t.setValidationResult(new ValidationResult(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized", null));
        throw new SamlServiceException();
    }
}

From source file:ch.wisv.areafiftylan.security.TokenAuthenticationFilter.java

private AuthenticationToken extractOptional(Optional<AuthenticationToken> op, ServletResponse response)
        throws IOException {
    if (!op.isPresent()) {
        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token not found");
        return null;
    } else {//from  w  w  w .j  a v a2 s  .com
        return op.get();
    }
}