SpringBoot+SpringSecurity系列四:自定义登录页面和退出登录

第一步: 在resources/templates下创建index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>首页</title>
</head>
<body>
<h2>首页</h2>
<a href="openLogin">登录</a>
<a href="userLogout">退出登录</a>
</body>
</html>

第二步:在resources/templates下创建login.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>登录页面</title>
</head>
<body>
<form action="userLogin" method="post">
  <input name="username" value="zhangsan"><br>
  <input name="password" value="1234"><br>
  <input type="submit" value="登录">
</form>
</body>
</html>

第三步:修改SpringSecurity配置文件

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin() //表单登录
                .loginPage("/openLogin") //设置登录页面对应的地址,默认是/login
                .loginProcessingUrl("/userLogin") //设置用户登录时请求的地址,默认是/login
                .and()
                .authorizeRequests()
                //授权
                .antMatchers("/openLogin").permitAll()//放行登录页面:不需要拦截,可以随便访问
                .antMatchers("/openIndex").permitAll()//放行首页:不需要拦截,可以随便访问
                .anyRequest().authenticated()//其它请求都必须认证后才能访问
                .and()
                .logout()
                .logoutUrl("/userLogout")  //自定义退出url
                .logoutSuccessUrl("/openIndex") //退出成功后跳转到的连接
                .and()
                //关闭防火墙:为了保证完整流程可用关闭CSRF安全协议
                .csrf().disable();
    }
}

结果

请添加图片描述

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 11
    评论
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梁云亮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值