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.sonicle.webtop.core.app.shiro.WTFormAuthFilter.java

@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
    String ctxRequestUrl = ServletUtils.getContextRequestURI((HttpServletRequest) request);
    if (StringUtils.startsWithIgnoreCase(ctxRequestUrl, PrivateRequest.URL)
            || StringUtils.startsWithIgnoreCase(ctxRequestUrl, PrivateRequest.URL_LEGACY) // for compatibility purpose only!
            || StringUtils.startsWithIgnoreCase(ctxRequestUrl, PushEndpoint.URL)) {
        ServletUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
        return false;
    } else {//from   www.  j  a  v  a 2  s.com
        return super.onAccessDenied(request, response);
    }
}

From source file:com.adito.security.AbstractHTTPAuthenticationModule.java

/**
 * @param request//from  www  . j a  v  a2s  .c  o  m
 * @param response
 * @param realm
 * @throws IOException
 */
public static void sendAuthorizationError(HttpServletRequest request, HttpServletResponse response,
        String realm) throws IOException {
    if (log.isInfoEnabled())
        log.info("Sending auth request for realm " + realm);
    response.setHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\"");
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    request.getSession().setAttribute(Constants.AUTH_SENT, Boolean.TRUE);
}

From source file:com.haulmont.cuba.restapi.LoginServiceController.java

protected void doLogin(String username, String password, String localeStr, HttpServletRequest request,
        HttpServletResponse response) throws IOException, JSONException {
    Locale locale = localeFromString(localeStr);

    AuthenticationService authenticationService = AppBeans.get(AuthenticationService.NAME);
    try {//from w ww .ja  v a 2s.c om
        AbstractClientCredentials credentials = new LoginPasswordCredentials(username,
                passwordEncryption.getPlainHash(password), locale);
        UserSession userSession = authenticationService.login(credentials).getSession();

        if (!userSession.isSpecificPermitted(Authentication.PERMISSION_NAME)) {
            log.info(String.format("User %s is not allowed to use REST-API", username));
            AppContext.setSecurityContext(new SecurityContext(userSession));
            try {
                authenticationService.logout();
            } finally {
                AppContext.setSecurityContext(null);
            }
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        try {
            AppContext.setSecurityContext(new SecurityContext(userSession));
            setSessionInfo(request, userSession);
        } finally {
            AppContext.setSecurityContext(null);
        }

        response.setStatus(HttpServletResponse.SC_OK);
        PrintWriter writer = new PrintWriter(
                new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8));
        writer.write(userSession.getId().toString());
        writer.close();

        log.debug(String.format("User %s logged in with REST-API, session id: %s", username,
                userSession.getId()));
    } catch (LoginException e) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
}

From source file:org.drugis.addis.config.SecurityConfig.java

