欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringSecurity学习1

程序员文章站 2022-07-05 08:14:33
...

先建立一个简单的例子:

 

1.引入SpringSecurity相关的jar:spring-security-core、spring-security-config、spring-security-web以及其他相关的jar

 

2.在web.xml中配置filter,其中filter的名称为springSecurityFilterChain,不能改变

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

 3.在一个spring的application context文件中进行安全配置

<?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"
	xmlns:context="http://www.springframework.org/schema/context"
	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.0.xsd 
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
	<http use-expressions="true">
	    <intercept-url pattern="/login.html" filters="none"/>
	    <intercept-url pattern="/loginfail.html" filters="none"/>
		<intercept-url pattern="/loginsucc.html" access="hasAnyRole('user')" />
		<intercept-url pattern="/resource.html" access="hasAnyRole('admin')" />
		
		<form-login login-page="/login.html" login-processing-url="/login.shtml" 
		    default-target-url="/loginsucc.html" authentication-failure-url="/loginfail.html"/>
		    
		<!-- 配置退出页面 -->
		<logout logout-url="/logout.shtml" logout-success-url="/login.html" />
		<anonymous enabled="false"/>
	</http>
	
	<authentication-manager>
		<authentication-provider>
			<user-service>
				<user name="lan" password="111111" authorities="user" />
			</user-service>
		</authentication-provider>
	</authentication-manager>

</beans:beans>

 
4.登录页面表单,用户名和密码要用j_usernamej_password

<form action="/login.shtml" method="post">
     用户名:<input type="text" name="j_username" id="username" /><br>
     密码:<input type="password" name="j_password" id="password" /><br>
      <input type="submit" value="登录"/>
</form>

5.该例子的效果是login.html和loginfail.html的访问不受限制,有user权限的用户可以访问loginsucc.html,有admin权限的用户可以访问resource.html。如果直接在地址栏输入url访问收保护的资源,将跳转到login.html页面,如果登录成功,跳转到loginsucc.html页面。登入成功后尝试访问resource.html会显示403页面。