Spring Security - 08 自定义登录页面和登录表单参数

文章目录

  • 环境
  • 项目结构
  • 自定义登录页面和登录表单参数
  • 测试
  • 参考

环境

操作系统:

Windows 10 x64

集成开发环境:

Spring Tool Suite 4 
Version: 4.12.1.RELEASE
Build Id: 202110260750

浏览器(客户端):

Firefox Browser
96.0.3 (64 位)

项目结构

参考:Spring Security - 07 在内存中认证(添加用户到内存中)

Spring Security - 08 自定义登录页面和登录表单参数_第1张图片

自定义登录页面和登录表单参数

修改 pom.xml 配置文件,添加 Thymeleaf 依赖:

<dependency>
	<groupId>org.springframework.bootgroupId>
	<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>

修改 WebSecurityConfigurer 配置类,重写 configure(HttpSecurity) 方法(第 27 ~ 57 行):

package com.mk.security.config.annotation.web.configuration;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.FormLoginConfigurer;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.User.UserBuilder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;

//@Configuration
@EnableWebSecurity
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    // 其他保持不变...
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        http.formLogin(); // 默认的表单登录配置
        
        // 写法一:自定义的表单登录配置
//        http.formLogin((configurer) ->
//            configurer
//                .usernameParameter("username")
//                .passwordParameter("password")
//                .loginPage("/authentication/login")
//                .failureUrl("/authentication/login?failed")
//                .loginProcessingUrl("/authentication/login/process")
//                .permitAll()
//        );
        // 写法二:自定义的表单登录配置
        http.formLogin(new Customizer<FormLoginConfigurer<HttpSecurity>>() {
            
            @Override
            public void customize(FormLoginConfigurer<HttpSecurity> configurer) {
                configurer
                    .usernameParameter("username")
                    .passwordParameter("password")
                    .loginPage("/authentication/login")
                    .failureUrl("/authentication/login?failed")
                    .loginProcessingUrl("/authentication/login/process")
                    .permitAll(true);
            }
        });
        
        http.authorizeRequests((requests) -> requests.anyRequest().authenticated());
    }
}

新建 /Spring-Security-Hello/src/main/resources/templates/login.html 登录页面:

注意:这里使用 Thymeleaf 模板,其会自动为我们添加 CSRF Token,稍后请在测试中注意观察。

DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org">
    <head>
        <title>Please Log Intitle>
    head>
    <body>
        <h1>Please Log Inh1>
        <div th:if="${param.failed}">
            Invalid username and password.div>
        <div th:if="${param.logout}">
            You have been logged out.div>
        <form th:action="@{/authentication/login/process}" method="post">
            <div>
            <input type="text" name="username" placeholder="Username"/>
            div>
            <div>
            <input type="password" name="password" placeholder="Password"/>
            div>
            <input type="submit" value="Log in" />
        form>
    body>
html>

新建 LoginController 控制器类,当我们访问 /authentication/login 时,令其返回上面的登录页面:

package com.mk.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class LoginController {

    @GetMapping("/authentication/login")
    public String login() {
        return "login"; // 指向 templates/login.html 登录页面
    }
}

以上参数的对应关系是这样的:

Spring Security - 08 自定义登录页面和登录表单参数_第2张图片

测试

启动项目,打开浏览器,如果你已经登录,请重启浏览器,防止遗留的认证信息干扰本次测试。

访问 http://localhost:8080/principal,Spring Security 将我们重定向至 http://localhost:8080/authentication/login,让我们使用 lisi 用户登录。第一次我们使用错误的密码进行登录,第二次我们使用正确的密码进行登录,请注意两次的区别:

注意:当我们自定义登录页面和登录表单参数之后,默认的退出登录就不可用了!

Spring Security - 08 自定义登录页面和登录表单参数_第3张图片

参考

Spring Security > Servlet Applications > Authentication > Username/Password > Reading Username/Password > Form / Form Login

你可能感兴趣的:(Spring,Security,spring,java,spring,security,登录页面,自定义)