Search in sources :

Example 96 with ServletRequest

use of javax.servlet.ServletRequest in project blade by biezhi.

the class DigestAuthenticator method validateRequest.

@Override
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException {
    if (!mandatory)
        return new DeferredAuthentication(this);
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    String credentials = request.getHeader(HttpHeader.AUTHORIZATION.asString());
    try {
        boolean stale = false;
        if (credentials != null) {
            if (LOG.isDebugEnabled())
                LOG.debug("Credentials: " + credentials);
            QuotedStringTokenizer tokenizer = new QuotedStringTokenizer(credentials, "=, ", true, false);
            final Digest digest = new Digest(request.getMethod());
            String last = null;
            String name = null;
            while (tokenizer.hasMoreTokens()) {
                String tok = tokenizer.nextToken();
                char c = (tok.length() == 1) ? tok.charAt(0) : '\0';
                switch(c) {
                    case '=':
                        name = last;
                        last = tok;
                        break;
                    case ',':
                        name = null;
                        break;
                    case ' ':
                        break;
                    default:
                        last = tok;
                        if (name != null) {
                            if ("username".equalsIgnoreCase(name))
                                digest.username = tok;
                            else if ("realm".equalsIgnoreCase(name))
                                digest.realm = tok;
                            else if ("nonce".equalsIgnoreCase(name))
                                digest.nonce = tok;
                            else if ("nc".equalsIgnoreCase(name))
                                digest.nc = tok;
                            else if ("cnonce".equalsIgnoreCase(name))
                                digest.cnonce = tok;
                            else if ("qop".equalsIgnoreCase(name))
                                digest.qop = tok;
                            else if ("uri".equalsIgnoreCase(name))
                                digest.uri = tok;
                            else if ("response".equalsIgnoreCase(name))
                                digest.response = tok;
                            name = null;
                        }
                }
            }
            int n = checkNonce(digest, (Request) request);
            if (n > 0) {
                //UserIdentity user = _loginService.login(digest.username,digest);
                UserIdentity user = login(digest.username, digest, req);
                if (user != null) {
                    return new UserAuthentication(getAuthMethod(), user);
                }
            } else if (n == 0)
                stale = true;
        }
        if (!DeferredAuthentication.isDeferred(response)) {
            String domain = request.getContextPath();
            if (domain == null)
                domain = "/";
            response.setHeader(HttpHeader.WWW_AUTHENTICATE.asString(), "Digest realm=\"" + _loginService.getName() + "\", domain=\"" + domain + "\", nonce=\"" + newNonce((Request) request) + "\", algorithm=MD5, qop=\"auth\"," + " stale=" + stale);
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return Authentication.SEND_CONTINUE;
        }
        return Authentication.UNAUTHENTICATED;
    } catch (IOException e) {
        throw new ServerAuthException(e);
    }
}
Also used : MessageDigest(java.security.MessageDigest) UserIdentity(org.eclipse.jetty.server.UserIdentity) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ServerAuthException(org.eclipse.jetty.security.ServerAuthException) UserAuthentication(org.eclipse.jetty.security.UserAuthentication) Constraint(org.eclipse.jetty.util.security.Constraint) HttpServletRequest(javax.servlet.http.HttpServletRequest) QuotedStringTokenizer(org.eclipse.jetty.util.QuotedStringTokenizer)

Example 97 with ServletRequest

use of javax.servlet.ServletRequest in project dropwizard by dropwizard.

the class CacheBustingFilterTest method passesThroughNonHttpRequests.

