首先是创建一个maven的web工程,需要导入需要的pom依赖,因为是spring的,所以还需要spring的一些pom依赖,下面是springSecurity的pom依赖
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>
接下来在web.xml中配置filter,springweb组件中有提供一个filter的代理类
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
过滤器的名字必须是springSecurityFilterChain
接下来配置spring的配置文件
<?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>
<!-- 拦截的路径,具有ROLE_USER角色的用户才可以访问资源 -->
<intercept-url pattern="/**" access="hasRole('ROLE_USER')"/>
<!-- 使用表单登录 -->
<form-login/>
</http>
<!-- 认证管理 -->
<authentication-manager>
<authentication-provider>
<user-service>
<!-- 配置登录的用户名和密码还有角色 -->
<user name="root" password="root" authorities="ROLE_USER"/>
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
启动项目,访问 http://localhost:8080/login,默认路径是/login,
默认的登录页面
输入设置的用户和密码以后,第一次登录会出现
这个图标找不到
返回登录页面,再登录一次,就可以正常登录了
<form-login login-page="/login.html" authentication-failure-url="error.html" default-target-url="success.html"/>
可以自定义自己的登录页面,登录错误页面,和登录成功过页面
注意:因为之前的pattern是/**,所以要把登录页面和登录错误页面排除
<!-- 不登陆也可以访问 -->
<http pattern="/login.html" security="none"/>
<http pattern="/error.html" security="none"/>
还要注意一点:html需要增加如下红色部分,才可以使用
<http>
<!-- 拦截的路径,具有ROLE_USER角色的用户才可以访问资源 -->
<intercept-url pattern="/**" access="hasRole('ROLE_USER')"/>
<!-- 使用表单登录 -->
<form-login login-page="/login.html" authentication-failure-url="error.html" default-target-url="success.html"/>
<csrf disabled="true"/>
</http>