Невозможно загрузить статический контент в Spring Security - PullRequest
0 голосов
/ 28 сентября 2018

Я построил базовую службу аутентификации Spring из этого источника: https://spring.io/guides/gs/securing-web/

Попытался включить файлы JS из локальных папок, используя почти все решения на стеке, но я не смог.При загрузке html-страницы выдается:
«Uncaught ReferenceError: myFunction не определена» *

Вот мой скрипт home.html:

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
    <head>
        <title>Spring Security Example</title>
        <script type="javascript" src="test.js"></script>
    </head>
    <body onload="myFunction()">
        <h1>Welcome!</h1>

        <p>Click <a href="/hello">here</a> to see a greeting.</p>
    </body>
</html>

Здесь находится мой js-файлнаходится, и htmls помещаются в папку шаблонов.

enter image description here

вот мой код mvcConfig:

package hello;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;


@Configuration
public class MvcConfig implements WebMvcConfigurer {

    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/home").setViewName("home");
        registry.addViewController("/").setViewName("home");
        registry.addViewController("/hello").setViewName("redirect:http://localhost:3000/home.html");
        registry.addViewController("/login").setViewName("login");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if (!registry.hasMappingForPattern("/webjars/**")) {
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");
    }
    if (!registry.hasMappingForPattern("/**")) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/", "classpath:/resources/","classpath:/static/", "classpath:/public/");
    }

    registry.addResourceHandler("/resources/**")
        .addResourceLocations("/resources/");


}

}

Код WebSecurityConfig:

package hello;

import org.springframework.context.annotation.Bean;
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.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/home","/resources/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

@Bean
@Override
public UserDetailsService userDetailsService() {
    UserDetails user =
         User.withDefaultPasswordEncoder()
            .username("user")
            .password("password")
            .roles("USER")
            .build();

    return new InMemoryUserDetailsManager(user);
}

}

Ответы [ 2 ]

0 голосов
/ 28 сентября 2018

В классе WebSecurityConfig вы устанавливаете для allowAll только '/', '/home' и '/resources/**'.Анонимный пользователь может получить доступ к этим трем конечным точкам без проверки безопасности.

Для файла test.js src указывает на test.js в текущем URL.Поэтому, когда вы запускаете его на локальном хосте, браузер пытается найти test.js как http://localhost:{port}/{current-page-url}/test.js

Например, если страница находится под /home, то браузер вызывает http://localhost:8080/home/test.js, но, как вы определилив WebSecurityConfig любой вызов, кроме самого /home, будет заблокирован Spring Security.(/home - это не то же самое, что /home/**)

Так что вам нужно изменить URL-адрес источника на <script src="/resources/test.js"></script> Поскольку любой объект в конечной точке /resources/** может быть доступен любому, и онуже зарегистрирован в конфигурации resourceHandler в MvcConfig

    registry.addResourceHandler("/resources/**")
    .addResourceLocations("classpath:/");

Надеюсь, это поможет!Happy Coding:)

ADD:

Кроме того, в теге <script> вы должны изменить атрибут type на text/javascript, или вы можете просто удалитьатрибут, и он будет работать.

0 голосов
/ 28 сентября 2018

Независимо от того, какая папка находится в src / main / resources, вы можете настроить их следующим образом: создайте этот метод в своем классе конфигурации безопасности, обычно мы помещаем статические ресурсы в статическую папку внутри src / main / resources.

//this method allows static resources to be neglected by spring security
        @Override
        public void configure(WebSecurity web) throws Exception {
            web
                .ignoring()
                .antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**","/assets/**","/fonts/**","/dis/**","/vendor1/**");
        }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...