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:org.jboss.as.test.integration.security.jaas.JAASIdentityCachingTestCase.java

/**
 * Test how many times is called login() method of {@link CustomLoginModule} and if the response from HelloBean is the
 * expected one./*from  w ww . j  a  v  a2 s.c o m*/
 * 
 * @param webAppURL
 * @throws Exception
 */
@Test
public void test(@ArquillianResource URL webAppURL) throws Exception {
    final URI greetingUri = new URI(webAppURL.toExternalForm() + HelloEJBCallServlet.SERVLET_PATH.substring(1)
            + "?" + HelloEJBCallServlet.PARAM_JNDI_NAME + "="
            + URLEncoder.encode("java:app/" + JAR_BASE_NAME + "/" + HelloBean.class.getSimpleName(), "UTF-8"));
    final URI counterUri = new URI(webAppURL.toExternalForm() + LMCounterServlet.SERVLET_PATH.substring(1));
    LOGGER.info("Requesting URL " + greetingUri);
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    try {
        final HttpGet getCounter = new HttpGet(counterUri);
        final HttpGet getGreeting = new HttpGet(greetingUri);
        HttpResponse response = httpClient.execute(getGreeting);
        assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode());
        EntityUtils.consume(response.getEntity());

        //check if LoginModule #login() counter is initialized correctly
        response = httpClient.execute(getCounter);
        assertEquals("0", EntityUtils.toString(response.getEntity()));

        final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin",
                CustomLoginModule.PASSWORD);
        httpClient.getCredentialsProvider()
                .setCredentials(new AuthScope(greetingUri.getHost(), greetingUri.getPort()), credentials);

        //make 2 calls to the servlet
        response = httpClient.execute(getGreeting);
        assertEquals("Hello Caller!", EntityUtils.toString(response.getEntity()));
        response = httpClient.execute(getGreeting);
        assertEquals("Hello Caller!", EntityUtils.toString(response.getEntity()));

        //There should be only one call to login() method 
        response = httpClient.execute(getCounter);
        assertEquals("1", EntityUtils.toString(response.getEntity()));
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:org.openrepose.filters.clientauth.common.AuthenticationHandler.java

@Override
public FilterDirector handleRequest(HttpServletRequest request, ReadableHttpServletResponse response) {
    FilterDirector filterDirector = new FilterDirectorImpl();
    filterDirector.setResponseStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
    filterDirector.setFilterAction(FilterAction.RETURN);

    final String uri = request.getRequestURI();
    LOG.debug("Uri is " + uri);
    if (uriMatcher.isUriOnWhiteList(uri)) {
        filterDirector.setFilterAction(FilterAction.PASS);
        LOG.debug("Uri is on whitelist!  Letting request pass through.");
    } else {/*from w  w  w  . j  a v  a 2  s .c  o m*/
        filterDirector = this.authenticate(request);
    }

    return filterDirector;
}

From source file:org.ngrinder.script.controller.SvnDavController.java

/**
 * Request Handler./*from  w w  w  .ja v  a 2 s . c  o  m*/
 *
 * @param request  request
 * @param response response
 * @throws ServletException occurs when servlet has a problem.
 * @throws IOException      occurs when file system has a problem.
 */
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (LOGGER.isTraceEnabled()) {
        logRequest(request);
    }
    try {
        // To make it understand Asian Language..
        request = new MyHttpServletRequestWrapper(request);
        DAVRepositoryManager repositoryManager = new DAVRepositoryManager(getDAVConfig(), request);
        ServletDAVHandler handler = DAVHandlerFactory.createHandler(repositoryManager, request, response);
        handler.execute();
    } catch (DAVException de) {
        response.setContentType(XML_CONTENT_TYPE);
        handleError(de, response);
    } catch (SVNException svne) {
        StringWriter sw = new StringWriter();
        svne.printStackTrace(new PrintWriter(sw));

        /**
         * truncate status line if it is to long
         */
        String msg = sw.getBuffer().toString();
        if (msg.length() > 128) {
            msg = msg.substring(0, 128);
        }
        SVNErrorCode errorCode = svne.getErrorMessage().getErrorCode();
        if (errorCode == SVNErrorCode.FS_NOT_DIRECTORY || errorCode == SVNErrorCode.FS_NOT_FOUND
                || errorCode == SVNErrorCode.RA_DAV_PATH_NOT_FOUND) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
        } else if (errorCode == SVNErrorCode.NO_AUTH_FILE_PATH) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, msg);
        } else if (errorCode == SVNErrorCode.RA_NOT_AUTHORIZED) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, msg);
        } else {
            String errorBody = generateStandardizedErrorBody(errorCode.getCode(), null, null,
                    svne.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.setContentType(XML_CONTENT_TYPE);
            response.getWriter().print(errorBody);
        }
    } catch (Throwable th) {
        StringWriter sw = new StringWriter();
        th.printStackTrace(new PrintWriter(sw));
        String msg = sw.getBuffer().toString();
        LOGGER.debug("Error in DavSVN Controller", th);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
    } finally {
        response.flushBuffer();
    }
}

