Spring Security 2

本文介绍SpringSecurity2的基础配置方法,包括加载过滤器、配置安全信息等步骤,并提供了简单的登录示例。适用于初次接触SpringSecurity2的开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原创   小试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:

  1. <!-- Spring security Filter -->   
  2.     < filter >   
  3.       < filter-name > springSecurityFilterChain </ filter-name >   
  4.       < filter-class > org.springframework.web.filter.DelegatingFilterProxy </ filter-class >   
  5.     </ filter >   
  6.     < filter-mapping >   
  7.       < filter-name > springSecurityFilterChain </ filter-name >   
  8.       < url-pattern > /* </ url-pattern >   
  9.     </ filter-mapping >   
  10. <!-- Spring security Filter End -->   
  11. <!-- listener for defend login many times -->   
  12. < listener >   
  13.       < listener-class > org.springframework.security.ui.session.HttpSessionEventPublisher </ listener-class >   
  14. </ listener > /  

3.配置applicationContext-security.xml
参考tutorial里的文件作一些修改

  1. <?xml version= "1.0"  encoding= "UTF-8" ?>  
  2. <beans:beans xmlns="http://www.springframework.org/schema/security"   
  3.     xmlns:beans="http://www.springframework.org/schema/beans"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd   
  6.                         http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.4.xsd">   
  7.       
  8.     <beans:bean id="loggerListener"   class = "org.springframework.security.event.authentication.LoggerListener"  />  
  9.       
  10.     <global-method-security secured-annotations="enabled" >  
  11.         <!-- AspectJ pointcut expression that locates our "post"  method and applies security that way  
  12.         <protect-pointcut expression="execution(* bigbank.*Service.post*(..))"  access= "ROLE_TELLER" />  
  13.         -->  
  14.     </global-method-security>  
  15.       
  16.       
  17.     <http auto-config="true" >  
  18.         <intercept-url pattern="/login.jsp*"  filters= "none" />  
  19.         <intercept-url pattern="/**"  access= "ROLE_USER"  />  
  20.         <form-login login-page="/login.jsp"  authentication-failure-url= "/login.jsp?error=true"   default -target-url= "/index.jsp"  />  
  21.         <logout logout-success-url="/login.jsp" />  
  22.         <!--<concurrent-session-control max-sessions="1"  exception- if -maximum-exceeded= "true" />-->  
  23.     </http>  
  24.       
  25.     <!-- All of this   is  unnecessary  if  auto-config= "true"   
  26.         <form-login />  
  27.         <anonymous />  
  28.         <http-basic />  
  29.         <logout />  
  30.         <remember-me /> -->  
  31.     <!--  
  32.     Usernames/Passwords are  
  33.         rod/koala  
  34.         dianne/emu  
  35.         scott/wombat  
  36.         peter/opal  
  37.     -->  
  38.     <authentication-provider>  
  39.         <password-encoder hash="md5" />  
  40.         <user-service>  
  41.             <user name="rod"  password= "a564de63c2d0da68cf47586ee05984d7"  authorities="ROLE_SUPERVISOR, ROLE_USER,   
  42. ROLE_TELLER" />  
  43.             <user name="dianne"  password= "65d15fe9156f9c4bbffd98085992a44e"  authorities= "ROLE_USER,ROLE_TELLER"  />  
  44.             <user name="scott"  password= "2b58af6dddbd072ed27ffc86725d7d3a"  authorities= "ROLE_USER"  />  
  45.             <user name="peter"  password= "22b5c9accc6e1ba628cedc63a72d57f8"  authorities= "ROLE_USER"  />  
  46.         </user-service>  
  47.     </authentication-provider>  
  48.       
  49. </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

  1. public   class  UserDetailsSerivceImpl  implements  UserDetailsService {  
  2.     //private UserDao userDao;     
  3.          
  4.     // public UserDao getUserDao() {     
  5.     //         return userDao;     
  6.     // }     
  7.       
  8.     @Override   
  9.     public  UserDetails loadUserByUsername(String username)  
  10.             throws  UsernameNotFoundException, DataAccessException {  
  11.         // return (User)getUserDao().findByName(username);   
  12.           
  13.         User userDetails=new  User();  
  14.         // peter/opal   
  15.         userDetails.setUsername("peter" );  
  16.         userDetails.setPassword("22b5c9accc6e1ba628cedc63a72d57f8" );  
  17.           
  18.         return  userDetails;  
  19.     }  
  20. }  

我直接设置了值,当然可以从数据库等地方去获取User

实现UserDetail Interface:

  1. public   class  User  implements  UserDetails {  
  2.     /**  
  3.      * @author chao.yin  
  4.      */   
  5.     private   static   final   long  serialVersionUID = -8118972725674341185L;  
  6.       
  7.     private  String user_id;  
  8.     private  String username;  
  9.     private  String password;  
  10.       
  11.     @Override   
  12.     /**  
  13.      * return roles list  
  14.      */   
  15.     public  GrantedAuthority[] getAuthorities() {  
  16.         //can get data from database   
  17.           
  18.         List <GrantedAuthority>authorities=new  ArrayList<GrantedAuthority>();  
  19.         authorities.add(new  GrantedAuthorityImpl( "ROLE_USER" ));  
  20.         authorities.add(new  GrantedAuthorityImpl( "ROLE_SUPERVISOR" ));  
  21.           
  22.         return  authorities.toArray( new  GrantedAuthority[ 0 ]);  
  23.     }  
  24.     @Override   
  25.     public  String getPassword() {  
  26.         return  password;  
  27.     }  
  28.     @Override   
  29.     public  String getUsername() {  
  30.         return  username;  
  31.     }  
  32.     @Override   
  33.     public   boolean  isAccountNonExpired() {  
  34.         return   true ;  
  35.     }  
  36.     @Override   
  37.     public   boolean  isAccountNonLocked() {  
  38.         return   true ;  
  39.     }  
  40.     @Override   
  41.     public   boolean  isCredentialsNonExpired() {  
  42.         return   true ;  
  43.     }  
  44.     @Override   
  45.     public   boolean  isEnabled() {  
  46.         return   true ;  
  47.     }  
  48.     public  String getUser_id() {  
  49.         return  user_id;  
  50.     }  
  51.     public   void  setUser_id(String user_id) {  
  52.         this .user_id = user_id;  
  53.     }  
  54.     public   void  setUsername(String username) {  
  55.         this .username = username;  
  56.     }  
  57.     public   void  setPassword(String password) {  
  58.         this .password = password;  
  59.     }  
  60. }  

