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.pearson.developer.xapi.proxy.SSOServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {/*from  w ww  .j  av a2s  .c o  m*/
        // verify consumer key
        String ltiKey = this.getInitParameter("ltiConsumerKey");
        if (!ltiKey.equals(request.getParameter("oauth_consumer_key"))) {
            // TODO - consider redirecting to launch_presentation_return_url if present
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
            return;
        }

        // verify SSO with Basic LTI
        String ssoEndpoint = request.getRequestURL().toString(); // TODO - better to use parameter?
        String ltiSecret = this.getInitParameter("ltiSharedSecret");
        LtiVerificationResult ltiResult = BasicLTIUtil.validateMessage(request, ssoEndpoint, ltiSecret);
        if (!ltiResult.getSuccess()) {
            // TODO - consider redirecting to launch_presentation_return_url if present
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
            return;
        }

        // load the parameters 
        String activityProvider = request.getParameter("custom_xapi_ap_url");
        String email = request.getParameter("lis_person_contact_email_primary");
        String fullName = request.getParameter("lis_person_name_full");
        String userId = request.getParameter("user_id");

        // validate the incoming data has the expected data
        if (activityProvider == null || activityProvider.trim().length() == 0 || email == null
                || email.trim().length() == 0 || fullName == null || fullName.trim().length() == 0
                || userId == null || userId.trim().length() == 0) {
            // TODO - consider redirecting to launch_presentation_return_url if present
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Missing Data");
            return;
        }

        // the parameter is passed double encoded, so decode it once more.
        activityProvider = URLDecoder.decode(activityProvider, "UTF-8");

        // validate the incoming data is valid
        try {
            // userId is expected to be numeric for LearningStudio (TODO - change accordingly)
            Long.parseLong(userId);

            // activity provider url must be valid
            UrlValidator urlValidator = new UrlValidator(new String[] { "http", "https" });
            if (!urlValidator.isValid(activityProvider))
                throw new RuntimeException();

            // learner email must be valid
            EmailValidator emailValidator = EmailValidator.getInstance();
            if (!emailValidator.isValid(email))
                throw new RuntimeException();

            // simple name validation (TODO - handle more complex names)
            if (!fullName.matches("[a-zA-Z .,-]+"))
                throw new RuntimeException();
        } catch (Exception e) {
            // TODO - consider redirecting to launch_presentation_return_url if present
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid Data");
            return;
        }

        // generate and save secret for session
        String sessionSecret = UUID.randomUUID().toString();
        SessionDatabase.save(userId, sessionSecret);

        // prepare auth for launch link
        String basicAuth = new String(Base64.encodeBase64((userId + ":" + sessionSecret).getBytes("UTF-8")),
                "UTF-8");
        basicAuth = URLEncoder.encode("Basic " + basicAuth, "UTF-8");

        // prepare endpoint for launch link
        String xapiEndpoint = ssoEndpoint.substring(0, ssoEndpoint.length() - request.getServletPath().length())
                + "/xapi";
        xapiEndpoint = URLEncoder.encode(xapiEndpoint, "UTF-8");

        // prepare actor for launch link
        String actor = "{\"mbox\":\"mailto:" + email + "\",\"name\":\"" + fullName
                + "\",\"objectType\":\"Agent\"}";
        actor = URLEncoder.encode(actor, "UTF-8");

        // append the appropriate first delimiter
        if (activityProvider.indexOf("?") == -1) {
            activityProvider += "?";
        } else {
            activityProvider += "&";
        }

        // add launch link parameters
        activityProvider += "auth=" + basicAuth;
        activityProvider += "&endpoint=" + xapiEndpoint;
        activityProvider += "&actor=" + actor;

        response.sendRedirect(activityProvider);
    } catch (Throwable t) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Server Error");
    }
}

From source file:waffle.spring.NegotiateSecurityFilterEntryPoint.java

@Override
public void commence(final HttpServletRequest request, final HttpServletResponse response,
        final AuthenticationException ex) throws IOException, ServletException {

    NegotiateSecurityFilterEntryPoint.LOGGER.debug("[waffle.spring.NegotiateEntryPoint] commence");

    if (this.provider == null) {
        throw new ServletException("Missing NegotiateEntryPoint.Provider");
    }/*from   w w w  .j  av  a2  s .  co m*/

    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    response.setHeader("Connection", "keep-alive");
    this.provider.sendUnauthorized(response);
    response.flushBuffer();
}

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

@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {
    response.addHeader("WWW-Authenticate", String.format("%s realm=\"%s\"", typeName, realmName));
    String accept = request.getHeader("Accept");
    boolean json = false;
    if (StringUtils.hasText(accept)) {
        for (MediaType mediaType : MediaType.parseMediaTypes(accept)) {
            if (mediaType.includes(MediaType.APPLICATION_JSON)) {
                json = true;/*  w w  w . j  a  va 2 s.  c om*/
                break;
            }
        }
    }
    if (json) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.getWriter().append(String.format("{\"error\":\"%s\"}", authException.getMessage()));
    } else {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage());
    }
}

