【发布时间】:2014-07-25 21:27:41
【问题描述】:
我正在尝试在我的 Spring-Boot 项目中使用 Spring Security。
我的项目结构是:
/project
-/src/main
-- /java
-- / resources
--- /static
---- /css
---- /fonts
---- /libs
--- /templates
---- /all html files
这是我的 gradle 设置:
apply plugin: 'java'
apply plugin: 'groovy'
apply plugin: 'idea'
apply plugin: 'spring-boot'
apply plugin: 'jacoco'
apply plugin: 'war'
apply plugin: 'maven'
project.ext {
springBootVersion = '1.0.2.RELEASE'
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-web:$springBootVersion")
compile("org.springframework.boot:spring-boot:1.0.1.RELEASE")
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
compile("org.springframework.boot:spring-boot-starter-data-jpa:$springBootVersion")
compile("org.springframework.security:spring-security-web:4.0.0.M1")
compile("org.springframework.security:spring-security-config:4.0.0.M1")
...
}
我的每个 html 文件都有这个:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta name="description" content=""/>
<link href="/css/bootstrap.css" rel="stylesheet"/>
<link href="/css/bootstrap.min.css" rel="stylesheet"/>
<link href="/css/bootstrap-responsive.css" rel="stylesheet"/>
<link href="/css/bootstrap-responsive.min.css" rel="stylesheet"/>
<link href="/css/ofac.css" rel="stylesheet"/>
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet"/>
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
这是我的 MVC 配置: @配置 公共类 MvcConfig 扩展 WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController( "/home" ).setViewName( "index" );
registry.addViewController( "/" ).setViewName( "index" );
registry.addViewController( "/about" ).setViewName( "about" );
registry.addViewController( "/login" ).setViewName( "login" );
registry.addViewController( "/upload" ).setViewName( "upload" );
registry.addViewController( "/status" ).setViewName( "status" );
registry.addViewController( "/search" ).setViewName( "search" );
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName( "lang" );
registry.addInterceptor( localeChangeInterceptor );
}
@Bean
public LocaleResolver localeResolver() {
CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver();
cookieLocaleResolver.setDefaultLocale( StringUtils.parseLocaleString( "en" ) );
return cookieLocaleResolver;
}
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasenames( "classpath:messages/messages", "classpath:messages/validation" );
// if true, the key of the message will be displayed if the key is not
// found, instead of throwing a NoSuchMessageException
messageSource.setUseCodeAsDefaultMessage( true );
messageSource.setDefaultEncoding( "UTF-8" );
// # -1 : never reload, 0 always reload
messageSource.setCacheSeconds( 0 );
return messageSource;
}
根据我在网上找到的各种示例,我有以下安全配置:
@Configuration
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource datasource;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers( "/resources/**" ).permitAll();
http
.formLogin().failureUrl("/login?error")
.defaultSuccessUrl("/")
.loginPage("/login")
.permitAll()
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login")
.permitAll();
http
.authorizeRequests().anyRequest().authenticated();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
JdbcUserDetailsManager userDetailsService = new JdbcUserDetailsManager();
userDetailsService.setDataSource( datasource );
PasswordEncoder encoder = new BCryptPasswordEncoder();
auth.userDetailsService( userDetailsService ).passwordEncoder( encoder );
auth.jdbcAuthentication().dataSource( datasource );
if ( !userDetailsService.userExists( "user" ) ) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add( new SimpleGrantedAuthority( "USER" ) );
User userDetails = new User( "user", encoder.encode( "password" ), authorities );
userDetailsService.createUser( userDetails );
}
}
}
当我导航到localhost:9001 时,系统会提示我登录页面。我提供了正确的凭据并被重定向到 url:http://localhost:9001/css/ofac.css 显示了我的 css 文件的内容。在我添加安全性之前,页面会正确呈现。登录成功后,会显示 css,但如果我将根导航回“/”,那么一切都会正常运行。
谁能看到我在这里做错了什么?
更新: 我删除了以下内容,因为 Spring-boot 将处理 /resources/**
http
.authorizeRequests()
.antMatchers( "/resources/**" ).permitAll();
我还将成功登录的重定向更改为:
.defaultSuccessUrl("/home")
因为那也映射到“/”
但是,行为是相同的。一个有趣的行为是,当我使用 Safari 时,登录会给我“http://localhost:9001/css/bootstrap.css”但 Firefox 会给我“http://localhost:9001/css/bootstrap-responsive.min.css”
当我使用 Firebug 检查 POST http://localhost:9001/login 时,我得到一个“302 Found”,然后是一个返回 200 的 GET http://localhost:9001/css/bootstrap-responsive.min.css。
【问题讨论】:
-
/css受到保护,因此一旦请求该 URL,登录后就会显示登录信息,您将被重定向到触发登录的 URL。我希望您的 css 在/resources/**下可用,否则包括/css/**和permitAll()。 -
我的 /css 文件在 /resources 下(更新了原始帖子以显示这一点),所以我相信它会与我的 ".authorizeRequests() .antMatchers( "/resources/**" ) 一起暴露。 permitAll();"
-
显然有些东西正在请求不是来自该目录的 CSS 检查您的模板。
-
要记住的一点是,Spring Boot 会自动公开
/static下的所有内容。见docs.spring.io/spring-boot/docs/current/reference/html/… -
不,它不是……正如我之前提到的,
/css/受到保护。您需要将其添加到您的全部许可中。它们在资源下的事实仅在 mavensrc/main/resources中是正确的,这是一个默认的 maven 文件夹,它将被添加到您的类路径中。你要做的就是让/css等全部配置permitAll。
标签: spring-security spring-boot