Не удается установить флаг Spring Boot XSRF-TOKEN как безопасный в браузере

#java #spring #spring-boot

#java — язык #spring #пружинный ботинок #java #spring-boot

Вопрос:

Я запускаю отчет о безопасности, который указывает, что для cookie установлено значение secure = False. Также на изображении ниже показано, что в XSRF-TOKEN не отмечен столбец Secure. Я хотел бы знать, есть ли какой-либо способ установить для этого флага безопасное значение TRUE

введите описание изображения здесь

Я добавил в свой application.properties запись:

сервер.сервлет.сеанс.файл cookie.безопасный = true

И я установил конфигурацию WebSecurityConfiguration как:

 @Configuration
@EnableWebSecurity 
//@EnableGlobalMethodSecurity(prePostEnabled = true) 
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {


    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/", "/assets/**", "/*.css", "/*.js", "index.html");
    } 

    @Override
    protected void configure(HttpSecurity http) throws Exception {
         http
         .httpBasic()
         .authenticationEntryPoint(new CeaAuthenticationEntryPoint())
         .and()
         .authorizeRequests()
           .antMatchers("/index.html", "/", "/home", "/login","/logout", "/assets/**").permitAll() 
             .and()
         .csrf()
             .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()); 


    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS", "DELETE", "PUT", "PATCH"));
        configuration.setAllowedHeaders(Arrays.asList("X-Requested-With", "Origin", "Content-Type", "Accept", "Authorization"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}
  

Комментарии:

1. Это должно сработать, какую версию Spring Boot вы используете? Я знаю, что путь к свойству изменился с 1.x на 2.x (например, server.session.cookie.secure на server.servlet.session.cookie.secure который вы используете)

2. Я уже добавил его, и не сработало, сэр

Ответ №1:

Я исправляю это, создавая пользовательский CustomCookieCsrfTokenRepository, который вызывает сам себя в методе с помощью httponlyfalse , также жестко кодируя атрибуты ниже, однако мне пришлось прокомментировать параметр setHttpOnly, поскольку Angular нужно, чтобы это было открыто для его чтения.

  • cookie.setSecure(true);
  • //cookie.setHttpOnly(true);
  • файл cookie.setPath(«/»);

 import java.lang.reflect.Method;
import java.util.UUID;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.util.WebUtils;

import org.springframework.security.web.csrf.*;


public class CustomCookieCsrfTokenRepository implements CsrfTokenRepository {
    static final String DEFAULT_CSRF_COOKIE_NAME = "XSRF-TOKEN";

    static final String DEFAULT_CSRF_PARAMETER_NAME = "_csrf";

    static final String DEFAULT_CSRF_HEADER_NAME = "X-XSRF-TOKEN";

    private String parameterName = DEFAULT_CSRF_PARAMETER_NAME;

    private String headerName = DEFAULT_CSRF_HEADER_NAME;

    private String cookieName = DEFAULT_CSRF_COOKIE_NAME;

    private final Method setHttpOnlyMethod;

    private boolean cookieHttpOnly;

    private String cookiePath;

    public CustomCookieCsrfTokenRepository() {
        this.setHttpOnlyMethod = ReflectionUtils.findMethod(Cookie.class, "setHttpOnly", boolean.class);
        if (this.setHttpOnlyMethod != null) {
            this.cookieHttpOnly = true;
        }
    }

    @Override
    public CsrfToken generateToken(HttpServletRequest request) {
        return new DefaultCsrfToken(this.headerName, this.parameterName,
                createNewToken());
    }

    @Override
    public void saveToken(CsrfToken token, HttpServletRequest request,
            HttpServletResponse response) {
        String tokenValue = token == null ? "" : token.getToken();
        Cookie cookie = new Cookie(this.cookieName, tokenValue);

        cookie.setSecure(true);
        //cookie.setHttpOnly(true);
        cookie.setPath("/");

        if (this.cookiePath != null amp;amp; !this.cookiePath.isEmpty()) {
                cookie.setPath(this.cookiePath);
        } else {
                cookie.setPath(this.getRequestContext(request));
        }
        if (token == null) {
            cookie.setMaxAge(0);
        }
        else {
            cookie.setMaxAge(-1);
        }
        if (cookieHttpOnly amp;amp; setHttpOnlyMethod != null) {
            ReflectionUtils.invokeMethod(setHttpOnlyMethod, cookie, Boolean.TRUE);
        }

        response.addCookie(cookie);
    }

    @Override
    public CsrfToken loadToken(HttpServletRequest request) {
        Cookie cookie = WebUtils.getCookie(request, this.cookieName);
        if (cookie == null) {
            return null;
        }
        String token = cookie.getValue();
        if (!StringUtils.hasLength(token)) {
            return null;
        }
        return new DefaultCsrfToken(this.headerName, this.parameterName, token);
    }

    /**
     * Sets the name of the HTTP request parameter that should be used to provide a token.
     *
     * @param parameterName the name of the HTTP request parameter that should be used to
     * provide a token
     */
    public void setParameterName(String parameterName) {
        Assert.notNull(parameterName, "parameterName is not null");
        this.parameterName = parameterName;
    }

    /**
     * Sets the name of the HTTP header that should be used to provide the token.
     *
     * @param headerName the name of the HTTP header that should be used to provide the
     * token
     */
    public void setHeaderName(String headerName) {
        Assert.notNull(headerName, "headerName is not null");
        this.headerName = headerName;
    }

    /**
     * Sets the name of the cookie that the expected CSRF token is saved to and read from.
     *
     * @param cookieName the name of the cookie that the expected CSRF token is saved to
     * and read from
     */
    public void setCookieName(String cookieName) {
        Assert.notNull(cookieName, "cookieName is not null");
        this.cookieName = cookieName;
    }

    /**
     * Sets the HttpOnly attribute on the cookie containing the CSRF token.
     * The cookie will only be marked as HttpOnly if both <code>cookieHttpOnly</code> is <code>true</code> and the underlying version of Servlet is 3.0 or greater.
     * Defaults to <code>true</code> if the underlying version of Servlet is 3.0 or greater.
     * NOTE: The {@link Cookie#setHttpOnly(boolean)} was introduced in Servlet 3.0.
     *
     * @param cookieHttpOnly <code>true</code> sets the HttpOnly attribute, <code>false</code> does not set it (depending on Servlet version)
     * @throws IllegalArgumentException if <code>cookieHttpOnly</code> is <code>true</code> and the underlying version of Servlet is less than 3.0
     */
    public void setCookieHttpOnly(boolean cookieHttpOnly) {
        if (cookieHttpOnly amp;amp; setHttpOnlyMethod == null) {
            throw new IllegalArgumentException("Cookie will not be marked as HttpOnly because you are using a version of Servlet less than 3.0. NOTE: The Cookie#setHttpOnly(boolean) was introduced in Servlet 3.0.");
        }
        this.cookieHttpOnly = cookieHttpOnly;
    }

    private String getRequestContext(HttpServletRequest request) {
        String contextPath = request.getContextPath();
        return contextPath.length() > 0 ? contextPath : "/";
    }

    /**
     * Factory method to conveniently create an instance that has
     * {@link #setCookieHttpOnly(boolean)} set to false.
     *
     * @return an instance of CookieCsrfTokenRepository with
     * {@link #setCookieHttpOnly(boolean)} set to false
     */
    public static CustomCookieCsrfTokenRepository withHttpOnlyFalse() {
        CustomCookieCsrfTokenRepository result = new CustomCookieCsrfTokenRepository();
        result.setCookieHttpOnly(false);
        return resu<
    }

    private String createNewToken() {
        return UUID.randomUUID().toString();
    }

    /**
     * Set the path that the Cookie will be created with. This will override the default functionality which uses the
     * request context as the path.
     *
     * @param path the path to use
     */
    public void setCookiePath(String path) {
        this.cookiePath = path;
    }

    /**
     * Get the path that the CSRF cookie will be set to.
     *
     * @return the path to be used.
     */
    public String getCookiePath() {
        return this.cookiePath;
    }
}
  

