Spring Security 自定义登录页

时间:2022-07-28
本文章向大家介绍Spring Security 自定义登录页,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.1 自定义登录页面

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登陆</title>
</head>
<body>

--欢迎的登陆系统--
<!-- 提交地址必须为:/login, 用户名为:username, 密码为:password-->
<form action="/login" method="post">
	用户名:<input name="username"><br>
	密码:<input name="password"><br>
	<button>登陆</button>
</form>


</body>
</html>

1.2 修改配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
             xmlns:beans="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans.xsd
                http://www.springframework.org/schema/security
                http://www.springframework.org/schema/security/spring-security.xsd">

    <!-- 设置页面不登陆也可以访问 -->
    <http pattern="/login.html" security="none"></http>
    <http pattern="/login_error.html" security="none"></http>

    <!-- 页面的拦截规则    use-expressions:是否启动 SPEL 表达式 默认是 true -->
    <http use-expressions="false">
        <!-- 当前用户必须有 ROLE_USER 的角色 才可以访问根目录及所属子目录的资源 -->
        <intercept-url pattern="/**" access="ROLE_USER"/>
        
        <!-- 开启表单登陆功能 
	        login.html ☞ 登录页
	        login_error.html ☞ 错误页
	        index.html ☞ 首页 
        -->
        <form-login login-page="/login.html" 
			        default-target-url="/index.html" 
			        authentication-failure-url="/login_error.html"/>
			        
        <!-- 关闭跨站请求伪造 -->
        <csrf disabled="true"/>
    </http>

    <!-- 认证管理器 -->
    <authentication-manager>
        <authentication-provider>
            <user-service>
                <user name="admin" password="123456" authorities="ROLE_USER"/>
            </user-service>
        </authentication-provider>
    </authentication-manager>

</beans:beans>