簡體   English   中英

無法在Spring Security中加載靜態內容

[英]Unable to load static content in spring security

我已經從以下來源構建了基本的spring身份驗證服務: https : //spring.io/guides/gs/securing-web/

試圖使用Stackoverflow上的幾乎所有解決方案包括本地文件夾中的JS文件,但我不能。 當html頁面加載時,它說:
“未捕獲的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放置在模板文件夾中。

在此處輸入圖片說明

這是我的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);
}

}

無論文件夾位於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/**");
        }

WebSecurityConfig類中,將permitAll設置為僅'/''/home''/resources/**' 匿名用戶無需安全檢查即可訪問這三個端點。

對於test.js文件,src指向當前URL中的test.js 所以,當你在本地主機上運行,瀏覽器嘗試找到test.jshttp://localhost:{port}/{current-page-url}/test.js

例如,如果頁面位於/home則瀏覽器將調用http://localhost:8080/home/test.js ,但是正如您在WebSecurityConfig定義的那樣,除/home之外的任何調用都將被Spring Security阻止。 /home/home/**

因此,您需要做的是將src URL更改為<script src="/resources/test.js"></script>因為/resources/**端點下的任何內容都可以被任何人訪問,並且已經被注冊。在MvcConfig的resourceHandler配置中

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

希望這可以幫助! 快樂編碼:)

新增:

同樣,在<script>標記中,您應該將type屬性更改為text/javascript或者只需刪除該屬性即可使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM