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:io.github.howiefh.jeews.modules.oauth2.shiro.filter.TokenFilter.java

@Override
protected boolean onAccessDenied(ServletRequest req, ServletResponse resp) throws Exception {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;
    try {/*from www  . j  a  v a  2s  .  c  o m*/
        // OAuth?
        OAuthAccessResourceRequest oauthRequest = new OAuthAccessResourceRequest(request,
                ParameterStyle.HEADER);
        // ?Access Token
        String accessToken = oauthRequest.getAccessToken();

        // ?Access Token
        if (!oAuthService.checkAccessToken(accessToken)) {
            // ?/???
            OAuthResponse oauthResponse = OAuthRSResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
                    .setRealm(Constants.RESOURCE_SERVER_NAME)
                    .setError(OAuthError.ResourceResponse.INVALID_TOKEN).buildHeaderMessage();

            response.addHeader(OAuth.HeaderType.WWW_AUTHENTICATE,
                    oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        return true;
    } catch (OAuthProblemException e) {
        // ??
        String errorCode = e.getError();
        if (OAuthUtils.isEmpty(errorCode)) {
            OAuthResponse oauthResponse = OAuthRSResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
                    .setRealm(Constants.RESOURCE_SERVER_NAME).buildHeaderMessage();

            response.addHeader(OAuth.HeaderType.WWW_AUTHENTICATE,
                    oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        OAuthResponse oauthResponse = OAuthRSResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
                .setRealm(Constants.RESOURCE_SERVER_NAME).setError(e.getError())
                .setErrorDescription(e.getDescription()).setErrorUri(e.getUri()).buildHeaderMessage();

        response.addHeader(OAuth.HeaderType.WWW_AUTHENTICATE,
                oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return false;
    }

}

From source file:de.afbb.bibo.servlet.server.servlet.MainServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w  ww  . j av  a2s. co  m*/
 *
 * @param request
 *            servlet request
 * @param response
 *            servlet response
 * @throws NumberFormatException
 * @throws ServletException
 *             if a servlet-specific error occurs
 * @throws IOException
 *             if an I/O error occurs
 * @throws java.lang.InterruptedException
 * @throws org.apache.commons.fileupload.FileUploadException
 */
protected void processRequest(final HttpServletRequest request, final HttpServletResponse response)
        throws NumberFormatException, IOException {
    boolean valid = true;
    final String requestRoot = Utils.getRequestPart(request, 0);
    log.debug("entering MAIN Servlet...");

    if (!requestRoot.equals("/login")) {
        valid = SessionContainer.getInstance().validate(request.getHeader("sessionId"));
    }
    log.info("new request: " + request.getRequestURI());
    if (!valid) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    } else {

        response.setContentType("application/json");

        try {
            switch (requestRoot) {
            case "/login":
                new LoginServlet(request, response).processRequest();
                break;
            case "/user":
                new UserServlet(request, response).processRequest();
                break;
            case "/stock":
                new StockServlet(request, response).processRequest();
                break;
            case "/borrow":
                new BorrowServlet(request, response).processRequest();
                break;
            default:
                Utils.returnErrorMessage(MainServlet.class, request, response);
                break;
            }
        } catch (final SQLException | IOException e) {
            log.debug(e.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}

From source file:com.nec.harvest.security.HarvestLoginUrlAuthenticationEntryPoint.java

@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {
    if (isPreflight(request)) {
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } else if (isRestRequest(request)) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
    } else {//from   ww  w . j  a  va2 s.  c  o  m
        super.commence(request, response, authException);
    }
}

From source file:com.devicehive.websockets.WebSocketResponseBuilder.java

public JsonObject buildResponse(JsonObject request, WebSocketSession session) {
    JsonObject response;//from w w  w  . ja  v  a 2s .com
    try {
        response = requestProcessor.process(request, session).getResponseAsJson();
    } catch (BadCredentialsException ex) {
        logger.error("Unauthorized access", ex);
        response = JsonMessageBuilder
                .createErrorResponseBuilder(HttpServletResponse.SC_UNAUTHORIZED, "Invalid credentials").build();
    } catch (AccessDeniedException ex) {
        logger.error("Access to action is denied", ex);
        response = JsonMessageBuilder
                .createErrorResponseBuilder(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized").build();
    } catch (HiveException ex) {
        logger.error("Error executing the request", ex);
        response = JsonMessageBuilder.createError(ex).build();
    } catch (ConstraintViolationException ex) {
        logger.error("Error executing the request", ex);
        response = JsonMessageBuilder
                .createErrorResponseBuilder(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage()).build();
    } catch (org.hibernate.exception.ConstraintViolationException ex) {
        logger.error("Error executing the request", ex);
        response = JsonMessageBuilder
                .createErrorResponseBuilder(HttpServletResponse.SC_CONFLICT, ex.getMessage()).build();
    } catch (JsonParseException ex) {
        logger.error("Error executing the request", ex);
        response = JsonMessageBuilder.createErrorResponseBuilder(HttpServletResponse.SC_BAD_REQUEST,
                Messages.INVALID_REQUEST_PARAMETERS).build();
    } catch (OptimisticLockException ex) {
        logger.error("Error executing the request", ex);
        logger.error("Data conflict", ex);
        response = JsonMessageBuilder
                .createErrorResponseBuilder(HttpServletResponse.SC_CONFLICT, Messages.CONFLICT_MESSAGE).build();
    } catch (PersistenceException ex) {
        if (ex.getCause() instanceof org.hibernate.exception.ConstraintViolationException) {
            response = JsonMessageBuilder
                    .createErrorResponseBuilder(HttpServletResponse.SC_CONFLICT, ex.getMessage()).build();
        } else {
            response = JsonMessageBuilder
                    .createErrorResponseBuilder(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage())
                    .build();
        }
    } catch (Exception ex) {
        logger.error("Error executing the request", ex);
        response = JsonMessageBuilder
                .createErrorResponseBuilder(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage())
                .build();
    }

    return new JsonMessageBuilder().addAction(request.get(JsonMessageBuilder.ACTION))
            .addRequestId(request.get(JsonMessageBuilder.REQUEST_ID)).include(response).build();
}

From source file:org.openwms.client.security.UnauthorizedEntryPoint.java

/**
 * {@inheritDoc}//from www. j a v  a 2s  .c  o  m
 * 
 * On {@link AuthenticationException}s we always commence with an
 * {@value HttpServletResponse#SC_UNAUTHORIZED} code.
 * 
 * @see org.springframework.security.web.AuthenticationEntryPoint#commence(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse,
 *      org.springframework.security.core.AuthenticationException)
 */
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
            "Unauthorized: Authentication token was either missing or invalid.");
}

From source file:fr.treeptik.cloudunit.config.Http401EntryPoint.java

public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg)
        throws IOException, ServletException {

    // Maybe change the log level...
    log.warn("Access Denied [ " + request.getRequestURL().toString() + "] : " + arg.getMessage());

    // Trace message to ban intruders with fail2ban
    //generateLogTraceForFail2ban();

    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access unauthorized");
}

From source file:org.craftercms.security.authentication.impl.RestLoginFailureHandlerTest.java

@Test
public void testHandle() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/login.json");
    MockHttpServletResponse response = new MockHttpServletResponse();
    RequestContext context = new RequestContext(request, response);

    handler.handle(context, new BadCredentialsException(ERROR_MESSAGE));

    assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
    assertEquals(EXPECTED_RESPONSE_CONTENT, response.getContentAsString());
}

From source file:net.navasoft.madcoin.backend.services.security.CustomAuthenticationEntryPoint.java

/**
 * Commence./*  ww  w.ja va 2s . c  o  m*/
 * 
 * @param request
 *            the request
 * @param response
 *            the response
 * @param authException
 *            the auth exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws ServletException
 *             the servlet exception
 * @since 27/07/2014, 06:48:55 PM
 */
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {
    System.out.println("Entra...");
    System.out.println(request.getParameterMap());
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
            "Unauthorized: Authentication token was either missing or invalid.");
}

From source file:com.mirth.connect.server.servlets.EngineServlet.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  . j a  va  2  s  .  c om
        try {
            EngineController engineController = ControllerFactory.getFactory().createEngineController();
            ObjectXMLSerializer serializer = new ObjectXMLSerializer();
            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.CHANNEL_REDEPLOY)) {
                if (!isUserAuthorized(request, null) || doesUserHaveChannelRestrictions(request)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    engineController.redeployAllChannels(context);
                }
            } else if (operation.equals(Operations.CHANNEL_DEPLOY)) {
                List<String> channelIds = (List<String>) serializer.fromXML(request.getParameter("channelIds"));
                parameterMap.put("channelIds", channelIds);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    engineController.deployChannels(channelIds, context);
                }
            } else if (operation.equals(Operations.CHANNEL_UNDEPLOY)) {
                List<String> channelIds = (List<String>) serializer.fromXML(request.getParameter("channelIds"));
                parameterMap.put("channelIds", channelIds);

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

From source file:org.craftercms.security.authentication.impl.RestAuthenticationRequiredHandlerTest.java

@Test
public void testHandle() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/profile.json");
    MockHttpServletResponse response = new MockHttpServletResponse();
    RequestContext context = new RequestContext(request, response);

    handler.handle(context, new AuthenticationRequiredException(ERROR_MESSAGE));

    assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
    assertEquals(EXPECTED_RESPONSE_CONTENT, response.getContentAsString());
}