SpringSecurity6从入门到实战之自定义登录页面

SpringSecurity6从入门到实战之自定义登录页面

在使用SpringSecurity进行认证操作的时候,可以发现默认提供的登录页面比较简陋.那么我们能否对登录页面进行自定义配置呢?接下来开始讲解应该如何进行配置

自定义登录页面流程

引入模板依赖

由于自定义登录页面会使用到前端相关技术,这里需要引入thymeleaf依赖

xml 复制代码
<!--thymeleaf-->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

在 templates 中定义登录界面

html 复制代码
<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>自定义登录页面</title>
</head>
<body>
<h1>用户登录</h1>
<form method="post" th:action="@{/doLogin}">
    用户名:<input name="uname" type="text"/><br>
    密码:<input name="upass" type="password"/><br>
    <input type="submit" value="登录"/>
</form>
</body>
</html>

定义登录页面 controller

新建LoginController

java 复制代码
@Controller
public class LoginController {

    @RequestMapping("/login.html")
    public String login() {
        return "login";
    }
}

这里直接访问localhost:8080/login.html会发现还是会需要进行认证操作,因为我们在自定义配置中还没有进行放行

定义 Spring Security 配置类

java 复制代码
@Configuration
@EnableWebSecurity
public class MySecurityConfig {
    // 自定义表单认证
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests()
                .requestMatchers("/test").permitAll() // 放行该资源
                .requestMatchers("/login.html").permitAll() // 放行该资源
                .anyRequest().authenticated() // 其它请求 必须先认证通过后 才能访问
                .and().formLogin() // 开启表单认证
                .loginPage("/login.html")  // 默认登录页
                .loginProcessingUrl("/doLogin")  // 处理登录请求的url
                .usernameParameter("uname") // 用户名文件框的名称
                .passwordParameter("upass") // 密码框的名称
                .and().csrf().disable();  //关闭 CSRF
        ;

        return http.build();
    }
}

可以发现这里的配置项都是跟login.html中的内容一一对应

测试

这里就可以发现访问需要认证的/hello会跳转到我们自定义的登录页面来了

输入账号密码进行认证


最终发现通过认证操作可以访问/hello接口了

相关推荐
f***R819 小时前
HeidiSQL导入与导出数据
java
q***71011 天前
Spring Boot(快速上手)
java·spring boot·后端
n***84071 天前
十七:Spring Boot依赖 (2)-- spring-boot-starter-web 依赖详解
前端·spring boot·后端
better_liang1 天前
每日Java面试场景题知识点之-分布式事务处理
java·微服务·面试·springcloud·分布式事务
爱学习的小可爱卢1 天前
JavaEE进阶——SpringMVC响应处理详解
spring boot·postman·javaee
q***96581 天前
Spring Cloud Data Flow 简介
后端·spring·spring cloud
7***68431 天前
Spring Boot 从 2.7.x 升级到 3.3注意事项
数据库·hive·spring boot
L***d6701 天前
Spring Boot 各种事务操作实战(自动回滚、手动回滚、部分回滚)
java·数据库·spring boot
凌波粒1 天前
Springboot基础教程(3)--自动装配原理/静态资源处理/欢迎页
java·spring boot·后端
java_logo1 天前
MySQL Server Docker 容器化部署指南
linux·运维·数据库·docker·容器