@Test
public void passesThroughNonHttpRequests() throws Exception {
    final ServletRequest req = mock(ServletRequest.class);
    final ServletResponse res = mock(ServletResponse.class);
    filter.doFilter(req, res, chain);
    verify(chain).doFilter(req, res);
    verifyZeroInteractions(res);
}
Also used : ServletRequest(javax.servlet.ServletRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletResponse(javax.servlet.ServletResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) Test(org.junit.Test)

Example 98 with ServletRequest

use of javax.servlet.ServletRequest in project jetty.project by eclipse.

the class TestFilter method doFilter.

/* ------------------------------------------------------------ */
/*
     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    String from = request.getRemoteAddr();
    String to = request.getLocalAddr();
    String path = ((HttpServletRequest) request).getServletPath();
    if (!_remote && !_allowed.contains(path) && !from.equals(to)) {
        _context.getRequestDispatcher("/remote.html").forward(request, response);
        return;
    }
    Integer old_value = null;
    ServletRequest r = request;
    while (r instanceof ServletRequestWrapper) r = ((ServletRequestWrapper) r).getRequest();
    try {
        old_value = (Integer) request.getAttribute("testFilter");
        Integer value = (old_value == null) ? new Integer(1) : new Integer(old_value.intValue() + 1);
        request.setAttribute("testFilter", value);
        String qString = ((HttpServletRequest) request).getQueryString();
        if (qString != null && qString.indexOf("wrap") >= 0) {
            request = new HttpServletRequestWrapper((HttpServletRequest) request);
        }
        _context.setAttribute("request" + r.hashCode(), value);
        chain.doFilter(request, response);
    } finally {
        request.setAttribute("testFilter", old_value);
        _context.setAttribute("request" + r.hashCode(), old_value);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) ServletRequestWrapper(javax.servlet.ServletRequestWrapper)

Example 99 with ServletRequest

use of javax.servlet.ServletRequest in project jetty.project by eclipse.

the class PushCacheFilter method doFilter.

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    Request jettyRequest = Request.getBaseRequest(request);
    if (HttpVersion.fromString(request.getProtocol()).getVersion() < 20 || !HttpMethod.GET.is(request.getMethod()) || !jettyRequest.isPushSupported()) {
        chain.doFilter(req, resp);
        return;
    }
    long now = System.nanoTime();
    // Iterating over fields is more efficient than multiple gets
    HttpFields fields = jettyRequest.getHttpFields();
    boolean conditional = false;
    String referrer = null;
    loop: for (int i = 0; i < fields.size(); i++) {
        HttpField field = fields.getField(i);
        HttpHeader header = field.getHeader();
        if (header == null)
            continue;
        switch(header) {
            case IF_MATCH:
            case IF_MODIFIED_SINCE:
            case IF_NONE_MATCH:
            case IF_UNMODIFIED_SINCE:
                conditional = true;
                break loop;
            case REFERER:
                referrer = field.getValue();
                break;
            default:
                break;
        }
    }
    if (LOG.isDebugEnabled())
        LOG.debug("{} {} referrer={} conditional={}", request.getMethod(), request.getRequestURI(), referrer, conditional);
    String path = request.getRequestURI();
    String query = request.getQueryString();
    if (_useQueryInKey && query != null)
        path += "?" + query;
    if (referrer != null) {
        HttpURI referrerURI = new HttpURI(referrer);
        String host = referrerURI.getHost();
        int port = referrerURI.getPort();
        if (port <= 0)
            port = request.isSecure() ? 443 : 80;
        boolean referredFromHere = _hosts.size() > 0 ? _hosts.contains(host) : host.equals(request.getServerName());
        referredFromHere &= _ports.size() > 0 ? _ports.contains(port) : port == request.getServerPort();
        if (referredFromHere) {
            if (HttpMethod.GET.is(request.getMethod())) {
                String referrerPath = _useQueryInKey ? referrerURI.getPathQuery() : referrerURI.getPath();
                if (referrerPath == null)
                    referrerPath = "/";
                if (referrerPath.startsWith(request.getContextPath() + "/")) {
                    if (!referrerPath.equals(path)) {
                        PrimaryResource primaryResource = _cache.get(referrerPath);
                        if (primaryResource != null) {
                            long primaryTimestamp = primaryResource._timestamp.get();
                            if (primaryTimestamp != 0) {
                                if (now - primaryTimestamp < TimeUnit.MILLISECONDS.toNanos(_associatePeriod)) {
                                    Set<String> associated = primaryResource._associated;
                                    // Not strictly concurrent-safe, just best effort to limit associations.
                                    if (associated.size() <= _maxAssociations) {
                                        if (associated.add(path)) {
                                            if (LOG.isDebugEnabled())
                                                LOG.debug("Associated {} to {}", path, referrerPath);
                                        }
                                    } else {
                                        if (LOG.isDebugEnabled())
                                            LOG.debug("Not associated {} to {}, exceeded max associations of {}", path, referrerPath, _maxAssociations);
                                    }
                                } else {
                                    if (LOG.isDebugEnabled())
                                        LOG.debug("Not associated {} to {}, outside associate period of {}ms", path, referrerPath, _associatePeriod);
                                }
                            }
                        }
                    } else {
                        if (LOG.isDebugEnabled())
                            LOG.debug("Not associated {} to {}, referring to self", path, referrerPath);
                    }
                } else {
                    if (LOG.isDebugEnabled())
                        LOG.debug("Not associated {} to {}, different context", path, referrerPath);
                }
            }
        } else {
            if (LOG.isDebugEnabled())
                LOG.debug("External referrer {}", referrer);
        }
    }
    PrimaryResource primaryResource = _cache.get(path);
    if (primaryResource == null) {
        PrimaryResource r = new PrimaryResource();
        primaryResource = _cache.putIfAbsent(path, r);
        primaryResource = primaryResource == null ? r : primaryResource;
        primaryResource._timestamp.compareAndSet(0, now);
        if (LOG.isDebugEnabled())
            LOG.debug("Cached primary resource {}", path);
    } else {
        long last = primaryResource._timestamp.get();
        if (last < _renew && primaryResource._timestamp.compareAndSet(last, now)) {
            primaryResource._associated.clear();
            if (LOG.isDebugEnabled())
                LOG.debug("Clear associated resources for {}", path);
        }
    }
    // Push associated resources.
    if (!conditional && !primaryResource._associated.isEmpty()) {
        PushBuilder pushBuilder = jettyRequest.getPushBuilder();
        // Breadth-first push of associated resources.
        Queue<PrimaryResource> queue = new ArrayDeque<>();
        queue.offer(primaryResource);
        while (!queue.isEmpty()) {
            PrimaryResource parent = queue.poll();
            for (String childPath : parent._associated) {
                PrimaryResource child = _cache.get(childPath);
                if (child != null)
                    queue.offer(child);
                if (LOG.isDebugEnabled())
                    LOG.debug("Pushing {} for {}", childPath, path);
                pushBuilder.path(childPath).push();
            }
        }
    }
    chain.doFilter(request, resp);
}
Also used : Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) HttpURI(org.eclipse.jetty.http.HttpURI) ArrayDeque(java.util.ArrayDeque) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpHeader(org.eclipse.jetty.http.HttpHeader) HttpField(org.eclipse.jetty.http.HttpField) HttpFields(org.eclipse.jetty.http.HttpFields) PushBuilder(org.eclipse.jetty.server.PushBuilder)

Example 100 with ServletRequest

use of javax.servlet.ServletRequest in project jetty.project by eclipse.

the class PushSessionCacheFilter method doFilter.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    // Get Jetty request as these APIs are not yet standard
    Request baseRequest = Request.getBaseRequest(request);
    String uri = baseRequest.getRequestURI();
    if (LOG.isDebugEnabled())
        LOG.debug("{} {} push={}", baseRequest.getMethod(), uri, baseRequest.isPush());
    HttpSession session = baseRequest.getSession(true);
    // find the target for this resource
    Target target = _cache.get(uri);
    if (target == null) {
        Target t = new Target(uri);
        target = _cache.putIfAbsent(uri, t);
        target = target == null ? t : target;
    }
    request.setAttribute(TARGET_ATTR, target);
    // Set the timestamp for this resource in this session
    ConcurrentHashMap<String, Long> timestamps = (ConcurrentHashMap<String, Long>) session.getAttribute(TIMESTAMP_ATTR);
    if (timestamps == null) {
        timestamps = new ConcurrentHashMap<>();
        session.setAttribute(TIMESTAMP_ATTR, timestamps);
    }
    timestamps.put(uri, System.currentTimeMillis());
    // push any associated resources
    if (baseRequest.isPushSupported() && !baseRequest.isPush() && !target._associated.isEmpty()) {
        // Breadth-first push of associated resources.
        Queue<Target> queue = new ArrayDeque<>();
        queue.offer(target);
        while (!queue.isEmpty()) {
            Target parent = queue.poll();
            PushBuilder builder = baseRequest.getPushBuilder();
            builder.addHeader("X-Pusher", PushSessionCacheFilter.class.toString());
            for (Target child : parent._associated.values()) {
                queue.offer(child);
                String path = child._path;
                if (LOG.isDebugEnabled())
                    LOG.debug("PUSH {} <- {}", path, uri);
                builder.path(path).etag(child._etag).lastModified(child._lastModified).push();
            }
        }
    }
    chain.doFilter(request, response);
}
Also used : HttpSession(javax.servlet.http.HttpSession) Request(org.eclipse.jetty.server.Request) ServletRequest(javax.servlet.ServletRequest) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) PushBuilder(org.eclipse.jetty.server.PushBuilder) ArrayDeque(java.util.ArrayDeque)

Aggregations

ServletRequest (javax.servlet.ServletRequest)185 ServletResponse (javax.servlet.ServletResponse)129 HttpServletRequest (javax.servlet.http.HttpServletRequest)117 HttpServletResponse (javax.servlet.http.HttpServletResponse)95 FilterChain (javax.servlet.FilterChain)79 Test (org.junit.Test)75 ServletException (javax.servlet.ServletException)59 IOException (java.io.IOException)57 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)35 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)35 MockFilterChain (org.springframework.mock.web.MockFilterChain)32 Filter (javax.servlet.Filter)28 Injector (com.google.inject.Injector)25 HttpServletResponseWrapper (javax.servlet.http.HttpServletResponseWrapper)21 NestedServletException (org.springframework.web.util.NestedServletException)19 ServletTestUtils.newFakeHttpServletRequest (com.google.inject.servlet.ServletTestUtils.newFakeHttpServletRequest)18 ServletTestUtils.newFakeHttpServletResponse (com.google.inject.servlet.ServletTestUtils.newFakeHttpServletResponse)18 HttpServletRequestWrapper (javax.servlet.http.HttpServletRequestWrapper)15 ErrorPage (org.springframework.boot.web.server.ErrorPage)15 MockHttpServletRequest (org.springframework.mock.web.test.MockHttpServletRequest)14