如何使用Spring Security自定义登录页面?
我正在将Spring Security用于我的应用程序,这是安全部分,它对用户进行身份validation,但登录页面由Spring Security提供:
@EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { public void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity .authorizeRequests() .antMatchers("/home*").hasRole("USER") .and() .formLogin(); @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user") .password("password") .roles("USER") } }
而不是Spring的登录页面,我想使用我的登录页面,如下所示:
login.html
:
WebApp Dashboard
如何使用我的自定义登录页面而不是Spring Security的登录页面?
请参阅Spring Security参考 :
虽然自动生成的登录页面便于快速启动和运行,但大多数应用程序都希望提供自己的登录页面。 为此,我们可以更新我们的配置,如下所示:
protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") 1 .permitAll(); 2 }
1更新的配置指定登录页面的位置。
2我们必须授予所有用户(即未经身份validation的用户)访问我们的登录页面的权限。 formLogin()。permitAll()方法允许为与基于表单的登录相关联的所有URL授予对所有用户的访问权限。
你修改过的代码:
public void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity .authorizeRequests() .antMatchers("/home*").hasRole("USER") .and() .formLogin() .loginPage("/login.html") .permitAll(); }
httpSecurity.authorizeRequests() .antMatchers("/home*").hasRole("USER").and() .formLogin() .loginPage("/login.html") .permitAll();
loginFormUrl
必须以“/”或绝对URL开头。 并确保可以正确处理请求/login.html
。
顺便说一句:如果您没有配置处理url,处理url将与login page
( /login.html
)url相同,但是在您的登录页面中,操作url是/home.html
,请配置处理url为’/home.html’
.formLogin() .loginProcessingUrl("/home.html") .loginPage("/login.html") .permitAll();
默认情况下启用CSRF
,我在您的登录表单中找不到任何CSRF
令牌。 您可以禁用csrf或使用令牌请求。
http.csrf().disable();