Spring 安全性 - 重定向到自定义登录页面,而无需通过控制器



我目前正在使用Spring Boot + Spring Security来开发一个简单的网站,需要用户登录才能访问它。我已经在resources/templates1/bruceLogin1.html下创建了自己的自定义静态登录页面。任何未经许可访问我的网站首先被重定向到登录页面 URL

,这是 http://localhost:8080/templates1/bruceLogin1.html注意:我没有为此登录 URL 创建任何控制器,因此我希望直接绕过控制器访问 bruceLogin1.html。因为我直接允许访问这个 html 页面而不通过控制器,所以我假设不需要视图解析器(例如 thymleaf(。

我打开浏览器,输入 http://localhost:8080/blablabl,浏览器将我重定向到 http://localhost:8080/templates1/bruceLogin1.html,但遗憾的是,我得到了错误

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sat Jan 11 12:40:37 SGT 2020
There was an unexpected error (type=Not Found, status=404).
No message available

以下是我的配置,


@SpringBootApplication
@EnableWebSecurity
public class SpringSecurityCatalogApplication  implements WebMvcConfigurer {
public static void main(String[] args) {
SpringApplication.run(SpringSecurityCatalogApplication.class, args);
}

@EnableWebSecurity
@Order(Ordered.HIGHEST_PRECEDENCE)
class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/templates1/bruceLogin1.html")
.permitAll();
}
}

}

想想不要放在资源/模板 1 文件夹下,我只会将自定义登录页面放入资源/静态或资源/公共文件夹中。 然后按如下所示进行配置

@EnableWebSecurity
@Order(Ordered.HIGHEST_PRECEDENCE)
class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/bruceLogin1.html")
.permitAll();
}
}

打开浏览器并访问任何URL,您将被重定向到 http://localhost:8080/bruceLogin1.html。 就是这样!
请注意,这不需要任何控制器或视图解析程序。

相关内容

最新更新