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.climate.oada.security.RestAuthenticationEntryPoint.java

@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException {
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}

From source file:org.sventon.web.AbstractHttpAuthenticationHandlerTest.java

@Test
public void testSendChallenge() throws Exception {
    final MockHttpServletResponse response = new MockHttpServletResponse();
    handler.sendChallenge(response);/*from   w ww  . j ava2s .co  m*/
    assertEquals("basic realm=\"realm\"",
            response.getHeader(AbstractHttpAuthenticationHandler.AUTHENTICATE_HEADER));
    assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
}

From source file:com.tce.oauth2.spring.client.filters.SessionDataFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;

    // Todo Controller is not authorized for anonymous user
    if (req.getRequestURI().indexOf("/todos") != -1) {
        if (req.getSession().getAttribute("username") == null) {
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
        } else {/* w ww.ja v a2  s  .co m*/
            filterChain.doFilter(request, response);
        }
    } else {
        filterChain.doFilter(request, response);
    }
}

From source file:com.telefonica.euro_iaas.paasmanager.rest.auth.RestAuthenticationEntryPoint.java

/**
 * (non-Javadoc).//from w  ww  .  jav a 2  s  . c om
 * 
 * @see org.springframework.security.web.AuthenticationEntryPoint#commence(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse,
 *      org.springframework.security.core.AuthenticationException)
 */
public final void commence(final HttpServletRequest request, final HttpServletResponse response,
        final AuthenticationException authException) throws IOException, ServletException {

    // if (authException instanceof AuthenticationServiceException) {
    // LOG.error(authException);
    // response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
    // authException.getMessage());
    // }

    if (authException instanceof InsufficientAuthenticationException) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
    } else {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
    }
}

From source file:net.lr.jmsbridge.BridgeServlet.java

/**
 * Forward HTTP request to a jms queue and listen on a temporary queue for the reply.
 * Connects to the jms server by using the username and password from the HTTP basic auth.
 *//* ww w . j  ava  2 s. c om*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String authHeader = req.getHeader("Authorization");
    if (authHeader == null) {
        resp.setHeader("WWW-Authenticate", "Basic realm=\"Bridge\"");
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "auth");
        return;
    }
    UserNameAndPassword auth = extractUserNamePassword(authHeader);
    PrintStream out = new PrintStream(resp.getOutputStream());
    String contextPath = req.getContextPath();
    String uri = req.getRequestURI();
    String queueName = uri.substring(contextPath.length() + 1);
    final StringBuffer reqContent = retrieveRequestContent(req.getReader());

    ConnectionFactory cf = connectionPool.getConnectionFactory(auth);
    JmsTemplate jmsTemplate = new JmsTemplate();
    jmsTemplate.setConnectionFactory(cf);
    jmsTemplate.setReceiveTimeout(10000);
    final Destination replyDest = connectionPool.getReplyDestination(cf, auth);
    jmsTemplate.send(queueName, new MessageCreator() {

        @Override
        public Message createMessage(Session session) throws JMSException {
            TextMessage message = session.createTextMessage(reqContent.toString());
            message.setJMSReplyTo(replyDest);
            return message;
        }

    });
    Message replyMsg = jmsTemplate.receive(replyDest);
    if (replyMsg instanceof TextMessage) {
        TextMessage replyTMessage = (TextMessage) replyMsg;
        try {
            out.print(replyTMessage.getText());
        } catch (JMSException e) {
            JmsUtils.convertJmsAccessException(e);
        }
    }
}

From source file:com.mirth.connect.server.servlets.ChannelStatusServlet.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  ava2  s .  com
        try {
            ChannelStatusController channelStatusController = ControllerFactory.getFactory()
                    .createChannelStatusController();
            ObjectXMLSerializer serializer = new ObjectXMLSerializer();
            PrintWriter out = response.getWriter();
            Operation operation = Operations.getOperation(request.getParameter("op"));
            String channelId = request.getParameter("id");
            Map<String, Object> parameterMap = new HashMap<String, Object>();
            parameterMap.put("channelId", channelId);

            if (operation.equals(Operations.CHANNEL_START)) {
                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    channelStatusController.startChannel(channelId);
                }
            } else if (operation.equals(Operations.CHANNEL_STOP)) {
                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    channelStatusController.stopChannel(channelId);
                }
            } else if (operation.equals(Operations.CHANNEL_PAUSE)) {
                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    channelStatusController.pauseChannel(channelId);
                }
            } else if (operation.equals(Operations.CHANNEL_RESUME)) {
                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    channelStatusController.resumeChannel(channelId);
                }
            } else if (operation.equals(Operations.CHANNEL_GET_STATUS)) {
                response.setContentType(APPLICATION_XML);
                List<ChannelStatus> channelStatuses = null;

                if (!isUserAuthorized(request, null)) {
                    channelStatuses = new ArrayList<ChannelStatus>();
                } else if (doesUserHaveChannelRestrictions(request)) {
                    channelStatuses = redactChannelStatuses(request,
                            channelStatusController.getChannelStatusList());
                } else {
                    channelStatuses = channelStatusController.getChannelStatusList();
                }

                serializer.toXML(channelStatuses, out);
            }
        } catch (RuntimeIOException rio) {
            logger.debug(rio);
        } catch (Throwable t) {
            logger.error(ExceptionUtils.getStackTrace(t));
            throw new ServletException(t);
        }
    }
}

From source file:com.mirth.connect.server.servlets.CodeTemplateServlet.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 w ww.  jav a  2 s.c  o m*/
        try {
            CodeTemplateController codeTemplateController = ControllerFactory.getFactory()
                    .createCodeTemplateController();
            ObjectXMLSerializer serializer = new ObjectXMLSerializer();
            PrintWriter out = response.getWriter();
            Operation operation = Operations.getOperation(request.getParameter("op"));
            Map<String, Object> parameterMap = new HashMap<String, Object>();

            if (operation.equals(Operations.CODE_TEMPLATE_GET)) {
                CodeTemplate codeTemplate = (CodeTemplate) serializer
                        .fromXML(request.getParameter("codeTemplate"));
                parameterMap.put("codeTemplate", codeTemplate);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    response.setContentType(APPLICATION_XML);
                    serializer.toXML(codeTemplateController.getCodeTemplate(codeTemplate), out);
                }
            } else if (operation.equals(Operations.CODE_TEMPLATE_UPDATE)) {
                List<CodeTemplate> codeTemplates = (List<CodeTemplate>) serializer
                        .fromXML(request.getParameter("codeTemplates"));
                parameterMap.put("codeTemplates", codeTemplates);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    codeTemplateController.updateCodeTemplates(codeTemplates);
                }
            } else if (operation.equals(Operations.CODE_TEMPLATE_REMOVE)) {
                CodeTemplate codeTemplate = (CodeTemplate) serializer
                        .fromXML(request.getParameter("codeTemplate"));
                parameterMap.put("codeTemplate", codeTemplate);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    codeTemplateController.removeCodeTemplate(codeTemplate);
                }
            }
        } catch (RuntimeIOException rio) {
            logger.debug(rio);
        } catch (Throwable t) {
            logger.error(ExceptionUtils.getStackTrace(t));
            throw new ServletException(t);
        }
    }
}

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

