SpringBoot 集成 SpringSecurity 详解(七)-- 自定义登录页面

SpringBoot 集成 SpringSecurity 详解(七)-- 自定义登录页面

需求缘起

系统默认的登录页面不友好,这一节我们来实现自定义登录页面。
本节是在第六小节的基础上继续开发。

本节 demo

技术要点

  1. 编写登录界面
  2. 配置页面和登录路径等

1.编辑登录界面

编写login.html界面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
<h2>自定义登录页面</h2>
<form action="/authentication/form" method="post">
    <table>
        <tr>
            <td>用户名:</td>
            <td><input type="text" name="username"></td>
        </tr>
        <tr>
            <td>密码:</td>
            <td><input type="password" name="password"></td>
        </tr>
        <tr>
            <td colspan="2">
                <button type="submit">登录</button>
            </td>
        </tr>
    </table>
</form>
</body>
</html>

2.配置Spring Security的登录页面路径

@Configuration
@EnableWebSecurity//开启Spring Security的功能
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启方法安全级别的控制
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        //SpringSecurity 提供的一种编码器,我们也可以自己实现PasswordEncoder
        return new BCryptPasswordEncoder();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        super.configure(http);
        http.formLogin()
                .loginPage("/login.html")// 自定义登录页面路径
                .loginProcessingUrl("/authentication/form")// 自定义页面的登录路径,注意要与登录页面的action值一致,<form action="/authentication/form" method="post">
                .and()
                .authorizeRequests() // 定义哪些URL需要被保护、哪些不需要被保护
                .antMatchers("/login.html").permitAll()// 设置所有人都可以访问登录页面
                .anyRequest().authenticated()  // 除了以上的请求外都需要身份验证
        ;
        http.csrf().disable();// 禁用跨站攻击
    }
}

3.测试

重启应用,访问http://localhost:8080/hello/helloUser
现在的界面已经变成了我们自定义的界面,如下所示
在这里插入图片描述
然后输入用户名密码即可访问。

提示:

  1. login.html 要放在resource/static 目录下;
  2. 配置的 loginProcessingUrl 参数中的值要与界面中action中的值一致。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值