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.concursive.connect.web.webdav.WebdavManager.java

public static void askForAuthentication(HttpServletResponse res) throws Exception {
    String nonce = DefaultServlet.generateNonce();
    // determine the 'opaque' value which should be returned as-is by the client
    String opaque = DefaultServlet.generateOpaque();
    res.setHeader("WWW-Authenticate", "Digest realm=\"" + WebdavServlet.USER_REALM + "\", " + "nonce=\"" + nonce
            + "\", " + "opaque=\"" + opaque + "\"");
    res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
}

From source file:com.google.gsa.valve.modules.krb.KerberosAuthenticationProcess.java

/**
 *  It does the Kerberos authentication using the negotiation way. It 
 *  establishes a negotiation with the browser sending HTTP error messages.
 *  /*from w ww  . j  a  v a  2s.  c  o m*/
 * @param request HTTP request
 * @param response HTTP response
 * 
 * @return the method result in HTTP error format
 */
public int authNegotiate(HttpServletRequest request, HttpServletResponse response) {
    //Implement Kerberos negotiatiation and authentication

    int result = HttpServletResponse.SC_UNAUTHORIZED;

    //read Authorization header
    boolean isAuthorization = false;

    //reset challenge
    challenge = null;

    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = (String) headerNames.nextElement();
        if (headerName.toLowerCase().equals(HEADER_AUTHORIZATION)) {
            isAuthorization = true;
            challenge = request.getHeader(headerName);
            logger.debug("Authorization header read: " + challenge);
            break;
        }
    }

    // Instantiate the authentication process class
    try {

        //Check if the header sent by the client is Authorization or not
        if (!isAuthorization) {
            logger.debug("Sending.... " + HEADER_WWW_AUTHENTICATE);

            response.addHeader(HEADER_WWW_AUTHENTICATE, NEG_TOKEN);

            // Return
            return HttpServletResponse.SC_UNAUTHORIZED;
        } else {
            if (challenge == null) {

                // Log error
                logger.error("The browser did not send the challenge properly");

                // Return
                return HttpServletResponse.SC_INTERNAL_SERVER_ERROR;

            }
        }

        //Check if serverCreds and subject are properly set                    
        if ((serverCreds == null) || (serverSubject == null)) {

            // Log error
            logger.error("The GSA authentication servlet cannot get Server credentials");

            // Return
            return HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        }

        //Initialize Spnego server
        spnegoServer = new GssSpNegoServer(serverCreds, spnegoAuth.getManager(), serverSubject);

        boolean isComplete = false;

        try {
            isComplete = spnegoServer.processSpNego(challenge);
            logger.debug("isComplete? " + isComplete);

            if (!isComplete) {
                logger.debug("Sending.... " + HEADER_WWW_AUTHENTICATE);
                // Raise error
                response.addHeader(HEADER_WWW_AUTHENTICATE, NEG_TOKEN + " " + spnegoServer.getResponseToken());

                return HttpServletResponse.SC_UNAUTHORIZED;
            } else {
                if (spnegoServer.isFailed()) {
                    logger.error("Error during the negotiation process");

                    return HttpServletResponse.SC_UNAUTHORIZED;
                } else { //Negotiation result is OK

                    //Add cookies before returning

                    //Get client subject
                    userSubject = spnegoServer.getClientSubject();

                    //Preparing Unique id
                    username = getPrincipalStr(userSubject);
                    id = username;

                    logger.debug("username is ... " + id);

                    result = HttpServletResponse.SC_OK;

                }
            }

        } catch (Exception ex) {
            logger.error("Exception during the negotiation: " + ex.getMessage(), ex);
            return HttpServletResponse.SC_UNAUTHORIZED;
        } finally {
        }

    } catch (Exception e) {

        // Log error
        logger.error("Exception during the negotiation: " + e.getMessage(), e);

        return HttpServletResponse.SC_UNAUTHORIZED;
    }

    return result;
}

From source file:com.sun.syndication.propono.atom.server.AtomServlet.java

/**
 * Handle Atom DELETE by calling appropriate handler.
 *//*from w w w .  ja va 2  s.c  o  m*/
protected void doDelete(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    log.debug("Entering");
    AtomHandler handler = createAtomRequestHandler(req, res);
    String userName = handler.getAuthenticatedUsername();
    if (userName != null) {
        AtomRequest areq = new AtomRequestImpl(req);
        try {
            if (handler.isEntryURI(areq)) {
                handler.deleteEntry(areq);
                res.setStatus(HttpServletResponse.SC_OK);
            } else {
                res.setStatus(HttpServletResponse.SC_NOT_FOUND);
            }
        } catch (AtomException ae) {
            res.sendError(ae.getStatus(), ae.getMessage());
            log.debug("ERROR processing DELETE", ae);
        } catch (Exception e) {
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
            log.debug("ERROR processing DELETE", e);
        }
    } else {
        res.setHeader("WWW-Authenticate", "BASIC realm=\"AtomPub\"");
        // Wanted to use sendError() here but Tomcat sends 403 forbidden 
        // when I do that, so sticking with setStatus() for time being.
        res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
    log.debug("Exiting");
}

From source file:edu.stanford.epad.epadws.handlers.HandlerUtil.java

public static int invalidTokenJSONResponse(String message, PrintWriter responseStream, EPADLogger log) {
    return warningJSONResponse(HttpServletResponse.SC_UNAUTHORIZED, message, responseStream, log);
}

From source file:eu.trentorise.smartcampus.mobility.controller.rest.JourneyPlannerController.java

@RequestMapping(method = RequestMethod.POST, value = "/recurrent")
public @ResponseBody BasicRecurrentJourney saveRecurrentJourney(HttpServletResponse response,
        @RequestBody(required = false) BasicRecurrentJourney recurrent) throws Exception {
    try {/*from w  w  w . jav a 2s  .com*/
        String userId = getUserId();
        if (userId == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return null;
        }
        logger.info("-" + userId + "~AppConsume~monitor");

        String clientId = recurrent.getClientId();

        if (clientId == null) {
            clientId = new ObjectId().toString();
        } else {
            Map<String, Object> pars = new TreeMap<String, Object>();
            pars.put("clientId", clientId);
            RecurrentJourneyObject res = domainStorage.searchDomainObject(pars, RecurrentJourneyObject.class);

            if (res != null && !userId.equals(res.getUserId())) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return null;
            }
        }

        RecurrentJourneyObject rec = new RecurrentJourneyObject();
        rec.setData(recurrent.getData());
        rec.setName(recurrent.getName());
        rec.setUserId(userId);
        rec.setMonitor(recurrent.isMonitor());
        rec.setClientId(clientId);
        if (recurrent.getAppId() == null || recurrent.getAppId().isEmpty()) {
            rec.setAppId(NotificationHelper.MS_APP);
        } else {
            rec.setAppId(recurrent.getAppId());
        }

        domainStorage.saveRecurrent(rec);

        recurrent.setClientId(clientId);
        return recurrent;
    } catch (Exception e) {
        e.printStackTrace();
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    return null;
}

From source file:edu.stanford.epad.epadws.handlers.HandlerUtil.java

public static int invalidTokenJSONResponse(String message, EPADLogger log) {
    return warningJSONResponse(HttpServletResponse.SC_UNAUTHORIZED, message, log);
}

From source file:edu.stanford.epad.epadws.handlers.HandlerUtil.java

public static int invalidTokenResponse(String message, PrintWriter responseStream, EPADLogger log) {
    return warningResponse(HttpServletResponse.SC_UNAUTHORIZED, message, responseStream, log);
}

From source file:com.almende.eve.transport.http.AgentServlet.java

/**
 * Delete an agent usage: DELETE /servlet/agentId.
 * //from w ww .  j  a v a2s.c  om
 * @param req
 *            the req
 * @param resp
 *            the resp
 * @throws ServletException
 *             the servlet exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@Override
protected void doDelete(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    final String agentUrl = req.getRequestURI();
    String agentId;
    try {
        agentId = httpTransport.getAgentId(new URI(agentUrl));
    } catch (URISyntaxException e) {
        throw new ServletException(AGENTURLWARNING, e);
    }

    if (!handleSession(req, resp)) {
        if (!resp.isCommitted()) {
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
        return;
    }
    if (agentId == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "No agentId found in url.");
        return;
    }

    try {
        host.deleteAgent(agentId);
        resp.getWriter().write("Agent " + agentId + " deleted");
    } catch (final Exception e) {
        throw new ServletException(e);
    }
}

From source file:net.shibboleth.idp.authn.spnego.impl.SPNEGOAuthnController.java

/**
 * Send back a Negotiate challenge token.
 * /* w  w  w.  jav a  2 s.c om*/
 * @param profileRequestContext profile request context
 * @param httpRequest servlet request
 * @param httpResponse servlet response
 * @param base64Token challenge token to send back
 * 
 * @return a {@link ModelAndView} wrapping the response
 */
@Nonnull
private ModelAndView replyUnauthorizedNegotiate(@Nonnull final ProfileRequestContext profileRequestContext,
        @Nonnull final HttpServletRequest httpRequest, @Nonnull final HttpServletResponse httpResponse,
        @Nonnull final String base64Token) {

    final StringBuilder authenticateHeader = new StringBuilder("Negotiate");
    if (!base64Token.isEmpty()) {
        authenticateHeader.append(" " + base64Token);
    }
    httpResponse.addHeader(HttpHeaders.WWW_AUTHENTICATE, authenticateHeader.toString());
    httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    return createModelAndView(profileRequestContext, httpRequest, httpResponse);
}

From source file:org.openremote.modeler.service.impl.TemplateServiceImpl.java

public List<Template> getTemplates(boolean fromPrivate) {
    String shared = fromPrivate ? "private" : "public";
    List<Template> templates = new ArrayList<Template>();
    String restURL = configuration.getBeehiveRESTRootUrl() + "account/" + userService.getAccount().getOid()
            + "/templates/" + shared;

    HttpGet httpGet = new HttpGet(restURL);
    httpGet.setHeader("Accept", "application/json");
    this.addAuthentication(httpGet);
    HttpClient httpClient = new DefaultHttpClient();

    try {/* w ww . j  av a  2s  .  c o  m*/
        HttpResponse response = httpClient.execute(httpGet);

        if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) {
            if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_UNAUTHORIZED) {
                throw new NotAuthenticatedException(
                        "User " + userService.getCurrentUser().getUsername() + " not authenticated! ");
            }
            throw new BeehiveNotAvailableException("Beehive is not available right now! ");
        }

        InputStreamReader reader = new InputStreamReader(response.getEntity().getContent());
        BufferedReader buffReader = new BufferedReader(reader);
        StringBuilder sb = new StringBuilder();
        String line = "";

        while ((line = buffReader.readLine()) != null) {
            sb.append(line);
            sb.append("\n");
        }

        String result = sb.toString();
        TemplateList templateList = buildTemplateListFromJson(result);
        List<TemplateDTO> dtoes = templateList.getTemplates();

        for (TemplateDTO dto : dtoes) {
            templates.add(dto.toTemplate());
        }
    } catch (IOException e) {
        throw new BeehiveNotAvailableException(
                "Failed to get template list, The beehive is not available right now ", e);
    }

    return templates;
}