所以我是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");
}
}
网站的设计方式是,用户转到urlhttp://localhost:8080,然后他/她会看到初始页面,那里有一个login
选项卡,他/她可以在其中登录,然后转到dashboard
视图(我稍后会添加)。然而,当我加载初始页面时,页面的配置完全错误(没有加载css/js/images资源)。我去之后http://localhost:8080/login,执行登录,一切都恢复正常。
因此,表单的任何urlhttp://localhost:8080是允许的(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();
}
}
如何正确配置我的网页?
***注意事项:*我目前没有任何控制器类。
我发现regex匹配器的问题是从服务器加载的任何资源都需要在映射中说明。
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login", "/admin").hasRole('ADMIN') // e.g. for pages that need to be authenticated
.anyRequest().permitAll() // all the others will be accessable by all
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
}
最简单的匹配方法是以下步骤:
- 通过重写addResourceHandlers来声明资源文件
- 使用antmatcher来处理url安全性(更简单、更容易),除非您有具有关键参数的动态url
对不起,伙计,我会尽力澄清
anyRequest().authenticated()
使您对html资源的请求需要授权。您只允许All为'/'&'/登录'
因此,将permitAll添加到css、js和image中http
.authorizeRequests()
.regexMatchers("/", "/index").permitAll()
.antMatchers("/**/*.js", "/**/*.css").permitAll()
或者更简单的是,为登录页面创建一个样式。不依赖于其他静态资源。