From source file:org.dataconservancy.ui.api.ProjectController.java

/**
 * Handles empty get call this will return a list of projects that are
 * visible to the current user Not yet implemented.
 * /*from w w w . j  av a  2s  .  c om*/
 * @param mimeType
 * @param modifiedSince
 * @param request
 * @throws IOException
 * @throws BizPolicyException
 */
@RequestMapping(method = { RequestMethod.GET })
public void handleEmptyGetRequest(@RequestHeader(value = "Accept", required = false) String mimeType,
        @RequestHeader(value = "If-Modified-Since", required = false) @DateTimeFormat(iso = DATE_TIME) Date modifiedSince,
        HttpServletRequest request, HttpServletResponse resp)
        throws ServletException, IOException, BizPolicyException {

    Person user = getAuthenticatedUser();

    if (user == null) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    } else {
        Set<Project> projects = projectBizService.findByAdmin(user);
        Bop bop = new Bop();
        bop.setProjects(projects);

        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/xml");
        objectBuilder.buildBusinessObjectPackage(bop, resp.getOutputStream());
    }
}

From source file:com.codenvy.ide.git.VFSPermissionsFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    int tokenPlace;
    String lastTokenBeforePath = "/" + gitServerUriPrefix + "/";
    if ((tokenPlace = req.getRequestURL().indexOf(lastTokenBeforePath)) != -1) {
        //get path to project
        String url = req.getRequestURL().substring(tokenPlace + lastTokenBeforePath.length());
        url = url.replaceFirst("/info/refs", "");
        url = url.replaceFirst("/git-upload-pack", "");
        //adaptation to fs
        url = url.replaceAll("/", Matcher.quoteReplacement(File.separator));
        //search for dotVFS directory
        File projectDirectory = Paths.get(vfsRoot, url).toFile();
        String auth;//from  w  w  w. java 2 s  .  c  om
        String userName = "";
        String password = "";
        if ((auth = req.getHeader("authorization")) != null) {
            //get encoded password phrase
            String userAndPasswordEncoded = auth.substring(6);
            // decode Base64 user:password
            String userAndPasswordDecoded = new String(Base64.decodeBase64(userAndPasswordEncoded));
            //get username and password separator ':'
            int betweenUserAndPassword = userAndPasswordDecoded.indexOf(':');
            //get username - it is before first ':'
            userName = userAndPasswordDecoded.substring(0, betweenUserAndPassword);
            //get password - it is after first ':'
            password = userAndPasswordDecoded.substring(betweenUserAndPassword + 1);
        }

        // Check if user authenticated and has permissions to project, or send response code 403
        boolean needLogout = false;
        String token = null;
        User user;
        try {
            if (!userName.isEmpty()) {
                if (password.equals("x-che")) { // internal SSO
                    token = userName;
                } else {
                    token = getToken(userName, password);
                    if (token == null) {
                        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN);
                        return;
                    }
                    needLogout = true;
                }
                user = getUserBySSO(token);
                EnvironmentContext.getCurrent().setUser(user);
            }

            if (!hasAccessToItem(projectDirectory.getParentFile().getName(), projectDirectory.getName())) {
                if (!userName.isEmpty()) {
                    // Authenticated but no access
                    ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                } else {
                    // Not authenticated, try again with credentials
                    ((HttpServletResponse) response).addHeader("Cache-Control", "private");
                    ((HttpServletResponse) response).addHeader("WWW-Authenticate", "Basic");
                    ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
                    return;
                }
            }
        } finally {
            if (needLogout) {
                logout();
            }
            EnvironmentContext.reset();
        }
    }
    chain.doFilter(req, response);
}

