[RESOLVIDO] Vraptor + Interceptor: Setar valor no request

3 respostas
fred.dobroes

Olá Pessoal,

estou interceptando os valores que os usuário enviam no form para retirar tags HTML e Script maliciosos, para isso criei o seguinte interceptor:

@Intercepts
public class Log implements Interceptor {
	
	private final HttpServletRequest request;
	
	
	public Log (HttpServletRequest request){
		this.request = request;
	}
	
	public boolean accepts(ResourceMethod arg0) {
		return true;
	}

	public void intercept(InterceptorStack stack, ResourceMethod method,
			Object resourceInstance) throws InterceptionException {
		
	   	Enumeration params = request.getParameterNames();
    	        ArrayList<String> lista = Collections.list(params);   //cria uma lista com o nome de todos os parametros
		
		for (String parametro : lista) {
    		String insegura = request.getParameter(parametro);   //pega o paramentro do request.
    		String segura = Jsoup.clean(insegura, Whitelist.none());  // o Jsoup faz todo o trabalho de filtrar e gerar a string segura 
    		request.setAttribute(parametro, segura);  //e setado o novo atributo
		}
		
		stack.next(method, resourceInstance);
		
	}

}

O problema é que por mais que eu altere o request, os parâmetros que chegam no meu controller estão iguais aos do request antes de passar pelo interceptor.

3 Respostas

Rafael_Guerreiro

Creio que você precisará sobrescrever o ParametersInstantiatorInterceptor.
Aqui está ele na forma “natural”.

/***
 * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource
 * All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package br.com.caelum.vraptor.interceptor;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import br.com.caelum.vraptor.InterceptionException;
import br.com.caelum.vraptor.Intercepts;
import br.com.caelum.vraptor.Lazy;
import br.com.caelum.vraptor.Validator;
import br.com.caelum.vraptor.core.InterceptorStack;
import br.com.caelum.vraptor.core.Localization;
import br.com.caelum.vraptor.core.MethodInfo;
import br.com.caelum.vraptor.http.MutableRequest;
import br.com.caelum.vraptor.http.ParametersProvider;
import br.com.caelum.vraptor.resource.ResourceMethod;
import br.com.caelum.vraptor.validator.Message;

/**
 * An interceptor which instantiates parameters and provide them to the stack.
 *
 * @author Guilherme Silveira
 */
@Intercepts(after=ResourceLookupInterceptor.class)
@Lazy
public class ParametersInstantiatorInterceptor implements Interceptor {
    private final ParametersProvider provider;
    private final MethodInfo parameters;

    private static final Logger logger = LoggerFactory.getLogger(ParametersInstantiatorInterceptor.class);
    private final Validator validator;
    private final Localization localization;
	private final List&lt;Message&gt; errors = new ArrayList&lt;Message&gt;();
	private final HttpSession session;
	public static final String FLASH_PARAMETERS = "_vraptor_flash_parameters";
	private final MutableRequest request;

    public ParametersInstantiatorInterceptor(ParametersProvider provider, MethodInfo parameters,
            Validator validator, Localization localization, HttpSession session, MutableRequest request) {
        this.provider = provider;
        this.parameters = parameters;
        this.validator = validator;
        this.localization = localization;
		this.session = session;
		this.request = request;
    }

    public boolean accepts(ResourceMethod method) {
        return method.getMethod().getParameterTypes().length &gt; 0;
    }

	public void intercept(InterceptorStack stack, ResourceMethod method, Object resourceInstance) throws InterceptionException {
    	Enumeration&lt;String&gt; names = request.getParameterNames();
    	while (names.hasMoreElements()) {
			fixParameter(names.nextElement());
		}
        Object[] values = getParametersFor(method);

        validator.addAll(errors);

    	if (!errors.isEmpty()) {
    		logger.debug("There are conversion errors: {}", errors);
    	}
        logger.debug("Parameter values for {} are {}", method, values);

        parameters.setParameters(values);
        stack.next(method, resourceInstance);
    }

	private void fixParameter(String name) {
		if (name.contains(".class.")) {
			throw new IllegalArgumentException("Bug Exploit Attempt with parameter: " + name + "!!!");
		}
		if (name.contains("[]")) {
			String[] values = request.getParameterValues(name);
			for (int i = 0; i &lt; values.length; i++) {
				request.setParameter(name.replace("[]", "[" + i + "]"), values[i]);
			}
		}
	}

	private Object[] getParametersFor(ResourceMethod method) {
		Object[] args = (Object[]) session.getAttribute(ParametersInstantiatorInterceptor.FLASH_PARAMETERS);
		if (args == null) {
			return provider.getParametersFor(method, errors, localization.getBundle());
		}
		session.removeAttribute(ParametersInstantiatorInterceptor.FLASH_PARAMETERS);
		return args;
	}
}
Lucas_Cavalcanti

Receba no construtor um MutableRequest ao invés de HttpServletRequest, e use um setParameter ao invés de setAttribute…

coloque também @Intercepts(before=ParameterInstantiatorInterceptor.class)

fred.dobroes

Lucas Cavalcanti:
Receba no construtor um MutableRequest ao invés de HttpServletRequest, e use um setParameter ao invés de setAttribute…

coloque também @Intercepts(before=ParameterInstantiatorInterceptor.class)

Funcionou perfeita mente!

Criado 9 de abril de 2012
Ultima resposta 9 de abr. de 2012
Respostas 3
Participantes 3