java spring security详解

spring security文档介绍 
http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/index-all.html#_D_ 

自己写的一个demo,用来介绍security

1,UserDetails 

//返回验证用户密码,无法返回则NULL
String getPassword();
String getUsername();
//账户是否过期,过期无法验证
boolean isAccountNonExpired();
//指定用户是否被锁定或者解锁,锁定的用户无法进行身份验证
boolean isAccountNonLocked();
//指示是否已过期的用户的凭据(密码),过期的凭据防止认证
boolean isCredentialsNonExpired();
//是否被禁用,禁用的用户不能身份验证
boolean isEnabled();

UserDetails让User对象去实现,属性字段设计阶段就把字段跟接口字段对应!! 

2.UserDetailsService 

 

UserDetails loadUserByUsername(String username)
        throws UsernameNotFoundException, DataAccessException;

这里这个方法是当用户登录ok,通过之后会缓存起来,可以通过用户名从缓存中读取. 

UserDaoImpl可以去实现. 

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List users = getHibernateTemplate().find("from User where username=?", username);
        if (users == null || users.isEmpty()) {
            throw new UsernameNotFoundException("user '" + username + "' not found...");
        } else {
            return (UserDetails) users.get(0);
        }
    }

下边这个跟常用的session一样,也是从缓存中读取! 
这里要特别注意,应用是这样!但是框架的流程则复杂很多. 


3.SessionUtils 

public class SessionUtil {
    public static User getCurrentUser() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        User currentUser;
        if (auth.getPrincipal() instanceof UserDetails) {
            currentUser = (User) auth.getPrincipal();
        } else if (auth.getDetails() instanceof UserDetails) {
            currentUser = (User) auth.getDetails();
        } else {
            throw new AccessDeniedException("User not properly authenticated.");
        }
        return currentUser;
    }
}

4.web.xml中配置 
个人喜欢把security的东西新建一个xml,在web中启动自己的security.xml(当然放在web-inf下比较好) 

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
       /WEB-INF/security.xml
    </param-value>
</context-param>

 

dfp代理过滤Filter,在初始化的时候springSecurityFilterChain这个有注意到了吗? 

<!-- 所有的Filter委托给Spring -->
<!-- 第一种,可以自定义过滤器 -->
<filter>
  <filter-name>securityFilter</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
     <init-param>
        <param-name>targetBeanName</param-name>
        <param-value>springSecurityFilterChain</param-value>
     </init-param>
</filter>
<filter-mapping>
     <filter-name>securityFilter</filter-name>
     <url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 第二种配置 -->
<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>

在这里要特别注意:springSecurityFilterChain这个名称是命名空间默认创建的,用于处理Web安全的一个内部Bean的Id 
★在自定义Bean时不可以在用这个Id名称,不然会冲突异常! 
5.security.xml 

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:beans="http://www.springframework.org/schema/beans"
             xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
              http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.1.xsd">
    <!-- 还记得前面的代理吗,这里注明后!代理会自动生成 -->
    <http auto-config="true" lowercase-comparisons="false">
        <!--intercept-url pattern="/images/*" filters="none"/>
        <intercept-url pattern="/styles/*" filters="none"/>
        <intercept-url pattern="/scripts/*" filters="none"/--> 
        <intercept-url pattern="/admin/*" access="ROLE_ADMIN"/>
        <intercept-url pattern="/cpManagerPages/*" access="ROLE_ADMIN,ROLE_CONTENT_PROVIDER"/>
        <intercept-url pattern="/**/*.ca*" access="ROLE_CONTENT_PROVIDER,ROLE_ADMIN,ROLE_USER"/>
        <!-- 这里/j_security_check是表单提交位置 -->
        <form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?error=true" login-processing-url="/j_security_check"/>
        <remember-me user-service-ref="userDao" key="e37f4b31-0c45-11dd-bd0b-0800200c9a66"/>
    </http>
    <!--① 验证过程是由userDao,也就是连接数据库验证 -->
    <authentication-provider user-service-ref="userDao">
        <password-encoder ref="passwordEncoder"/>
    </authentication-provider>
    <!--② 这个跟1不同,这里是根据自定义的用户来验证 -->
    <authentication-provider>
        <user-service>
          <user name="sp" password="123" authorities="ROLE_SP" />
          <user name="admin" password="123" authorities="ROLE_CARRIER" />
          <user name="cp" password="123" authorities="ROLE_CP" />
        </user-service>
    </authentication-provider>
    <!-- Override the default password-encoder (SHA) by uncommenting the following and changing the class -->
    <!-- <bean id="passwordEncoder" class="org.springframework.security.providers.encoding.ShaPasswordEncoder"/> -->
    <!-- 限制对方法的访问 @Secured JSR-250注解 -->
    <global-method-security>
        <protect-pointcut expression="execution(* *..service.UserManager.getUsers(..))" access="ROLE_ADMIN"/>
        <protect-pointcut expression="execution(* *..service.UserManager.removeUser(..))" access="ROLE_ADMIN"/>
    </global-method-security>
</beans:beans>

在配置intercept-url,最先验证的是第一个intercept-url,队列形式! 


下边这些是标签属性说明: 
配置说明: 
  lowercase-comparisons:表示URL比较前先转为小写。 
  path-type:表示使用Apache Ant的匹配模式。 
  access-denied-page:访问拒绝时转向的页面。 
  access-decision-manager-ref:指定了自定义的访问策略管理器。当系统角色名的前缀不是默认的ROLE_时,需要自定义访问策略管理器。 
  login-page:指定登录页面。 
  login-processing-url:指定了客户在登录页面中按下 Sign In 按钮时要访问的 URL。与登录页面form的action一致。其默认值为:/j_spring_security_check。 
  authentication-failure-url:指定了身份验证失败时跳转到的页面。 
  default-target-url:指定了成功进行身份验证和授权后默认呈现给用户的页面。 
  always-use-default-target:指定了是否在身份验证通过后总是跳转到default-target-url属性指定的URL。 
  logout-url:指定了用于响应退出系统请求的URL。其默认值为:/j_spring_security_logout。 
  logout-success-url:退出系统后转向的URL。 
  invalidate-session:指定在退出系统时是否要销毁Session。 
  max-sessions:允许用户帐号登录的次数。范例限制用户只能登录一次。 
  exception-if-maximum-exceeded: 默认为false,此值表示:用户第二次登录时,前一次的登录信息都被清空。 
  当exception-if-maximum-exceeded="true"时系统会拒绝第二次登录。

posted @ 2013-10-25 15:21  暖流  阅读(14125)  评论(0编辑  收藏  举报