@Bean
public AuthenticationEntryPoint unauthorizedEntryPoint() {
    return (request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
}

From source file:nc.noumea.mairie.organigramme.core.authentification.AuthentificationFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    /* Cast des objets request et response */
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    HttpSession hSess = ((HttpServletRequest) request).getSession();

    // Hack pour pouvoir rcuprer les images sur la page de connexion
    if (request.getRequestURI().contains("imgs")) {
        chain.doFilter(request, response);
        return;//  w ww.  j a  v a  2  s. c o m
    }

    // on laisse passer pour le rproxy et ainsi permettre de deployer l
    // application sur le 2e noeud tomcat
    if (PAGES_STATIQUES.contains(request.getServletPath())) {
        chain.doFilter(request, response);
        return;
    }

    if (null != hSess.getAttribute("logout")) {
        if (!request.getRequestURI().contains("zkau") && !request.getRequestURI().contains("login.zul")
                && !request.getRequestURI().contains("css")) {

            // dans le cas ou la personne a clique sur ce deconnecte et ne
            // ferme pas le navigateur
            LOGGER.debug("User disconnect");
            hSess.setAttribute("logout", "logout");
            request.getRequestDispatcher("login.zul").forward(request, response);
            return;
        }
        chain.doFilter(request, response);
        return;
    }

    if (null != hSess.getAttribute("currentUser")) {
        chain.doFilter(request, response);
        return;
    }

    if ((null == request.getHeader("x-krb_remote_user")
            || "".equals(request.getHeader("x-krb_remote_user").trim()))) {
        LOGGER.debug("x-krb_remote_user is NULL");
        // hSess.invalidate();
        // request.logout();
        // response.sendError(HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED,
        // "You are logged out.");
        // #15803
        hSess.setAttribute("logout", "logout");
        request.getRequestDispatcher("login.zul").forward(request, response);
        return;
    }

    String remoteUser = request.getHeader("x-krb_remote_user");

    remoteUser = convertRemoteUser(remoteUser);

    LightUserDto userDto = radiWSConsumer.getAgentCompteADByLogin(remoteUser);
    if (null == userDto) {
        LOGGER.debug("User not exist in Radi WS with RemoteUser : " + remoteUser);
        // request.logout();

        hSess.setAttribute("logout", "logout");
        request.getRequestDispatcher("login.zul").forward(request, response);
        return;
    }

    if (0 == userDto.getEmployeeNumber()) {
        LOGGER.debug("User not exist in Radi WS with RemoteUser : " + remoteUser);

        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                "Vous n'tes pas un agent de la mairie, vous n'tes pas autoris  accder  cette application.");
        return;
    }

    ProfilAgentDto profilAgent = recupereProfilAgent(request, userDto.getEmployeeNumber());
    if (profilAgent == null) {
        return;
    }

    AccessRightOrganigrammeDto accessRightOrganigrammeDto = recupereAccessRightOrganigramme(request,
            userDto.getEmployeeNumber());
    if (accessRightOrganigrammeDto == null || accessRightOrganigrammeDto.isAucunRole()) {
        hSess.setAttribute("logout", "logout");
        request.getRequestDispatcher("login.zul").forward(request, response);
        return;
    }

    renseigneAccessRightOnUser(profilAgent, accessRightOrganigrammeDto);

    hSess.setAttribute("currentUser", profilAgent);
    LOGGER.debug("Authentification du user ok : " + remoteUser);
    LOGGER.debug("Droits du user ok : " + accessRightOrganigrammeDto);

    chain.doFilter(request, response);
}

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

@RequestMapping(method = RequestMethod.PUT, value = "/app/{capp:.*}/notification/{id}")
public @ResponseBody void updateByApp(HttpServletRequest request, HttpServletResponse response,
        HttpSession session, @PathVariable("id") String id, @PathVariable("capp") String capp,
        @RequestBody Notification notification)
        throws DataException, IOException, NotFoundException, SmartCampusException {

    String userId = getUserId();/*from  w w w  . j a  v  a2s .  c  o  m*/
    if (userId == null) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }

    notificationManager.updateLabelsByApp(id, capp, notification.getLabelIds());
    notificationManager.starredByApp(id, capp, notification.isStarred());
}

From source file:de.mpg.escidoc.services.pidcache.web.MainServlet.java

private boolean authenticate(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String auth = request.getHeader("authorization");
    if (auth == null) {
        response.addHeader("WWW-Authenticate", "Basic realm=\"PID Cache\"");
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    } else {/*from   ww  w.  j  av a  2 s .  c  o  m*/
        auth = auth.substring(6);
        String cred = new String(Base64.decodeBase64(auth.getBytes()));
        if (cred.contains(":")) {

            String[] userPass = cred.split(":");
            String userName = PropertyReader.getProperty("escidoc.pidcache.user.name");
            String password = PropertyReader.getProperty("escidoc.pidcache.user.password");

            if (!userPass[0].equals(userName) || !userPass[1].equals(password)) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return false;
            } else {
                return true;
            }
        } else {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return false;
        }
    }
}

