Web项目中的登录验证思路

以前学习框架经常做登录页面的demo,输入正确的id+pwd就返回成功了。。可是这种模式无法阻止通过URL直接访问其他的页面,在一个非玩具系统中,控制未登录用户的页面访问权限是一个基本功能。

从实现思路讲,验证一个用户的有效登录,大多采用的是登入时候向Session写一个User认证信息,然后在访问每个页面前来判断Session中是否有认证信息。

if (session.get( "U ser " ) == null

另外有很多网站提供记住登陆信息xx天,这种是结合了Cookie的认证信息存储。谈到这里,也可以仔细想想Cookie和Session的作用。比如卓越的购物车就是Cookie做的(因为关闭IE后再访问购物车还记得你的物品),而大多数群集Web服务器的信息也是采用Cookie(因为群集的Session同步开销很大),掌握了Cookie和Session的基本特性,这些都是理所当然的做法了。

一。下面说第一种拦截实现:基于javax.servlet.Filter

1.首先需要到web.xml注册一个filter

(这里是将authorityFilter这个类委托给spring来代理

<!--  authority filter proxy  -->
< filter >    
        
< filter-name > authorityFilter </ filter-name >    
        
< filter-class > org.springframework.web.filter.DelegatingFilterProxy </ filter-class >    
        
< init-param >    
              
< param-name > targetFilterLifecycle </ param-name >    
              
< param-value > true </ param-value >    
        
</ init-param >    
 
</ filter >    
 
     < filter-mapping >
        
< filter-name > authorityFilter </ filter-name >
        
< url-pattern > /* </ url-pattern >
    
</ filter-mapping >

2.写authorityFilter类(基于URL字符串的过滤实现) 

public   class  AuthorityFilter  extends  HttpServlet  implements  Filter  ... {
    
private static final long serialVersionUID = 1L;
    
private static final Log log=LogFactory.getLog(AuthorityFilter.class);
    
public void init(FilterConfig arg0) throws ServletException ...{
        
//do something
    }

    
public void doFilter(ServletRequest sRequest, ServletResponse sResponse,    
            FilterChain filterChain) 
throws IOException, ServletException ...
        HttpServletRequest request 
= (HttpServletRequest) sRequest;    
        HttpServletResponse response 
= (HttpServletResponse) sResponse;    
        HttpSession session 
= request.getSession();    
        String url
=request.getServletPath();
        String contextPath
=request.getContextPath();
        
if(url.equals("/admin"))url+="/";
        
if(log.isDebugEnabled())
                log.debug(
"-----------------------"+url);
        
if((url.startsWith("/admin/")&&!url.startsWith("/admin/login")))...{//若访问后台资源
             Administartor adminUser=(Administartor)
                                     session.getAttribute(Constants.SESSION_ADMINISTRATOR);
             
if(adminUser==null)...{//转入管理员登陆页面
                  response.sendRedirect(contextPath+"/admin/login!input.action");
                  
return;
             }

        }

          filterChain.doFilter(sRequest, sResponse);  
    }

}

 

二。第二种权限过滤是基于struts2中Interceptor的概念

1.写过滤器类AuthorityInterceptor

public   class  AuthorityInterceptor  extends  AbstractInterceptor ... {

    @Override
    
public String intercept(ActionInvocation invocation) throws Exception ...{
        
        ActionContext ctx 
= invocation.getInvocationContext();
        Map session 
= ctx.getSession();
        
//未登录,返回输入
        if(session.get("user")==null...{
            
return "input";
        }

        
//否则通过拦截
        return invocation.invoke();
    }


}

2.配置result结果

将自己写的拦截器和defaultStack组合成myStack,并且配置成默认拦截器!为了避免拦截登录页面,将登陆Action显式的配置<interceptor-ref name="defaultStack"/>,从而不使用默认的myStack拦截自己。

< struts >
    
< package  name ="webMail"  extends ="struts-default"  namespace ="/webMail" >
    
< interceptors >
        
< interceptor  name ="authority"  class ="com.decentsoft.commons.security.AuthorityInterceptor" />
        
< interceptor-stack  name ="myStack" >
            
< interceptor-ref  name ="defaultStack" />
            
< interceptor-ref  name ="authority" />
        
</ interceptor-stack >
    
</ interceptors >
    
< default-interceptor-ref  name ="myStack" ></ default-interceptor-ref >
    
< global-results >
        
< result  name ="input"  type ="redirect" > /WEB-INF/page/webMail/portal.jsp </ result >
    
</ global-results >

    
< action  name ="indexAction"  class ="com.mail.action.MailStatisticAction" >
              
< result  name ="portal" > /WEB-INF/page/webMail/portal.jsp </ result >
              
< result  name ="login"  type ="chain" >
                
< param  name ="actionName" > webMailAction </ param >
                
< param  name ="namespace" > /webMail </ param >
                
< param  name ="method" > mailIndex </ param >
              
</ result >
              
< interceptor-ref  name ="defaultStack" />
        
</ action >
    
</ package >
</ struts >

3.MailStatisticAction的登录方法实现大概如下:根据校验结果返回登录或者进入页面

     /** */ /**
     * 通行证
     * 
@return
     
*/

    
public  String portal()  ... {
        
        
//登录时候验证用户,并且将用户信息放到session!
        if(condition)) ...{
            MailUser user 
= new MailUser("x","x");
            session.put(
"user", user);
            
return "login";
        }

        
return "portal";
    }

三。第三种权限过滤是spring中的Acegi安全系统,这个功能很强大,有模型。在《spring in Action》有介绍,没有仔细研究过。


 

p.s Acegi 系统已经由spring独立作为一个子项目发布了,名字叫“security”。官方地址在:http://static.springframework.org/spring-security/site/index.html. 

这是一整套的安全解决方案,不仅仅只是登陆验证,还可以用来做复杂的权限模型


Spring Security

Formerly the Acegi Security System for Spring, Spring Security provides powerful and flexible security solutions for enterprise applications developed using the Spring Framework. It is a stable and mature product - Acegi Security 1.0.0 was released in May 2006 after more than two and a half years of use in large production software projects and adopted as an official Spring sub-project on its release.

Spring Security 2.0.0 builds on Acegi Security's solid foundations, adding many new features:

  • Simplified namespace-based configuration syntax. Old configurations could require hundreds of lines of XML but our new convention over configuration approach ensures that many deployments will now require less than 10 lines.
  • OpenID integration, which is the web's emerging single sign on standard (supported by Google, IBM, Sun, Yahoo and others)
  • Windows NTLM support, providing easy enterprise-wide single sign on against Windows corporate networks
  • Support for JSR 250 ("EJB 3") security annotations, delivering a standards-based model for authorization metadata
  • AspectJ pointcut expression language support, allowing developers to apply cross-cutting security logic across their Spring managed objects
  • Substantial improvements to the high-performance domain object instance security ("ACL") capabilities
  • Comprehensive support for RESTful web request authorization, which works well with Spring 2.5's @MVC model for building RESTful systems
  • Long-requested support for groups, hierarchical roles and a user management API, which all combine to reduce development time and significantly improve system administration
  • An improved, database-backed "remember me" implementation
  • Support for portlet authentication out-of-the-box
  • Support for additional languages
  • Numerous other general improvements, documentation and new samples
  • New support for web state and flow transition authorization through the Spring Web Flow 2.0 release
  • New support for visualizing secured methods, plus configuration auto-completion support in Spring IDE
  • Enhanced WSS (formerly WS-Security) support through the Spring Web Services 1.5 release
  • Updated support for CAS single sign-on (CAS 3 is now supported).
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值