Spring Security总结(二)

继上一篇文章Spring Security总结(一)


用户自定义登陆页

实际开发中,我们不可能使用系统生成的登陆页,而是使用我们自己的登陆页。

构建登陆页login.html

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登陆</title>
</head>
<body>    
    <!-- /login是Spring Security的默认登陆访问路径 -->
    <form action='/login' method='POST'>
        <table>
            <tr>
                <td>用户名:</td>
                <td><input type='text' name='username' value=''></td>
            </tr>
            <tr>
                <td>密码:</td>
                <td><input type='password' name='password' /></td>
            </tr>
            <tr>
                <td colspan='2'><input name="submit" type="submit"
                    value="登陆" /></td>
            </tr>
        </table>
    </form>
</body>
</html>

构建登陆失败页login_error.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    用户名或者密码错误!
</body>
</html>

spring-security.xml

<?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" />
        <!-- 开启表单登陆功能 -->
        <form-login login-page="/login.html" default-target-url="/index.html" authentication-failure-url="/login_error.html"/>
        <!-- 关闭csrf -->
        <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>

security="none"  设置此资源不被拦截。

如果你没有设置登录页security="none"  ,将会出现以下错误

因为登录页会被反复重定向。

login-page:指定登录页面。

default-target-url:指定了成功进行身份验证和授权后默认呈现给用户的页面。
authentication-failure-url:指定了身份验证失败时跳转到的页面。

csrf disabled="true"  关闭csrf ,如果不加会出现如下错误

CSRFCross-site request forgery)跨站请求伪造,也被称为“One Click Attack”或者Session Riding,通常缩写为CSRF或者XSRF,是一种对网站的恶意利用。

原文地址:https://www.cnblogs.com/chuanqi1995/p/11579185.html