这篇文章将为大家详细讲解有关Spring security中怎么自定义登录页面,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
实现步骤
1. 复制上一示例的源码
重命名包名 case2 为 case3
重命名 Case2Application.java 为 Case3Application.java
2. 在 WebSecurityConfig 中配置登录页
在 config(HttpSecurity http) 方法中对 formLogin 选项进行配置。需要包含以下设置:
放行自定义登录页 url,例如: /login.html;
设置登录跳转页 url, 例如: /login.html;
禁用 csrf 保护。如不添加此项,则需要每次从 cookie 中获取 csrftoken 的值并随表单一同提交到服务端。
完整代码如下:
package net.txt100.learn.springsecurity.base.case3.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
/**
* Title: WebSecurityConfig
* Package: net.txt100.learn.springsecurity.base.case3.config
* Creation date: 2019-08-11
* Description:
*
* @author <a href="zgjt_tongl@thunis.com">Tonglei</a>
* @since 1.0
*/
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder() {
// 配置密码的保护策略,spring security 默认使用 bcrypt 加密算法。
// 此处只要显式声明 BCryptPasswordEncoder Bean 即可
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
UsernamePasswordAuthenticationFilter up;
http
.csrf().disable() // 关闭 CSRF 保护功能,否则不支持 Post 请求
.authorizeRequests() // 针对 HttpServletRequest 进行安全配置
.antMatchers("/login.html").permitAll() // login.html 页面无需登录即可访问
.anyRequest().authenticated() // 对所有 Request 均需安全认证
.and().formLogin()
.loginPage("/login.html") // 每当需要登录时浏览器跳转到 login.html 页面
.loginProcessingUrl("/login") // 自定义登录提交地址,默认地址是 /login, 默认处理器是 UsernamePasswordAuthenticationFilter
// .usernameParameter("/phone_number") // 自定义登录用户ID参数,默认是 username
// .passwordParameter("/check_code") // 自定义登录口令参数,默认是 password
.and().httpBasic(); // 定义如何验证用户,此项代表弹出浏览器认证窗口
}
}
3. 创建 login.html 页面
新建目录 src/main/webapp,并在该目录下创建文件 login.html。需要至少包含:
form 标签,并且 action 赋值为 WebSecurityConfig 中 loginProcessingUrl 配置地址 (默认: "/login");
用户名参数,与 WebSecurityConfig 中 usernameParameter 配置一致(默认:"username");
密码参数,与 WebSecurityConfig 中 passwordParameter 配置一致(默认:"password")。
关于Spring security中怎么自定义登录页面就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。