SpringSecurity最基本的配置使用

来源:互联网 发布:淘宝上的斗神摇杆 编辑:程序博客网 时间:2024/05/16 09:44

一、配置web.xml

web.xml中配置一个spring提供的过滤器springSecurityFilterChain,并且mapping这个过滤器让所有的url请求都经过这个过滤器;

<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>

二、配置Security的xml

可以在普通的applicationContext.xml中配置,最好是新建一个专门配置SpringSecurity的xml。注意web.xml中的<context-param>可以扫描到自己配置的applicationContext-security.xml。

applicationContext-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-3.0.xsd                        http://www.springframework.org/schema/security                         http://www.springframework.org/schema/security/spring-security-3.1.xsd"><http auto-config="true"><intercept-url pattern="/**" access="ROLE_USER" /></http><authentication-manager><authentication-provider><user-service><user name="admin" password="admin" authorities="ROLE_USER,ROLE_ADMIN"/><user name="shenggang" password="shenggang" authorities="ROLE_USER"/></user-service></authentication-provider></authentication-manager></beans:beans>
注意:这里的web安全服务是通过<http>元素进行配置的。下面详细解释具体关键配置代码:
<http auto-config="true"><intercept-url pattern="/**" access="ROLE_USER" /></http>
<http>元素是所有web相关的命名空间的上级元素,这里拦截了所有的请求url,并且允许拥有ROLE_USER权限的人才能访问。
<http auto-config="true">其实是如下信息的缩写:
<http><span style="white-space:pre"></span><from-login/><span style="white-space:pre"></span><http-basic/><span style="white-space:pre"></span><logout/></http>
对应了登陆、浏览认证、注销。
可以自己指定登陆时的页面:
<http auto-config="true"><intercept-url pattern="/login.jsp*"/ access="IS_AUTHENTICATED_ANONYMOUSLY"><intercept-url pattern="/**" access="ROLE_USER" /><form-login login-page='/login.jsp'/></http>
指定的<form-login>元素会覆盖掉上面的默认选项,因此auto-config可以继续使用没有影响。由于需要通过自己定义的login.jsp去登陆,所以这个页面可不能被拦截,所以添加了一个<intercept-url>的标签,让这个页面放行。

0 0
原创粉丝点击