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.vmware.identity.samlservice.impl.AuthnRequestStateTLSClientAuthenticationFilter.java

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

    Validate.notNull(t);//www  .  ja va  2s.  com
    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(Shared.REQUEST_AUTH_PARAM + " is missing, requesting " + Shared.TLSCLIENT_AUTH_PREFIX);
        t.setWwwAuthenticate(Shared.TLSCLIENT_AUTH_PREFIX);
        ValidationResult vr = new ValidationResult(HttpServletResponse.SC_UNAUTHORIZED, WebSSOError.BAD_REQUEST,
                null);
        t.setValidationResult(vr);
        throw new SamlServiceException();
    }

    // check if logout cookie is present
    Cookie[] cookies = request.getCookies();
    String logoutCookieName = Shared.getLogoutCookieName(accessor.getTenant());
    if (cookies != null && cookies.length > 0) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equalsIgnoreCase(logoutCookieName)) {
                ValidationResult vr = new ValidationResult(HttpServletResponse.SC_BAD_REQUEST,
                        WebSSOError.UNAUTHORIZED, WebSSOError.LOGGED_OUT_TLS_SESSION);
                t.setValidationResult(vr);
                throw new SamlServiceException();
            }
        }
    }
}

From source file:com.mirth.connect.server.servlets.MessageObjectServlet.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 {//from  ww  w .j  av a 2 s .c  om
        try {
            MessageObjectController messageObjectController = ControllerFactory.getFactory()
                    .createMessageObjectController();
            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 (request.getParameter("uid") != null && !request.getParameter("uid").equals("")) {
                uid = request.getParameter("uid");
                useNewTempTable = true;
            } else {
                uid = request.getSession().getId();
            }

            if (operation.equals(Operations.MESSAGE_CREATE_TEMP_TABLE)) {
                MessageObjectFilter filter = (MessageObjectFilter) serializer
                        .fromXML(request.getParameter("filter"));
                redactMessageObjectFilter(request, filter);
                parameterMap.put("messageFilter", filter);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    response.setContentType(TEXT_PLAIN);
                    out.println(messageObjectController.createMessagesTempTable(filter, uid, useNewTempTable));
                }
            } else if (operation.equals(Operations.MESSAGE_FILTER_TABLES_REMOVE)) {
                if (!isUserAuthorized(request, null)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    messageObjectController.removeFilterTable(uid);
                }
            } else if (operation.equals(Operations.MESSAGE_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("maxMessages"));
                    response.setContentType(APPLICATION_XML);
                    serializer.toXML(messageObjectController.getMessagesByPage(page, pageSize, max, uid, true),
                            out);
                }

            } else if (operation.equals(Operations.MESSAGE_GET_BY_PAGE_LIMIT)) {
                MessageObjectFilter filter = (MessageObjectFilter) serializer
                        .fromXML(request.getParameter("filter"));
                redactMessageObjectFilter(request, filter);
                parameterMap.put("filter", filter);

                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("maxMessages"));
                    response.setContentType(APPLICATION_XML);
                    serializer.toXML(
                            messageObjectController.getMessagesByPageLimit(page, pageSize, max, uid, filter),
                            out);
                }
            } else if (operation.equals(Operations.MESSAGE_REMOVE)) {
                MessageObjectFilter filter = (MessageObjectFilter) serializer
                        .fromXML(request.getParameter("filter"));
                redactMessageObjectFilter(request, filter);
                parameterMap.put("filter", filter);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    messageObjectController.removeMessages(filter);
                }
            } else if (operation.equals(Operations.MESSAGE_CLEAR)) {
                String channelId = request.getParameter("data");
                parameterMap.put("channelId", channelId);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    messageObjectController.clearMessages(channelId);
                }
            } else if (operation.equals(Operations.MESSAGE_REPROCESS)) {
                MessageObjectFilter filter = (MessageObjectFilter) serializer
                        .fromXML(request.getParameter("filter"));
                redactMessageObjectFilter(request, filter);
                boolean replace = Boolean.valueOf(request.getParameter("replace"));
                List<String> destinations = (List<String>) serializer
                        .fromXML(request.getParameter("destinations"));
                parameterMap.put("filter", filter);
                parameterMap.put("replace", replace);
                parameterMap.put("destinations", destinations);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    messageObjectController.reprocessMessages(filter, replace, destinations);
                }
            } else if (operation.equals(Operations.MESSAGE_PROCESS)) {
                MessageObject message = (MessageObject) serializer.fromXML(request.getParameter("message"));
                parameterMap.put("message", message);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    messageObjectController.processMessage(message);
                }
            } else if (operation.equals(Operations.MESSAGE_IMPORT)) {
                MessageObject message = (MessageObject) serializer.fromXML(request.getParameter("message"));
                parameterMap.put("message", message);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    messageObjectController.importMessage(message);
                }
            } else if (operation.equals(Operations.MESSAGE_ATTACHMENT_GET)) {
                String attachmentId = request.getParameter("attachmentId");
                parameterMap.put("attachmentId", attachmentId);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    response.setContentType(APPLICATION_XML);
                    Attachment attachment = messageObjectController.getAttachment(attachmentId);
                    serializer.toXML(attachment, out);
                }
            } else if (operation.equals(Operations.MESSAGE_ATTACHMENT_GET_BY_MESSAGE_ID)) {
                String messageId = request.getParameter("messageId");
                parameterMap.put("messageId", messageId);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    response.setContentType(APPLICATION_XML);
                    List<Attachment> list = messageObjectController.getAttachmentsByMessageId(messageId);
                    serializer.toXML(list, out);
                    out.println("");
                }
            } else if (operation.equals(Operations.MESSAGE_ATTACHMENT_GET_ID_BY_MESSAGE_ID)) {
                String messageId = request.getParameter("messageId");
                parameterMap.put("messageId", messageId);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    response.setContentType(APPLICATION_XML);
                    List<Attachment> list = messageObjectController.getAttachmentIdsByMessageId(messageId);
                    serializer.toXML(list, out);
                    out.println("");
                }
            } else if (operation.equals(Operations.MESSAGE_DICOM_MESSAGE_GET)) {
                MessageObject message = (MessageObject) serializer.fromXML(request.getParameter("message"));
                parameterMap.put("message", message);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    String dicomMessage = DICOMUtil.getDICOMRawData(message);
                    out.println(dicomMessage);
                }
            }
        } catch (RuntimeIOException rio) {
            logger.debug(rio);
        } catch (Throwable t) {
            logger.error(ExceptionUtils.getStackTrace(t));
            throw new ServletException(t);
        }
    }
}

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

