[英]Correctly configuring Spring with security - Java
因此,我是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");
}
}
网站的设计方式是,用户转到url http:// localhost:8080 ,然后向他/她显示初始页面,那里是一个login
选项卡,他/她可以在其中登录并移动到dashboard
视图(稍后将添加)。 但是,当我加载初始字母时,页面完全配置错误(未加载CSS / JS /图像资源)。 在我访问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类。
抱歉,我会尽力弄清楚
anyRequest().authenticated()
使您对html资源的请求需要授权。 您只允许All进入'/'&'/ login'
因此,也将allowAll添加到css,js,图像中http .authorizeRequests() .regexMatchers("/", "/index").permitAll() .antMatchers("/**/*.js", "/**/*.css").permitAll()
或更简单,为登录页面设置样式。 不依赖于其他静态资源。
我发现正则表达式匹配器的问题是从服务器加载的任何资源,您都需要在映射中说明。
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();
}
}
进行匹配的最简单方法是执行以下步骤:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.