Spring Security静态资源和Webjar问题(Spring Boot 2)

时间:2018-10-13 11:02:05

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

我在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 Security配置:

@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)。 Web配置中的更改:

@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状态代码也消失了。

2 个答案:

答案 0 :(得分:0)

请求尝试获取loginStyle.css文件且未授予。 您应该将permision添加到您的css文件夹中,所以请替换此行:

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

与其他内容相同

答案 1 :(得分:0)

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

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>webjars-locator</artifactId>
    <version>0.30</version>
</dependency>
相关问题