【发布时间】:2016-03-22 01:38:58
【问题描述】:
所以我是Spring 的新手,并且在我使用Spring-Boot 开发Web 应用程序的过程中学习。
目前我的页面由两个html 页面组成:index.html 和login.html。我也在使用Spring-Security。
这是我目前的MvcConfig:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/login").setViewName("login");
}
}
网站的设计方式是,用户访问网址http://localhost:8080,然后他/她会看到初始页面,那里有一个login 选项卡,他/她可以在其中登录,然后转到dashboard 视图(稍后我会添加)。
但是,当我加载初始页面时,页面完全配置错误(未加载 css / js / images 资源)。在我转到http://localhost:8080/login 后,执行登录,一切都恢复正常。
因此,http://localhost:8080 形式的任何 url 都是允许的 (index.html),但其他任何内容都需要登录。
这是我的Spring-Security 配置:
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.regexMatchers("/", "/index").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
}
如何正确配置我的网页?
*** 备注: * 我目前没有任何 Controller 类。
【问题讨论】:
-
将 permitAll 添加到 css、js、图像
http .authorizeRequests() .regexMatchers("/", "/index", "/**/*.js", ""/**/*.css"").permitAll()因为anyRequest().authenticated()将您的请求授权给 html 资源。或者更简单,为登录页面制作样式 -
@ThangHoang 你能更好地制定你的答案吗?
-
将 permitAll 添加到 css、js、图像
http .authorizeRequests() .regexMatchers("/", "/index", "/**/*.js", ""/**/*.css"").permitAll()因为anyRequest().authenticated()将您的请求授权给 html 资源。或者更简单,为登录页面制作样式。不依赖静态资源。 -
@ThangHoang 你能在答案中补充一下吗?
-
@philippe 避免使用 regexMatchers,除非您的应用程序确实依赖于超复杂的动态 url 模式。那么管理它的工作量要大得多。使用更简单的 antMatcher,因为它使用基本的 url 输入(/login、/admin、仪表板等),并且不会干扰您尝试和使用的任何资源文件。如果您走这条路,很乐意提供答案。
标签: java html spring security spring-mvc