From source file:memedb.httpd.MemeDBHandler.java

protected void sendNoAuthError(HttpServletResponse response, String reason) throws IOException {
    sendError(response, "Not authorized", reason, null, HttpServletResponse.SC_UNAUTHORIZED, log);
}

From source file:com.google.gsa.valve.modules.ldap.LDAPSSO.java

/**
 * This is the main method that does the authentication and should be 
 * invoked by the classes that would like to populate new user authentication 
 * credentials from the LDAP server.//from   w w w  .  j a v  a2s.c  om
 * <p>
 * It also authenticates the user against the LDAP server, so that only 
 * priviledged users are able to read the LDAP attributes. These multiple 
 * credentials are stored in the directory server and populate them in the 
 * user's credential container. It enables the other AuthN/AuthZ modules to 
 * use them when securely accessing the backend systems.
 * <p>
 * If the LDAP authentication result is OK, it creates an 
 * authentication cookie. Anyway, the HTTP response code is returned in this 
 * method to inform the caller on the status.
 * 
 * @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 {

    logger.debug("Start LDAPSSO AuthN process");

    //protection
    repositories.clear();
    ldapAttributes.clear();

    //Insert LDAP attributes from the config file
    getLDAPAttributes(id);

    //First read the u/p the credentails store, in this case using the same as the root login
    logger.debug("LDAPSSO: trying to get creds from repository ID: " + id);
    Credential cred = null;
    try {
        cred = creds.getCredential(id);
    } catch (NullPointerException npe) {
        logger.error("NPE while reading credentials of ID: " + id);
    }
    if (cred == null) {
        cred = creds.getCredential("root");
        if (cred != null) {
            logger.info("LDAPSSO: credential ID used is \"root\"");
        } else {
            logger.error("LDAPSSO: No credentials available for " + id);
        }
    }

    Cookie[] cookies = null;

    // Initialize status code
    int statusCode = HttpServletResponse.SC_UNAUTHORIZED;

    // Read cookies
    cookies = request.getCookies();

    try {
        authMaxAge = Integer.parseInt(valveConf.getAuthMaxAge());
    } catch (NumberFormatException nfe) {
        logger.error(
                "Configuration error: chack the configuration file as the number set for authMaxAge is not OK:");
    }

    //If the required cookie was not found need to authenticate.
    logger.info("Authenticating root user with LDAP");
    try {

        //Check if the LDAP credentials are OK                       
        Ldap ldapconn = new Ldap(ldapHost, cred.getUsername(), cred.getPassword(), ldapBaseuser, ldapDomain,
                rdnAttr);
        try {
            logger.debug("Connecting to LDAP");
            DirContext ctx = ldapconn.openConnection();
            if (ctx == null) {
                //Just send a comment  
                logger.debug("The user(" + cred.getUsername() + ")/password doesn't match");
                ldapconn.closeConnection(ctx);
                return (HttpServletResponse.SC_UNAUTHORIZED);
            }

            //Fetching credentials
            logger.debug("Fetching credentials from the LDAP");

            fetchingCredentials(ldapconn, ctx, cred.getUsername(), creds);

            //Close the connection
            ldapconn.closeConnection(ctx);

        } catch (Exception ex) {
            logger.error("LDAP connection problem during user access: " + ex.getMessage(), ex);
            return (HttpServletResponse.SC_UNAUTHORIZED);
        } finally {
        }

        Cookie extAuthCookie = null;

        extAuthCookie = settingCookie();

        //add sendCookies support
        logger.debug("Setting session");
        boolean isSessionEnabled = new Boolean(valveConf.getSessionConfig().isSessionEnabled()).booleanValue();
        boolean sendCookies = false;
        if (isSessionEnabled) {
            sendCookies = new Boolean(valveConf.getSessionConfig().getSendCookies()).booleanValue();
        }
        if ((!isSessionEnabled) || ((isSessionEnabled) && (sendCookies))) {
            response.addCookie(extAuthCookie);
        }

        //add cookie to the array
        authCookies.add(extAuthCookie);

        //This would be set to OK or 401 in a real AuthN module
        statusCode = HttpServletResponse.SC_OK;

    } catch (Exception e) {

        // Log error
        logger.error("LDAP SSO authentication failure: " + e.getMessage(), e);

        // Update status code
        statusCode = HttpServletResponse.SC_UNAUTHORIZED;

    }

    // Debug
    logger.debug("Sample Authentication completed (" + statusCode + ")");

    // Return status code
    return statusCode;

}

From source file:org.openrepose.common.auth.openstack.AuthenticationServiceClient.java

@Override
public AuthenticateResponse validateToken(String tenant, String userToken, String tracingHeader)
        throws AuthServiceException {
    AuthenticateResponse authenticateResponse = null;
    ServiceClientResponse serviceResponse = validateUser(userToken, tenant, false, tracingHeader);

    switch (serviceResponse.getStatus()) {
    case HttpServletResponse.SC_OK:
        authenticateResponse = openStackCoreResponseUnmarshaller.unmarshall(serviceResponse.getData(),
                AuthenticateResponse.class);
        break;/*from   w  w w  .j  ava  2  s.  com*/

    case HttpServletResponse.SC_NOT_FOUND:
        // User's token is bad
        delegationMessage.set("Unable to validate token: " + userToken + ". Invalid token.");
        LOG.error("Unable to validate token.  Invalid token. " + serviceResponse.getStatus());
        break;

    case HttpServletResponse.SC_UNAUTHORIZED:
        LOG.error(
                "Unable to validate token: " + userToken + " due to status code: " + serviceResponse.getStatus()
                        + " :admin token expired. Retrieving new admin token and retrying token validation...");

        serviceResponse = validateUser(userToken, tenant, true, tracingHeader);

        if (serviceResponse.getStatus() == HttpServletResponse.SC_OK) {
            authenticateResponse = openStackCoreResponseUnmarshaller.unmarshall(serviceResponse.getData(),
                    AuthenticateResponse.class);
        } else if (serviceResponse.getStatus() == HttpServletResponse.SC_NOT_FOUND) {
            delegationMessage.set("Unable to validate token: " + userToken + ". Invalid token. Status Code: "
                    + serviceResponse.getStatus());
            LOG.error("Unable to validate token.  Invalid token. " + serviceResponse.getStatus());
        } else {
            delegationMessage
                    .set("Unable to validate token: " + userToken + " with configured admin credentials.");
            LOG.error("Still unable to validate token: " + serviceResponse.getStatus());
            throw new AuthServiceException("Unable to authenticate user with configured Admin credentials");
        }
        break;
    case HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE:
    case FilterDirector.SC_TOO_MANY_REQUESTS: // (413 | 429)
        delegationMessage.set("Unable to validate token: " + userToken + ". Invalid token. Status Code: "
                + serviceResponse.getStatus());
        throw buildAuthServiceOverLimitException(serviceResponse);
    default:
        delegationMessage.set("Authentication Service returned an unexpected response status code: "
                + serviceResponse.getStatus() + " for token: " + userToken);
        LOG.error("Authentication Service returned an unexpected response status code: "
                + serviceResponse.getStatus());
        throw new AuthServiceException("Unable to validate token. Response from " + targetHostUri + ": "
                + serviceResponse.getStatus());
    }

    return authenticateResponse;
}

