以后可能要涉及到Spring Security ,在网上找资料挺多,因为第一次弄,搞的我看到后忘了前面,最后看了官方的tutorial,参考后研究出了
最基本的使用方法,暂时不去考虑高级用法,Spring Security使用了AOP思想,所以对安全方面使用起来很方便,加去自如。
我看了下通过提供role和auth,于url和method上提供许多验证机制(Provider),验证数据可以基于SQL或是LDAP等,
我写了下一个简单的基本配置的用户登录应用使用ss2(Spring Security 2进行了包装,使配置更加简化):
一.加载Spring security Filter
二.配置Security Information
下面详细讲解:
1.导入spring所需jar包,和spring security 2所需jar , 从官方下载后从里面tutorial的lib里拷就行了
2.配置web.xml:
3.配置applicationContext-security.xml
参考tutorial里的文件作一些修改
主要讲一下<http>的内容
<http auto-config="true">
<intercept-url pattern="/login.jsp*" filters="none"/>
<intercept-url pattern="/**" access="ROLE_USER" />
<form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?error=true" default-target-url="/index.jsp" />
<logout logout-success-url="/login.jsp"/>
<concurrent-session-control max-sessions="1" exception-if-maximum-exceeded="true"/>
</http>
首先看 auto-comfig这个东东,把这个设成true,系统会自己加上以下内容
<form-login />
<anonymous />
<http-basic />
<logout />
<remember-me />
这些东西,我这里自己写了一些,那么就会覆盖默认的设置,
<intercept-url /> : 用来告诉ss2哪些url不用Filter去处理了
<form-login/> :去定义一些关于表单的页面文件
<concurrent-session-control /> :就是控制登录次数了
<authentication-provider/>
这里就是设置验证信息了,你可以从数据库取得:
<authentication-provider>
<jdbc-user-service data-source-ref="securityDataSource"/>
</authentication-provider>
这里的"securityDataSource"就是 DataSource bean在application context里的名字,它指向了包含着Spring Security用户信息的表。 另外,你
可以配置一个Spring Security JdbcDaoImpl bean,使用user-service-ref属性指定:
<authentication-provider user-service-ref='myUserDetailsService'/>
<beans:bean id="myUserDetailsService" class="org.springframework.security.userdetails.jdbc.JdbcDaoImpl">
<beans:property name="dataSource" ref="dataSource"/>
</beans:bean>
<password-encoder hash="md5"/> :是密码加密机制还还其它的, 如:sha
如果是自定义userdetail的话要自己实现UserDetail和UserDetailService两个接口,告诉ss2如何取得
像上面定义的 用户名和密码 代码如下:
实现UserDetailService Interface
我直接设置了值,当然可以从数据库等地方去获取User
实现UserDetail Interface:
getAuthorities()里的autorities 可以从其它你想要的地方获取
如果是上面这种方式的话,applicationContext-security.xml里我要加下面的东西:
以前的直接设置帐号的可以comment掉了{
<!--
<authentication-provider>
<password-encoder hash="md5"/>
<user-service>
<user name="rod" password="a564de63c2d0da68cf47586ee05984d7" authorities="ROLE_SUPERVISOR, ROLE_USER, ROLE_TELLER" />
<user name="dianne" password="65d15fe9156f9c4bbffd98085992a44e" authorities="ROLE_USER,ROLE_TELLER" />
<user name="scott" password="2b58af6dddbd072ed27ffc86725d7d3a" authorities="ROLE_USER" />
<user name="peter" password="22b5c9accc6e1ba628cedc63a72d57f8" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
-->
}
以上配置只是最基本的配置,一些高级web特性先没有弄,一步一步来嘛!从简单入手.
4.创建页面
首先 login.jsp
注意:要用ss2的功能表单书写上有讲究:
form的action要到 j_spring_security_check
username和password的name分别为:j_username j_password
其次 index.jsp (登录通过后到的页面)
这里退出要到: j_spring_security_logout
这样就会按照你配置信息去work了.
好这就是一个最最简单的应用ss2了.