From source file:com.google.gsa.valve.rootAuth.RootAuthenticationProcess.java

/**
 * This is the main method that drives the whole authentication 
 * process. It launches each individual authentication method declared in 
 * the configuration files. Those that includes the tag "checkauthN" set to 
 * false are not processed./*from   w  w  w  .j a v  a2 s  . c o m*/
 * <p>
 * The name of the authentication classes that need to be processed are included 
 * in a vector that is reused multiple times. Whenever a new authentication 
 * process needs to be relaunched, all these classes are processed and the 
 * individual authentication process is treated.
 * <p>
 * It returns the HTTP error code associated to the process result. If it was 
 * OK, this methods returns a 200 and 401 (unauthorized) otherwise.
 * <p>
 * There is a special repository named "root" that is treatly in a special way. 
 * If any repository is named as "root", it means this is the main authentication 
 * mechanim and that's why it's trated first. If it fails, the authentication 
 * process stops here and the return result is an error. If not, the whole 
 * processing continues.
 * <p>
 * If there is a "root" repository and the authentication process for this 
 * repository is OK, although any other repository would fail, the overall 
 * authentication method returns an OK. If there is not such a "root" 
 * repository, any authentication error will cause the authentication process 
 * to fail.
 * 
 * @param request HTTP request
 * @param response HTTP response
 * @param authCookies vector that contains the authentication cookies
 * @param url the document url
 * @param creds an array of credentials for all external sources
 * @param id the default credential id to be retrieved from creds
        
 * @return the HTTP error code
        
 * @throws HttpException
 * @throws IOException
 */
