Tôi đang cố gắng sử dụng Spring Security trong dự án Spring-Boot của mình.Cấu hình Spring-Boot & Spring-Security
cấu trúc dự án của tôi là:
/project
-/src/main
-- /java
--/resources
--- /static
---- /css
---- /fonts
---- /libs
--- /templates
---- /all html files
Dưới đây là các thiết lập gradle tôi:
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")
...
}
Mỗi file html của tôi có này:
<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>
Đây là MVC Config của tôi: @Configuration lớp công khai MvcConfig mở rộng WebMvcConfigurerAd apter {
@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;
}
Dựa trên ví dụ khác nhau tôi thấy trên mạng, tôi đã cấu hình bảo mật sau:
@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);
}
}
}
Khi tôi hướng đến localhost:9001
Tôi nhắc với trang đăng nhập của tôi. Tôi cung cấp thông tin xác thực chính xác và được chuyển hướng đến url: http://localhost:9001/css/ofac.css
nội dung của tệp css của tôi được hiển thị. Trước khi tôi thêm bảo mật, các trang sẽ hiển thị chính xác. Khi đăng nhập thành công, css được hiển thị, nhưng nếu tôi điều hướng gốc trở lại "/" thì mọi thứ sẽ hoạt động như bình thường.
Có ai có thể thấy những gì tôi đang làm sai ở đây không?
Cập nhật: Tôi đã gỡ bỏ sau vì mùa xuân-boot sẽ xử lý/nguồn/**
http
.authorizeRequests()
.antMatchers("/resources/**").permitAll();
Tôi cũng đã thay đổi chuyển hướng cho lần đăng nhập thành công:
.defaultSuccessUrl("/home")
vì cũng được ánh xạ tới "/"
Tuy nhiên, hành vi là như nhau. Một hành vi thú vị là khi tôi sử dụng Safari, đăng nhập sẽ cho tôi "http://localhost:9001/css/bootstrap.css
" nhưng Firefox sẽ cho tôi "http://localhost:9001/css/bootstrap-responsive.min.css
"
Khi tôi kiểm tra việc POST http://localhost:9001/login
với Firebug tôi nhận được một "302 Found" theo sau là một GET http://localhost:9001/css/bootstrap-responsive.min.css
trả về một 200.
'/ css' được bảo vệ ngay sau khi yêu cầu URL đó đăng nhập được hiển thị sau khi đăng nhập, bạn sẽ được chuyển hướng đến url đã kích hoạt đăng nhập. Tôi hy vọng rằng css của bạn đã có sẵn trong '/ resources/**' khác bao gồm '/ css/**' với một 'allowAll()'. –
Tệp/css của tôi nằm trong/tài nguyên (cập nhật bài đăng gốc để hiển thị bài viết này) vì vậy tôi tin rằng nó sẽ được hiển thị với "của tôi".authorizeRequests() .antMatchers ("/ resources/**") .permitAll(); " – sonoerin
Dường như có điều gì đó đang yêu cầu một css không phải từ thư mục đó kiểm tra các mẫu của bạn. –