@Test
public void testCommenceWithEmptyAccept() throws Exception {
    entryPoint.commence(request, response, new BadCredentialsException("Bad"));
    assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
    assertEquals("Bad", response.getErrorMessage());
}

From source file:com.mirth.connect.server.servlets.DatabaseTaskServlet.java

@Override
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 {/* ww  w .  ja v a2s  .  c  o m*/
        try {
            DatabaseTaskController databaseTaskController = ControllerFactory.getFactory()
                    .createDatabaseTaskController();
            ObjectXMLSerializer serializer = ObjectXMLSerializer.getInstance();
            PrintWriter out = response.getWriter();
            Operation operation = Operations.getOperation(request.getParameter("op"));
            Map<String, Object> parameterMap = new HashMap<String, Object>();
            ServerEventContext context = new ServerEventContext();
            context.setUserId(getCurrentUserId(request));

            if (operation.equals(Operations.DATABASE_TASKS_GET)) {
                if (!isUserAuthorized(request, null)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    serializer.serialize(databaseTaskController.getDatabaseTasks(), out);
                }
            } else if (operation.equals(Operations.DATABASE_TASK_RUN)) {
                DatabaseTask databaseTask = serializer
                        .deserialize((String) request.getParameter("databaseTask"), DatabaseTask.class);
                parameterMap.put("databaseTask", databaseTask);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    String result = databaseTaskController.runDatabaseTask(databaseTask);
                    if (StringUtils.isNotBlank(result)) {
                        out.write(result);
                    }
                }
            } else if (operation.equals(Operations.DATABASE_TASK_CANCEL)) {
                DatabaseTask databaseTask = serializer
                        .deserialize((String) request.getParameter("databaseTask"), DatabaseTask.class);
                parameterMap.put("databaseTask", databaseTask);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    databaseTaskController.cancelDatabaseTask(databaseTask);
                }
            }
        } catch (RuntimeIOException rio) {
            logger.debug(rio);
        } catch (Throwable t) {
            logger.error(ExceptionUtils.getStackTrace(t));
            throw new ServletException(t);
        }
    }
}

From source file:edu.chalmers.dat076.moviefinder.filter.UserFilter.java

@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
        throws ServletException, IOException {
    HttpSession session = req.getSession(true);
    String path = req.getRequestURI().substring(req.getContextPath().length());

    Object o = session.getAttribute("user");

    if (o == null) {
        if (path.toLowerCase().startsWith("/api/login/login")) {
            chain.doFilter(req, res);/*  www . j a va 2  s  .  c o m*/
            return;
        } else if (path.toLowerCase().startsWith("/api/")) {
            res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        } else {
            chain.doFilter(req, res);
            return;
        }
    }

    User u = (User) o;
    if (path.toLowerCase().startsWith("/api/admin") && u.getRole() != UserRole.ADMIN) {
        res.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    chain.doFilter(req, res);
}