public int authenticate(HttpServletRequest request, HttpServletResponse response, Vector<Cookie> authCookies,
        String url, Credentials creds, String id) throws HttpException, IOException {

    // Initialize status code
    int rootStatusCode = HttpServletResponse.SC_UNAUTHORIZED;
    int repositoryAuthStatusCode = HttpServletResponse.SC_UNAUTHORIZED;
    //Check if authn is Ok in multiple repository
    boolean repositoryOKAuthN = false;

    //clear authCookies
    authCookies.clear();

    boolean rootAuthNDefined = false;
    logger.debug("AuthN authenticate [" + url + "]");

    //Read vars
    if (valveConf != null) {
        isKerberos = new Boolean(valveConf.getKrbConfig().isKerberos()).booleanValue();
        if (isKerberos) {
            isNegotiate = new Boolean(valveConf.getKrbConfig().isNegotiate()).booleanValue();
        }
        loginUrl = valveConf.getLoginUrl();
    } else {
        logger.error("Configuration error: Config file is not present");
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Configuration error - Kerberos is not set properly");
        return HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }

    //ValveHost: it's the same URL as the login page, without 
    String valveHost = loginUrl.substring(0, loginUrl.lastIndexOf("/") + 1);

    RE internal = new RE(valveHost, RE.MATCH_CASEINDEPENDENT);

    // The host and URL of the GSA for the search
    //TODO add support for multiple GSA's
    RE query = new RE("/search", RE.MATCH_CASEINDEPENDENT);

    //Request has come from the same host as the valve, so must be the login authenticate
    if (internal.match(url)) {

        //Authentication vars
        String repositoryID = null;
        AuthenticationProcessImpl authProcess = null;
        ValveRepositoryConfiguration repositoryConfig = null;

        int order = 1;
        int size = authenticationImplementationsOrder.size();
        if (authenticationImplementationsOrder == null) {
            order = 0;
            logger.error(
                    "No Authentication module has been defined. Please check and add those needed at config file");
        }

        while ((1 <= order) && (order <= size)) {

            //Get the repository ID
            logger.debug("###Processing repository # " + order + " ###");
            Integer orderInt = new Integer(order);
            if (authenticationImplementationsOrder.containsKey(orderInt)) {
                repositoryID = authenticationImplementationsOrder.get(orderInt);
            } else {
                logger.error("Error during processing authentication methods. Order is not valid");
                break;
            }

            //Get the Repository config and authentication class                                                    
            authProcess = authenticationImplementations.get(repositoryID);
            repositoryConfig = valveConf.getRepository(repositoryID);

            logger.debug("Authenticating ID: " + repositoryConfig.getId());
            if (repositoryConfig.getId().equals("root")) {
                //Root should be used for main authentication against an identity repository (LDAP, DB, ..)
                //and should not be used as a content repository that contains documents
                try {
                    //add support to cookie array
                    rootAuthCookies.clear();
                    rootStatusCode = authProcess.authenticate(request, response, rootAuthCookies, url, creds,
                            "root");
                    logger.info("Repository authentication - " + repositoryConfig.getId()
                            + " completed. Response was " + rootStatusCode);
                    if (rootStatusCode == HttpServletResponse.SC_UNAUTHORIZED) {
                        logger.error("Root AuthN failed");
                    } else {
                        //Support to cookie array
                        if (rootStatusCode == HttpServletResponse.SC_OK) {
                            logger.debug("Root AuthN is SC_OK (200)");
                            if (!rootAuthCookies.isEmpty()) {
                                logger.debug("Root AuthN returns cookies");
                                for (int j = 0; j < rootAuthCookies.size(); j++) {
                                    logger.debug("Root Cookie found: " + rootAuthCookies.elementAt(j).getName()
                                            + ":" + rootAuthCookies.elementAt(j).getValue());
                                    authCookies.add(rootAuthCookies.elementAt(j));
                                }
                            } else {
                                logger.debug("Root AuthN does NOT return cookies");
                            }
                        }
                    }

                    //If no repository is defined called root then rootStatusCode must be set to OK
                    // This flag is used to indicate that a root repository has been defined.
                    rootAuthNDefined = true;
                    //
                } catch (Exception e) {
                    logger.debug("Exception with authentication for ID: " + repositoryConfig.getId() + " - "
                            + e.getMessage());
                    rootAuthNDefined = true;
                }
            } else {
                try {

                    //add support to cookie array
                    repositoryAuthCookies.clear();

                    logger.debug("Let's do the authentication");

                    repositoryAuthStatusCode = authProcess.authenticate(request, response,
                            repositoryAuthCookies, url, creds, repositoryConfig.getId());

                    //add support to cookie array
                    if (repositoryAuthStatusCode == HttpServletResponse.SC_OK) {
                        logger.debug("Repository AuthN [" + repositoryConfig.getId() + "] is SC_OK (200)");
                        //check if multiple repository is set to valid
                        if (repositoryOKAuthN == false) {
                            repositoryOKAuthN = true;
                        }
                        //check if cookie array is not empty and consume it
                        if (!repositoryAuthCookies.isEmpty()) {
                            logger.debug("Repository AuthN [" + repositoryConfig.getId() + "] returns "
                                    + repositoryAuthCookies.size() + " cookies");
                            for (int j = 0; j < repositoryAuthCookies.size(); j++) {
                                logger.debug("Repository Cookie found: "
                                        + repositoryAuthCookies.elementAt(j).getName() + ":"
                                        + repositoryAuthCookies.elementAt(j).getValue());
                                authCookies.add(repositoryAuthCookies.elementAt(j));
                            }
                        } else {
                            logger.debug("Repository AuthN [" + repositoryConfig.getId()
                                    + "] does NOT return cookies");
                        }
                    }

                    //end Krb support
                    logger.info("Repository authentication - " + repositoryConfig.getId()
                            + " completed. Response was " + repositoryAuthStatusCode);
                } catch (Exception e) {
                    logger.debug("Exception with authentication for ID: " + repositoryConfig.getId() + " - "
                            + e.getMessage());
                }
            }

            //increase order
            order++;
        }
    } else if (query.match(url)) {

        logger.debug("Query pattern [" + url + "]");

        // Don't do anything in here
        rootStatusCode = HttpServletResponse.SC_OK;

    } else {

        logger.error("No pattern defined for URL: " + url + ". It should not have been possible to get here!");

        // Protection
        rootStatusCode = HttpServletResponse.SC_UNAUTHORIZED;

    }

    //add support to multiple repositories
    if ((!rootAuthNDefined) && (repositoryOKAuthN)) {
        //If no root repository has been defined then rootStatusCode has to be set valid, to OK
        rootStatusCode = HttpServletResponse.SC_OK;
    }

    // Return status code
    logger.debug("RootAuthN Complete - Status Code: " + rootStatusCode);

    return rootStatusCode;

}