protected Event doExecute(RequestContext context) {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final HttpServletResponse response = WebUtils.getHttpServletResponse(context);
    final String authorizationHeader = request.getHeader(SpnegoConstants.HEADER_AUTHORIZATION);
    final String userAgent = request.getHeader(SpnegoConstants.HEADER_USER_AGENT);

    if (StringUtils.hasText(userAgent) && isSupportedBrowser(userAgent)) {
        if (!StringUtils.hasText(authorizationHeader)
                || !authorizationHeader.startsWith(this.messageBeginPrefix)
                || authorizationHeader.length() <= this.messageBeginPrefix.length()) {
            if (logger.isDebugEnabled()) {
                logger.debug("Authorization header not found. Sending WWW-Authenticate header");
            }/*from  w  w w. jav a 2 s .c o  m*/
            response.setHeader(SpnegoConstants.HEADER_AUTHENTICATE,
                    this.ntlm ? SpnegoConstants.NTLM : SpnegoConstants.NEGOTIATE);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            // The responseComplete flag tells the pausing view-state not to render the response
            // because another object has taken care of it.
            context.getExternalContext().recordResponseComplete();
        }
    }
    return success();
}

From source file:de.knightsoftnet.validators.server.security.AuthSuccessHandler.java

@Override
public void onAuthenticationSuccess(final HttpServletRequest prequest, final HttpServletResponse presponse,
        final Authentication pauthentication) throws IOException, ServletException {
    this.csrfCookieHandler.setCookie(prequest, presponse);

    if (pauthentication.isAuthenticated()) {
        presponse.setStatus(HttpServletResponse.SC_OK);
        LOGGER.info("User is authenticated!");
        LOGGER.debug(pauthentication.toString());

        final PrintWriter writer = presponse.getWriter();
        this.mapper.writeValue(writer,
                this.userDetailsConverter.convert((UserDetails) pauthentication.getPrincipal()));
        writer.flush();//from  w  ww.  j ava2s.  com
    } else {
        presponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}

From source file:core.NiprSyncController.java

@RequestMapping(value = "/authorize", method = RequestMethod.POST)
public void authorize(@RequestBody AuthRequest request, HttpServletResponse response) {
    String s = request.getUsername() + ":" + request.getPassword();
    byte[] encodedBytes = org.apache.tomcat.util.codec.binary.Base64.encodeBase64(s.getBytes());
    String lAuthHeader = "Basic " + new String(encodedBytes);

    if (Configuration.IsAuthenticated(lAuthHeader)) {
        response.setStatus(HttpServletResponse.SC_OK);
    } else {/*ww w.  ja v a  2  s  . c  o  m*/
        System.out.println("Authentication Failed");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}

From source file:net.longfalcon.web.WebExceptionHandlerResolver.java

private ModelAndView handlePermissionDenied(PermissionDeniedException ex, HttpServletRequest request,
        HttpServletResponse response, Object handler) throws IOException {
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    _log.error(ex, ex);//from w w  w.  j  a  v a 2  s.  co  m
    return new ModelAndView();
}

From source file:de.logicline.splash.controller.UserController.java

/**
 * user login without captcha verification
 * needs configured heroku connector add on
 * returns specific error if auth failed or config not done
 * /*from   www .  j  av  a 2  s .com*/
 * @param userEntity credentials from the web client
 * @param response
 * 
 * @return
 */
@RequestMapping(value = "/user/login", method = RequestMethod.POST)
public @ResponseBody Map<String, String> userLogin(@RequestBody final UserEntity userEntity,
        HttpServletResponse response) {
    UserEntity userEntityTmp = userService.getUserByName(userEntity.getUsername());

    if (userEntityTmp == null || !BCrypt.checkpw(userEntity.getPassword(), userEntityTmp.getPassword())) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return null;
    }

    Map<String, String> responseMap = new HashMap<String, String>();
    String token = userEntityTmp.getToken();
    responseMap.put("token", token);
    responseMap.put("userId", String.valueOf(userEntityTmp.getUserId()));
    responseMap.put("role", userEntityTmp.getRole());

    try {
        ContactEntity contactEntity = userService.getContact(token);
        if (contactEntity != null) {
            responseMap.put("firstName", contactEntity.getFirstName());
            responseMap.put("lastName", contactEntity.getLastName());
        }
    } catch (Exception e) {
        LOGGER.error("Exception during getContact()", e);
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return null;
    }

    return responseMap;
}

From source file:StudentsUpdate.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request// w w  w.j  av  a2  s.c  o  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String a = request.getParameter("students");
    String class1 = request.getParameter("class");
    String hour = request.getParameter("hour");
    String name;
    HttpSession session = request.getSession(false);
    if (session != null) {
        name = (String) session.getAttribute("name");
        PrintWriter out = response.getWriter();
        getStud(a);
        util.toDatabase(stud, pa, class1, hour);
        out.println(a);
    } else {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        System.out.println("not auth");
    }

}

From source file:com.androgogic.AikauLoginController.java

/**
 * Overrides the default behaviour to return a simple JSON response. 
 * /*  w w w . j  a va2 s. co  m*/
 * @param request The {@link HttpServletRequest}
 * @param response The {@link HttpServletResponse}
 * @throws Exception
 */
@Override
protected void onFailure(HttpServletRequest request, HttpServletResponse response) throws Exception {
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}

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

@RequestMapping(method = RequestMethod.GET, value = "/app/public/notification/{capp:.*}")
public @ResponseBody Notifications getPublicNotificationsByApp(HttpServletRequest request,
        HttpServletResponse response, HttpSession session, @RequestParam("since") Long since,
        @RequestParam("position") Integer position, @RequestParam("count") Integer count,
        @PathVariable("capp") String capp) throws DataException, IOException, SmartCampusException {

    if (capp == null) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return null;
    }/* www.  j  a v a2 s.  c  om*/

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

    return result;
}