From source file:com.xpn.xwiki.user.impl.xwiki.MyBasicAuthenticator.java

public static void showLogin(HttpServletRequest request, HttpServletResponse response, String realmName)
        throws IOException {
    // save this request
    SecurityFilter.saveRequestInformation(request);

    // determine the number of login attempts
    int loginAttempts;
    if (request.getSession().getAttribute(LOGIN_ATTEMPTS) != null) {
        loginAttempts = ((Integer) request.getSession().getAttribute(LOGIN_ATTEMPTS)).intValue();
        loginAttempts += 1;/* w  w  w .ja va2 s .c o m*/
    } else {
        loginAttempts = 1;
    }
    request.getSession().setAttribute(LOGIN_ATTEMPTS, new Integer(loginAttempts));

    if (loginAttempts <= MAX_ATTEMPTS) {
        response.setHeader("WWW-Authenticate", "BASIC realm=\"" + realmName + "\"");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    } else {
        request.getSession().removeAttribute(LOGIN_ATTEMPTS);
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, LOGIN_FAILED_MESSAGE);
    }
}

From source file:org.dasein.cloud.rackspace.AbstractMethod.java

public synchronized @Nullable AuthenticationContext authenticate() throws CloudException, InternalException {
    Logger std = RackspaceCloud.getLogger(RackspaceCloud.class, "std");
    Logger wire = RackspaceCloud.getLogger(RackspaceCloud.class, "wire");

    if (std.isTraceEnabled()) {
        std.trace("enter - " + AbstractMethod.class.getName() + ".authenticate()");
    }/*from   w w  w. j  ava 2s.  c om*/
    if (wire.isDebugEnabled()) {
        wire.debug("--------------------------------------------------------> " + provider.getEndpoint());
        wire.debug("");
    }
    try {
        ProviderContext ctx = provider.getContext();
        HttpClient client = getClient();
        HttpGet get = new HttpGet(provider.getEndpoint());

        try {
            get.addHeader("Content-Type", "application/json");
            get.addHeader("X-Auth-User", new String(ctx.getAccessPublic(), "utf-8"));
            get.addHeader("X-Auth-Key", new String(ctx.getAccessPrivate(), "utf-8"));
        } catch (UnsupportedEncodingException e) {
            std.error("authenticate(): Unsupported encoding when building request headers: " + e.getMessage());
            if (std.isTraceEnabled()) {
                e.printStackTrace();
            }
            throw new InternalException(e);
        }
        if (wire.isDebugEnabled()) {
            wire.debug(get.getRequestLine().toString());
            for (Header header : get.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
        }
        HttpResponse response;

        try {
            response = client.execute(get);
            if (wire.isDebugEnabled()) {
                wire.debug(response.getStatusLine().toString());
                for (Header header : response.getAllHeaders()) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
                wire.debug("");
            }
        } catch (IOException e) {
            std.error("I/O error from server communications: " + e.getMessage());
            e.printStackTrace();
            throw new InternalException(e);
        }
        int code = response.getStatusLine().getStatusCode();

        std.debug("HTTP STATUS: " + code);
        if (code != HttpServletResponse.SC_NO_CONTENT) {
            if (code == HttpServletResponse.SC_FORBIDDEN || code == HttpServletResponse.SC_UNAUTHORIZED) {
                return null;
            }
            std.error("authenticate(): Expected NO CONTENT for an authentication request, got " + code);
            HttpEntity entity = response.getEntity();
            String json = null;

            if (entity != null) {
                try {
                    json = EntityUtils.toString(entity);

                    if (wire.isDebugEnabled()) {
                        wire.debug(json);
                        wire.debug("");
                    }
                } catch (IOException e) {
                    throw new CloudException(e);
                }
            }
            RackspaceException.ExceptionItems items;
            if (json == null) {
                items = RackspaceException.parseException(code, "{}");
            } else {
                items = RackspaceException.parseException(code, json);
            }
            if (items.type.equals(CloudErrorType.AUTHENTICATION)) {
                return null;
            }
            std.error("authenticate(): [" + code + " : " + items.message + "] " + items.details);
            throw new RackspaceException(items);
        } else {
            AuthenticationContext authContext = new AuthenticationContext();

            for (Header h : response.getAllHeaders()) {
                if (h.getName().equalsIgnoreCase("x-auth-token")) {
                    authContext.setAuthToken(h.getValue().trim());
                } else if (h.getName().equalsIgnoreCase("x-server-management-url")) {
                    authContext.setServerUrl(h.getValue().trim());
                } else if (h.getName().equalsIgnoreCase("x-storage-url")) {
                    authContext.setStorageUrl(h.getValue().trim());
                } else if (h.getName().equalsIgnoreCase("x-cdn-management-url")) {
                    authContext.setCdnUrl(h.getValue().trim());
                } else if (h.getName().equalsIgnoreCase("x-storage-token")) {
                    authContext.setStorageToken(h.getValue().trim());
                }
            }
            if (authContext.getAuthToken() == null) {
                std.warn("authenticate(): No authentication token in response");
                throw new CloudException("No authentication token in cloud response");
            }
            return authContext;
        }
    } finally {
        if (std.isTraceEnabled()) {
            std.trace("exit - " + AbstractMethod.class.getName() + ".authenticate()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("--------------------------------------------------------> " + provider.getEndpoint());
        }
    }
}