【问题标题】:Spring Security static resources and webjars issue (Spring Boot 2)Spring Security 静态资源和 webjars 问题(Spring Boot 2)
【发布时间】:2018-10-13 11:02:05
【问题描述】:

我正在努力解决 Spring Security 从文件夹和 webjars 获取静态资源的问题。项目结构如下:

.
├── pom.xml
├── src/main/resources
│   ├── static
│   │   ├── css
│   │   │   └── loginStyle.css
│   │   ├── js
│   │   └── images
│   │       ├── myLogo.svg

这是我的网络配置:

@EnableWebMvc
@Configuration
@ComponentScan
public class AdherenceWebConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/webjars/**", "/resources/**").addResourceLocations("/webjars/", "/resources/").resourceChain(false);
        WebMvcConfigurer.super.addResourceHandlers(registry);
    }

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.jsp("/WEB-INF/views/", ".jsp");
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // this will map uri to jsp view directly without a controller
        registry.addViewController("/adherence/login").setViewName("loginView");
    }
}

Spring 安全配置:

@Configuration
@EnableWebSecurity
public class AdherenceWebSecurityConfig extends WebSecurityConfigurerAdapter 
{
    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception { 
    http
        .authorizeRequests()
            .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
            .antMatchers("/webjars/**", "/resources/**").permitAll()
            .anyRequest().permitAll()
            .and()
        .formLogin()
            .loginPage("/adherence/login")
            .permitAll()
            .and()
        .logout().permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .userDetailsService(userDetailsService)
            .passwordEncoder(bCryptPasswordEncoder());
    }
}

loginView.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport"
	content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link href="src/main/resources/static/favicon.ico" rel="icon"
	type="image/x-icon">

<link rel="stylesheet" type="text/css"
	href="/webjars/bootstrap/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="/css/loginStyle.css" />

<script type="text/javascript" src="/webjars/jquery/jquery.min.js"></script>
<script type="text/javascript"
		src="/webjars/bootstrap/js/bootstrap.min.js"></script>

<title>BARMER Adherence Tool</title>
</head>

<body>
	<div class="container">
		<div class="wrapper">
			<form class="form-signin">
				<h3 class="form-signin-heading">
					<img src="/images/myLogo.svg" alt="Barmer_Logo" />
					<br />
					<b>Adherence Tool</b>
				</h3>
				<span>${message}</span>
				<input type="text" class="form-control" name="u_name"/>
				<br />
				<input type="password" class="form-control" name="u_pass"/>
				<span>${error}</span>

				<button class="btn btn-lg btn-primary btn-block btn-cstyle"
					name="Submit" value="Login" type="Submit">Login</button>
			</form>
		</div>
	</div>

</body>
</html>

我得到:

No mapping found for HTTP request with URI [/css/loginStyle.css] in 
DispatcherServlet with name 'dispatcherServlet'
2018-10-13 12:52:05.507  WARN 796 --- [nio-8088-exec-6] 
o.s.web.servlet.PageNotFound             : No mapping found for HTTP request 
with URI [/images/myLogo.svg] in DispatcherServlet with name 
'dispatcherServlet'

对于每个 jscsssvg,都为 404。

在我使用 Spring Security 之前,所有这些资源都已正确加载。我正在使用 Spring Boot 2.0.4

============================UPDATE-1============== ========================== 我有一些成功。我现在可以从 webjar 加载资源,但不幸的是我自己的资源仍然存在问题(HTTP 状态代码 302)。网络配置更改:

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/webjars/**", "/resources/**")
    .addResourceLocations("/webjars/", "/resources/")
    .resourceChain(false).addResolver(new WebJarsResourceResolver());
    WebMvcConfigurer.super.addResourceHandlers(registry);
}

loginView.jsp 的变化:

<link rel="stylesheet" type="text/css" href="/static/css/loginStyle.css" />
...
<h3 ...>
    <img src="/static/images/myLogo.svg" />
... />

new result are shown here。将路径更改为例如/css/loginStyle.css 结果为 404。我还添加了我的 project-structure

============================UPDATE-2============== ==========================

感谢@Pasha Gharibi

registry.addResourceHandler("/webjars/**", "/static/**")
.addResourceLocations("/webjars/", "classpath:/static/")
.resourceChain(false).addResolver(new WebJarsResourceResolver());

这对我来说终于成功了。现在我的自托管文件的 302 状态码也不见了。

【问题讨论】:

  • 您正在使用/css/loginStyle.css 访问您的CSS,但您的Web 配置添加了addResourceHandler("/webjars/**", "/resources/**") 的映射。无论有没有 Spring Security,这都不应该工作。

标签: spring-mvc spring-boot spring-security


【解决方案1】:

Request 尝试获取 loginStyle.css 文件并且没有授权。 您应该向您的 css 文件夹添加权限,所以替换这一行:

.antMatchers("/webjars/**", "/resources/**", "/css/**").permitAll()

其他的也一样

【讨论】:

  • 这就是 OP 已经在做的事情,请参阅他的 Spring Security 配置。但是,缺少权限应该导致 403 而不是 404。
  • 你是对的!也许路径不正确,我的意思是 .addResourceLocations("classpath:/resources/static/")
【解决方案2】:

可能你需要在 pom.xml 中添加 webjars 定位器。

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>webjars-locator</artifactId>
    <version>0.30</version>
</dependency>

【讨论】:

    猜你喜欢
    • 2017-11-02
    • 2016-05-04
    • 1970-01-01
    • 2017-05-02
    • 2016-10-01
    • 2015-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多