From source file:com.linuxbox.enkive.web.search.ViewSavedResultsServlet.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
    String sortBy = null;//from   www . ja v  a  2s  .c o m
    int sortDir = 1;
    res.setCharacterEncoding("UTF-8");
    try {
        String searchId = WebScriptUtils.cleanGetParameter(req, "id");
        sortBy = WebScriptUtils.cleanGetParameter(req, PAGE_SORT_BY_PARAMETER);
        String sortDirString = WebScriptUtils.cleanGetParameter(req, PAGE_SORT_DIR_PARAMETER);
        if (sortDirString != null)
            sortDir = Integer.parseInt(sortDirString);

        WebPageInfo pageInfo = new WebPageInfo(WebScriptUtils.cleanGetParameter(req, PAGE_POSITION_PARAMETER),
                WebScriptUtils.cleanGetParameter(req, PAGE_SIZE_PARAMETER));

        JSONObject dataJSON = new JSONObject();
        JSONObject jsonResult = new JSONObject();
        dataJSON.put(SEARCH_ID_TAG, searchId);
        if (LOGGER.isInfoEnabled())
            LOGGER.info("Loading " + searchId);

        SearchQuery query = workspaceService.getSearch(searchId);

        /* Query */
        try {
            dataJSON.put(QUERY_TAG, query.toJson());
        } catch (JSONException e) {
            LOGGER.error("could not return search criteria for search " + searchId, e);
        }

        /* Message Result List */

        try {
            SearchResult result = query.getResult();
            List<String> messageIds = result.getPage(sortBy, sortDir, pageInfo.getPagePos(),
                    pageInfo.getPageSize());

            List<MessageSummary> messageSummaries = archiveService.retrieveSummary(messageIds);
            pageInfo.setItemTotal(result.getCount());
            dataJSON.put(WebConstants.STATUS_ID_TAG, query.getStatus());

            JSONArray jsonMessageSummaryList = SearchResultsBuilder
                    .getMessageListJSON((Collection<MessageSummary>) messageSummaries);

            dataJSON.put(ITEM_TOTAL_TAG, pageInfo.getItemTotal());

            dataJSON.put(RESULTS_TAG, jsonMessageSummaryList);
        } catch (CannotRetrieveException e) {
            LOGGER.error("Could not access result message list", e);
            // throw new WebScriptException(
            // "Could not access query result message list", e);
        } catch (ResultPageException e) {
            LOGGER.error("Could not get page of results", e);
            this.addError(dataJSON, e.toString());
        }
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Returning saved search results for search id " + searchId);

        jsonResult.put(DATA_TAG, dataJSON);
        jsonResult.put(PAGING_LABEL, pageInfo.getPageJSON());
        jsonResult.write(res.getWriter());
    } catch (WorkspaceException e) {
        respondError(HttpServletResponse.SC_UNAUTHORIZED, null, res);
        throw new EnkiveServletException("Could not login to repository to retrieve search", e);
    } catch (JSONException e) {
        respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, res);
        throw new EnkiveServletException("Unable to serialize JSON", e);
    } finally {

    }
}