01-Spring Security框架学习--入门(二)

时间:2023-03-08 22:20:59
01-Spring Security框架学习--入门(二)

一、入门案例

Spring Security 自定义登录界面

通过之前的一节 01-Spring Security框架学习--入门(一)的简单演示,Spring security 使用框架自带的登录界面,下面的案例将使用自己定义的登录页面。

基本步骤

  1. 添加如下页面:
  • 登录界面 src/main/webapp/login.html
   <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<h3>自定义的登录界面</h3>
<form action="/login" method="post">
用户名: <input type="text" name="username"><br>
密码: <input type="password" name="password"><br>
<input name="submit" type="submit" value="登陆">
</form>
</body>
</html>
  • 登录结果页面 src/main/webapp/login_error.html
    <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录错误</title>
</head>
<body>
<span style="color:red">用户名或密码错误,无权访问!</span>
</body>
</html>
  1. 修改Spring-security.xml 配置

    src/main/resources/spring/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> <!-- 页面的链接规则 -->
<http use-expressions="false">
<intercept-url pattern="/**" access="ROLE_ADMIN" />
<!-- 开启表单提交功能(注意:路径前'/'符号不可省略)-->
<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="admin" authorities="ROLE_ADMIN" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>manager>
</beans:beans>

运行效果

01-Spring Security框架学习--入门(二)

运行问题

  1. 如下错误:HTTP Status 403 - Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.

    01-Spring Security框架学习--入门(二)

    这是由于Spring security 默认开启防范CSRF攻击导致,目前demo演示关闭即可。

二、Spring security 的总结

  1. 通过路上的简单的配置,Spring security 为我们将我们很多的事情:
  • 在你的应用中每个URL都要求认证
  • 为你生成一个登陆表单
  • 允许用户在表单中提交 Username 用户名为user 以及 Password 密码为 password 来进行认证
  • 允许用户注销
  • 防范CSRF攻击
  • 防范Session Fixation
  • 集成Security Header
  1. spring security的基本原理

spring 通过servlet的拦截器``拦截HTTP请求,在这个过滤链的作用下用户认证和授权。

01-Spring Security框架学习--入门(二)

如果想深入了解原理流程【请移步】