Partage
  • Partager sur Facebook
  • Partager sur Twitter

Spring boot httpSecurity : mon filtre marche pas

    30 avril 2022 à 17:45:52

    Bonjour ,
    Je suis en train de concevoir une api rest pour qu'un utilisateur puisse s'authentifier, j'utilise pour ça les cookies j'ai voulu utiliser Spring sécurité, j'ai tourvé un bout de code sur stackoverflow mais il ne marche pas!
    C'est un filtre mais la fonction addFiltreBefore ne le prend pas en compte on dirait!
    Voici mon code :
    package com.app.test.config;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.config.http.SessionCreationPolicy;
    import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
    
    @Configuration
    @EnableWebSecurity
    class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    	@Override
    	public void configure(HttpSecurity httpSecurity) throws Exception {
    
    		/*
    		 * httpSecurity.cors().and().authorizeRequests().antMatchers("/api/**").
    		 * permitAll().and().httpBasic().and() .csrf().disable();
    		 * httpSecurity.headers().frameOptions().disable();
    		 */
    
    		httpSecurity.cors().and().authorizeRequests().antMatchers("/api/Users/login").permitAll().anyRequest()
    				.authenticated().and().httpBasic().and().sessionManagement()
    				.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().csrf().disable();
    
    		httpSecurity.addFilterBefore(new CheckAuthCookieFilter(), BasicAuthenticationFilter.class);
    
    	}
    }
    
    package com.app.test.config;
    
    import java.util.Collections;
    import java.util.Enumeration;
    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.Map;
    import java.util.Set;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletRequestWrapper;
    
    public final class MutableHttpServletRequest extends HttpServletRequestWrapper {
        // holds custom header and value mapping
        private final Map<String, String> customHeaders;
    
        public MutableHttpServletRequest(HttpServletRequest request) {
            super(request);
            this.customHeaders = new HashMap<String, String>();
        }
    
        public void putHeader(String name, String value) {
            this.customHeaders.put(name, value);
        }
    
        public String getHeader(String name) {
            // check the custom headers first
            String headerValue = customHeaders.get(name);
    
            if (headerValue != null) {
                return headerValue;
            }
            // else return from into the original wrapped object
            return ((HttpServletRequest) getRequest()).getHeader(name);
        }
    
        public Enumeration<String> getHeaderNames() {
            // create a set of the custom header names
            Set<String> set = new HashSet<String>(customHeaders.keySet());
    
            // now add the headers from the wrapped request object
            Enumeration<String> e = ((HttpServletRequest) getRequest()).getHeaderNames();
            while (e.hasMoreElements()) {
                // add the names of the request headers into the list
                String n = e.nextElement();
                set.add(n);
            }
    
            // create an enumeration from the set and return
            return Collections.enumeration(set);
        }
    }
    
    package com.app.test.config;
    
    import java.io.IOException;
    import java.net.URLDecoder;
    
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServletRequest;
    
    public class CheckAuthCookieFilter implements Filter {    
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
    
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(httpServletRequest);
    
            Cookie[] cookies = httpServletRequest.getCookies();
    
            if (cookies != null && cookies.length > 0) {
                for (Cookie cookie : cookies) {                
                    if (cookie.getName().equals("user-id")) {
                    	System.out.println(cookie.getName() + " : " + cookie.getValue());
                        mutableRequest.putHeader(cookie.getValue(), URLDecoder.decode(cookie.getValue(), "utf-8"));                    
                    }
                }
            }
    
            chain.doFilter(mutableRequest, response);
        }
    }
    
    Pouvez vous m'aider svp ?
    Cdt.


    • Partager sur Facebook
    • Partager sur Twitter

    Android est SKYNET !

    Spring boot httpSecurity : mon filtre marche pas

    × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
    × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
    • Editeur
    • Markdown