Настройка безопасности Spring для отображения стилей

#spring #spring-security

#spring #spring-безопасность

Вопрос:

У меня проблема. Мои стили не работают для пользователей, не прошедших проверку подлинности.

Вот моя конфигурация безопасности:

 @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/registration").permitAll()
                .anyRequest()
                    .authenticated()
                .and()
                    .formLogin()
                    .loginPage("/login")
                    .defaultSuccessUrl("/hello")
                    .permitAll()
                .and()
                    .logout()
                    .logoutSuccessUrl("/hello")
                    .permitAll();
    }
 

Также вот моя конфигурация для стилей:

 @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/styles/**")
                .addResourceLocations("/WEB-INF/resources/css/");
    }
 

И вот моя страница простого стиля:

 <!DOCTYPE html>
<html xmlns:sec="http://www.w3.org/1999/xhtml" xmlns:th="http://www.w3.org/1999/xhtml">

<head>
    <meta charset="UTF-8"/>
    <link rel="stylesheet" type="text/css"
          href="/styles/demo.css">
    <title>Welcome</title>
</head>

<body>
    <div class="red-text">
        Red text
    </div>
    <br>
    <div class="green-text">
        Green text
    </div>
    <span sec:authorize="isAuthenticated()">
        <h1>Welcome, <span sec:authentication="name">Username</span></h1>
        <form th:action="@{/logout}" method="post">
            <input type="submit" value="Log out"/>
        </form>
    </span>
<br>

<input type="button" class="button" onclick="sayHello();"
       value="Click me!">

</body>
</html>
 

Я заметил, что это произошло после того, как я добавил эту строку в конфигурацию безопасности:

 .anyRequest().authenticated()
 

Ответ №1:

 .antMatchers("/styles/**").permitAll()