Комментарии:

1. Привет, спасибо за ответ. Но как этот класс можно использовать в конфигурации безопасности?

2. ……csrf().csrfTokenRepository(новый пользовательский cookiecsrftokenrepository());

3. @this.srivastava это ответ

Ответ №2:

Вы можете просто создать метод в WebSecurityConfiguration таком:

  private CookieCsrfTokenRepository csrfTokenRepository() {
    final CookieCsrfTokenRepository repository = CookieCsrfTokenRepository.withHttpOnlyFalse();
    repository.setSecure(true);
    return repository;
  }
  

и установите его в configure() :

 .csrf().csrfTokenRepository(csrfTokenRepository())
  

наконец, ваш конфигурационный файл будет:

    @Configuration
@EnableWebSecurity 
//@EnableGlobalMethodSecurity(prePostEnabled = true) 
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {


    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/", "/assets/**", "/*.css", "/*.js", "index.html");
    } 


   private CookieCsrfTokenRepository csrfTokenRepository() {
    final CookieCsrfTokenRepository repository = CookieCsrfTokenRepository.withHttpOnlyFalse();
    repository.setSecure(true);
    return repository;
  }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
         http
         .httpBasic()
         .authenticationEntryPoint(new CeaAuthenticationEntryPoint())
         .and()
         .authorizeRequests()
           .antMatchers("/index.html", "/", "/home", "/login","/logout", "/assets/**").permitAll() 
             .and()
          .csrf().csrfTokenRepository(csrfTokenRepository())


}

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("*"));
    configuration.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS", "DELETE", "PUT", "PATCH"));
    configuration.setAllowedHeaders(Arrays.asList("X-Requested-With", "Origin", "Content-Type", "Accept", "Authorization"));
    configuration.setAllowCredentials(true);
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}
  

}