小试Spring Security 2 收藏
以后可能要涉及到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:
- <!-- Spring security 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 >
- <!-- Spring security Filter End -->
- <!-- listener for defend login many times -->
- < listener >
- < listener-class > org.springframework.security.ui.session.HttpSessionEventPublisher </ listener-class >
- </ listener > /
3.配置applicationContext-security.xml
参考tutorial里的文件作一些修改
- <?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-2.5.xsd
- http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.4.xsd">
- <beans:bean id="loggerListener" class = "org.springframework.security.event.authentication.LoggerListener" />
- <global-method-security secured-annotations="enabled" >
- <!-- AspectJ pointcut expression that locates our "post" method and applies security that way
- <protect-pointcut expression="execution(* bigbank.*Service.post*(..))" access= "ROLE_TELLER" />
- -->
- </global-method-security>
- <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>
- <!-- All of this is unnecessary if auto-config= "true"
- <form-login />
- <anonymous />
- <http-basic />
- <logout />
- <remember-me /> -->
- <!--
- Usernames/Passwords are
- rod/koala
- dianne/emu
- scott/wombat
- peter/opal
- -->
- <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>
- </beans:beans>
主要讲一下<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
- public class UserDetailsSerivceImpl implements UserDetailsService {
- //private UserDao userDao;
- // public UserDao getUserDao() {
- // return userDao;
- // }
- @Override
- public UserDetails loadUserByUsername(String username)
- throws UsernameNotFoundException, DataAccessException {
- // return (User)getUserDao().findByName(username);
- User userDetails=new User();
- // peter/opal
- userDetails.setUsername("peter" );
- userDetails.setPassword("22b5c9accc6e1ba628cedc63a72d57f8" );
- return userDetails;
- }
- }
我直接设置了值,当然可以从数据库等地方去获取User
实现UserDetail Interface:
- public class User implements UserDetails {
- /**
- * @author chao.yin
- */
- private static final long serialVersionUID = -8118972725674341185L;
- private String user_id;
- private String username;
- private String password;
- @Override
- /**
- * return roles list
- */
- public GrantedAuthority[] getAuthorities() {
- //can get data from database
- List <GrantedAuthority>authorities=new ArrayList<GrantedAuthority>();
- authorities.add(new GrantedAuthorityImpl( "ROLE_USER" ));
- authorities.add(new GrantedAuthorityImpl( "ROLE_SUPERVISOR" ));
- return authorities.toArray( new GrantedAuthority[ 0 ]);
- }
- @Override
- public String getPassword() {
- return password;
- }
- @Override
- public String getUsername() {
- return username;
- }
- @Override
- public boolean isAccountNonExpired() {
- return true ;
- }
- @Override
- public boolean isAccountNonLocked() {
- return true ;
- }
- @Override
- public boolean isCredentialsNonExpired() {
- return true ;
- }
- @Override
- public boolean isEnabled() {
- return true ;
- }
- public String getUser_id() {
- return user_id;
- }
- public void setUser_id(String user_id) {
- this .user_id = user_id;
- }
- public void setUsername(String username) {
- this .username = username;
- }
- public void setPassword(String password) {
- this .password = password;
- }
- }
getAuthorities()里的autorities 可以从其它你想要的地方获取
如果是上面这种方式的话,applicationContext-security.xml里我要加下面的东西:
- < authentication-provider user-service-ref = "userDatailsService" >
- < password-encoder hash = "md5" />
- </ authentication-provider >
- < beans:bean id = "userDatailsService" class = "impl.UserDetailsSerivceImpl" />
以前的直接设置帐号的可以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
- < form name = "f" action = "<s:url value=" /j_spring_security_check" /> " method = "POST" >
- < table >
- < tr > < td > User: </ td > < td > < input type = 'text' name = 'j_username' value =' < s:if test ="${not empty
- m.error}"> ${SPRING_SECURITY_LAST_USERNAME} </ s:if > ' /> </ td > </ tr >
- < tr > < td > Password: </ td > < td > < input type = 'password' name = 'j_password' > </ td > </ tr >
- < tr > < td > < input type = "checkbox" name = "_spring_security_remember_me" > </ td > < td > Remember Me </ td > </ tr >
- < tr > < td > < input name = "submit" type = "submit" value = "Login" > </ td > < td > < input name = "reset" type = "reset" > </ td > </ tr >
- </ table >
- </ form >
注意:要用ss2的功能表单书写上有讲究:
form的action要到 j_spring_security_check
username和password的name分别为:j_username j_password
其次 index.jsp (登录通过后到的页面)
- < %@ taglib prefix = "sec" uri = "http://www.springframework.org/security/tags" % >
- < h4 > Hello < FONT color = "red" > < sec:authentication property = "principal.username" /> </ FONT > </ h4 >
- < p > < a href = "${pageContext.request.contextPath}/j_spring_security_logout" mce_href = "${pageContext.request.contextPath}/j_spring_security_logout" " > Logout </ a >
这里退出要到: j_spring_security_logout
这样就会按照你配置信息去work了.
好这就是一个最最简单的应用ss2了.