From source file:com.mirth.connect.server.servlets.ChannelStatisticsServlet.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 .  ja  v a 2s.co m
        try {
            ChannelStatisticsController statisticsController = ControllerFactory.getFactory()
                    .createChannelStatisticsController();
            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_STATS_GET)) {
                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    response.setContentType(APPLICATION_XML);
                    serializer.toXML(statisticsController.getStatistics(channelId), out);
                }
            } else if (operation.equals(Operations.CHANNEL_STATS_CLEAR)) {
                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    boolean deleteReceived = Boolean.valueOf(request.getParameter("deleteReceived"));
                    boolean deleteFiltered = Boolean.valueOf(request.getParameter("deleteFiltered"));
                    boolean deleteQueued = Boolean.valueOf(request.getParameter("deleteQueued"));
                    boolean deleteSent = Boolean.valueOf(request.getParameter("deleteSent"));
                    boolean deleteErrored = Boolean.valueOf(request.getParameter("deleteErrored"));
                    boolean deleteAlerted = Boolean.valueOf(request.getParameter("deleteAlerted"));
                    statisticsController.clearStatistics(channelId, deleteReceived, deleteFiltered,
                            deleteQueued, deleteSent, deleteErrored, deleteAlerted);
                }
            }
        } 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.AlertServlet.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  .  ja  va  2s  .  co m
        try {
            AlertController alertController = ControllerFactory.getFactory().createAlertController();
            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.ALERT_GET)) {
                Alert alert = (Alert) serializer.fromXML(request.getParameter("alert"));
                parameterMap.put("alert", alert);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    response.setContentType(APPLICATION_XML);
                    serializer.toXML(alertController.getAlert(alert), out);
                }
            } else if (operation.equals(Operations.ALERT_UPDATE)) {
                List<Alert> alerts = (List<Alert>) serializer.fromXML(request.getParameter("alerts"));
                parameterMap.put("alerts", alerts);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    alertController.updateAlerts(alerts);
                }
            } else if (operation.equals(Operations.ALERT_REMOVE)) {
                Alert alert = (Alert) serializer.fromXML(request.getParameter("alert"));
                parameterMap.put("alert", alert);

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

From source file:com.kixeye.chassis.transport.http.HttpExceptionHandler.java

@ExceptionHandler(Exception.class)
@ResponseBody//  w  ww.ja  v  a  2s .  c  o  m
public ServiceError defaultErrorHandler(HttpServletRequest request, HttpServletResponse response, Exception ex)
        throws Exception {
    ServiceError error = ExceptionServiceErrorMapper.mapException(ex);

    switch (error.code) {
    case ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE:
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

        logger.error("Unexpected error", ex);
        break;
    case ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE:
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

        if (logger.isDebugEnabled()) {
            logger.debug("Validation exception", ex);
        }
        break;
    case ExceptionServiceErrorMapper.SECURITY_ERROR_CODE:
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        if (logger.isDebugEnabled()) {
            logger.debug("Security exception", ex);
        }
        break;
    default:
        if (ex instanceof HttpServiceException) {
            HttpServiceException httpEx = (HttpServiceException) ex;

            response.setStatus(httpEx.httpResponseCode);
        }

        logger.warn("Service exception", ex);
        break;
    }

    return error;
}

From source file:com.google.gwt.benchmark.dashboard.server.servlets.AddBenchmarkResultServlet.java

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    String auth = req.getHeader("auth");
    if (!authController.validateAuth(auth)) {
        resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return;/*w w  w  .ja va2 s . c  o  m*/
    }

    BenchmarkRunJson benchmarkRunJSON = null;
    String json = null;
    try {
        json = IOUtils.toString(req.getInputStream(), "UTF-8");
        AutoBean<BenchmarkRunJson> bean = AutoBeanCodex.decode(JsonFactory.get(), BenchmarkRunJson.class, json);
        benchmarkRunJSON = bean.as();
    } catch (Exception e) {
        logger.log(Level.WARNING, "Can not deserialize JSON", e);
        if (json != null) {
            logger.warning(json);
        }
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        resp.getWriter().write("Can't parse JSON, see App Engine log for details.");
        return;
    }

    try {

        benchmarkController.addBenchmarkResult(benchmarkRunJSON);
        resp.setStatus(HttpServletResponse.SC_OK);
    } catch (Exception e) {
        logger.log(Level.WARNING, "Can not add benchmark results", e);
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:org.smigo.message.MessageController.java

@RequestMapping(value = "/rest/message", produces = "application/json", method = RequestMethod.POST)
@ResponseBody/*  w  w  w.j ava 2s.  c  o m*/
public int addMessage(@RequestBody MessageAdd message, @AuthenticationPrincipal AuthenticatedUser user,
        HttpServletResponse response, Locale locale) {
    mailHandler.sendAdminNotification("message added to forum", message);
    if (user == null) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return 0;
    }
    return messageHandler.addMessage(message, user, locale);
}

From source file:com.blogspot.ryanfx.auth.GoogleUtil.java

/**
 * Sends the auth token to google and gets the json result.
 * @param token auth token/*from   ww  w .j  a  v  a2s .c o m*/
 * @return json result if valid request, null if invalid.
 * @throws IOException
 * @throws LoginException
 */
private static String issueTokenGetRequest(String token) throws IOException, LoginException {
    int timeout = 2000;
    URL u = new URL("https://www.googleapis.com/oauth2/v2/userinfo");
    HttpURLConnection c = (HttpURLConnection) u.openConnection();
    c.setRequestMethod("GET");
    c.setRequestProperty("Content-length", "0");
    c.setRequestProperty("Authorization", "OAuth " + token);
    c.setUseCaches(false);
    c.setAllowUserInteraction(false);
    c.setConnectTimeout(timeout);
    c.setReadTimeout(timeout);
    c.connect();
    int status = c.getResponseCode();
    if (status == HttpServletResponse.SC_OK) {
        BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();
        return sb.toString();
    } else if (status == HttpServletResponse.SC_UNAUTHORIZED) {
        Logger.getLogger(GoogleUtil.class.getName()).severe("Invalid token request: " + token);
    }
    return null;
}