getAuthorities()里的autorities 可以从其它你想要的地方获取

如果是上面这种方式的话,applicationContext-security.xml里我要加下面的东西:

  1. < authentication-provider   user-service-ref = "userDatailsService" >   
  2.     < password-encoder   hash = "md5" />   
  3. </ authentication-provider >   
  4.   
  5. < 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 

  1. < form   name = "f"   action = "<s:url value=" /j_spring_security_check" />method = "POST" >   
  2.   
  3.   < table >   
  4.     < tr > < td > User: </ td > < td > < input   type = 'text'   name = 'j_username'   value =' < s:if   test ="${not empty   
  5. m.error}"> ${SPRING_SECURITY_LAST_USERNAME} </ s:if > ' /> </ td > </ tr >   
  6.     < tr > < td > Password: </ td > < td > < input   type = 'password'   name = 'j_password' > </ td > </ tr >   
  7.     < tr > < td > < input   type = "checkbox"   name = "_spring_security_remember_me" > </ td > < td > Remember Me </ td > </ tr >   
  8.     < tr > < td > < input   name = "submit"   type = "submit"   value = "Login" > </ td > < td > < input   name = "reset"   type = "reset" > </ td > </ tr >   
  9.   </ table >   
  10. </ form >   

注意:要用ss2的功能表单书写上有讲究:

form的action要到 j_spring_security_check
username和password的name分别为:j_username    j_password


其次  index.jsp  (登录通过后到的页面)

  1. < %@ taglib  prefix = "sec"   uri = "http://www.springframework.org/security/tags"  % >   
  2. < h4 > Hello  < FONT   color = "red" > < sec:authentication   property = "principal.username" /> </ FONT > </ h4 >   
  3. < 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了.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值