[英]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.