翱翔.Net

释放.Net的力量
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

浅析《ASP.Net Web 站点高级编程》的登录验证!

Posted on 2004-12-22 14:03  Hover  阅读(6328)  评论(9编辑  收藏  举报

ASP.NET 中内置的用户验证支持的功能非常强大,它能够自动地在Context对象中生成一个名为User的属性.
该属性能够让我们访问各种信息,包括用户是否已经验证。验证用户的类型,甚至还有用户名,不管我们是
使用基于表单的验证还是WINDOWS验证,都可以使用由Context对象表示的当前的HttpContext实例中的User对象

.Net FrameWork中提供的Context.User对象与前面介绍的User类不同。Context.User用于验证,
而User类用于某个用户的一般性信息.

.Net(不只是ASP.NET)中的安全机制基于负责人(principal)的概念,Principal对象代表以其名义运行代码的用户的安全
环境,因此,如果我运行程序,负责人就是程序运行期间我的安全环境。低于负责人的级别是身份(identity)
身份代表执行代码的用户。因此,每一个负责人都有一个身份,这种通用的负责人和身份的概念用于基于表单
的验证。Windows验证,甚至在.Net编程的其他用于传递证书给Web站点和远程主机.我们决定不创建自己的安全系统
但是要使用自己的负责人和身份的概念,以便巧妙地吻合于Microsoft已有的安全体系..

以上引用《ASP.NET Web站点高级编程 提出问题-设计方案-解决方案》,以下简称ThePhile(工程名)

ThePhile的验证方式是实现了IPrincipal和Identity接口


HttpContext.User的对象必须实现 System.Security.Principal.Iprincipal接口.

IPrincipal 概述

公共属性
Identity 获取当前用户的标识。

公共方法
IsInRole 确定当前用户是否属于指定的角色。

公共属性Identity又必须实现System.Security.Principal.IIdentity 接口

IIdentity 概述

公共属性
AuthenticationType 获取所使用的身份验证的类型。
IsAuthenticated 获取一个值,该值指示是否验证了用户。
Name 获取当前用户的名称

只要实现了这IPrincipal和IIdentity两个接口.然后分配给HttpContext.User的对象.
就可以判断出是否验证过.IsAuthenticated.或者获取用户名称等.


在ThePhile工程中。继承IPrincipal接口的是PhilePrincipal类(通过HttpContext.User可用)
继承IIdentity接口的是SiteIdentity类(通过HttpContext.User.Identity可用)
注:偶手里的代码此类是叫SiteIdentity。而书上的是PhileIdentity。其实没什么只是个类名. 


先来看看登录页位于Modules\User\Login.aspx

这中登录页的登陆按钮单击事件

private void Submit_Click(object sender, System.EventArgs e)
        
{            
            PhilePrincipal newUser 
= PhilePrincipal.ValidateLogin( EmailAddress.Text, Password.Text );
            
//这里验证用户.并实现IPrincipal和IIdentity接口
            
            
if (newUser == null)
            
{
                LoginResult.Text 
= "Login failed for " + EmailAddress.Text;
                LoginResult.Visible 
= true;
            }

            
else 
            
{
                Context.User 
= newUser;
                FormsAuthentication.SetAuthCookie( EmailAddress.Text, 
true );                    
                Response.Redirect(
"/ThePhile/default.aspx");
                
//登录成功、写Cookie。跳转
            }

        }


###修改用户接口来支持验证.
需要修改PhilePage类。
因为此类是Web页的基类.. 继承System.Web.UI.Page

 

using System;
using System.Web;
using System.Web.UI;
using System.Diagnostics;
using Wrox.WebModules;

using Wrox.WebModules.Accounts.Business;

namespace Wrox.ThePhile.Web
{
    
/// <summary>
    
/// Summary description for PhilePage.
    
/// </summary>

    public class PhilePage : System.Web.UI.Page
    
{                
        
public PhilePage()
        
{
        }


        
protected override void OnInit(EventArgs e)
        
{
            
//这里重写了OnInit方法
            base.OnInit(e);
            
this.Load += new System.EventHandler(this.PhilePage_Load);
            
this.Error += new System.EventHandler(this.PhilePage_Error);
        }

            
        
///这个是写事件日志方法
        protected void LogEvent(string message, EventLogEntryType entryType)
        
{
            
if (!EventLog.SourceExists("ThePhile.COM"))
            
{
                EventLog.CreateEventSource(
"ThePhile.COM""Application");
            }

            EventLog.WriteEntry(
"ThePhile.COM", message, entryType);
        }

        
        
/// <summary>
        
/// 捕获错误显示
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>

        protected void PhilePage_Error(object sender, System.EventArgs e)
        
{
            
string errMsg;
            Exception currentError 
= Server.GetLastError();

            errMsg 
= "<link rel=\"stylesheet\" href=\"/ThePhile/Styles/ThePhile.CSS\">";
            errMsg 
+= "<h1>Page Error</h1><hr/>An unexpected error has occurred on this page. The system " +
                
"administrators have been notified. Please feel free to contact us with the information " +
                
"surrounding this error.<br/>"+
                
"The error occurred in: "+Request.Url.ToString()+"<br/>"+
                
"Error Message: <font class=\"ErrorMessage\">"+ currentError.Message.ToString() + "</font><hr/>"+
                
"<b>Stack Trace:</b><br/>"+
                currentError.ToString();

            
if ( !(currentError is AppException) )
            
{
                
// It is not one of ours, so we cannot guarantee that it has been logged
                
// into the event log.
                LogEvent( currentError.ToString(), EventLogEntryType.Error );
            }


            Response.Write( errMsg );
            Server.ClearError();
        }


        
        
private void PhilePage_Load(object sender, System.EventArgs e)
        
{
            
// TODO: Place any code that will take place BEFORE the Page_Load event
            
// in the regular page, e.g. cache management, authentication verification,
            
// etc.                                            
            if (Context.User.Identity.IsAuthenticated) 
            
{
                        
//如果是验证通过的
                    
                
if (!(Context.User is PhilePrincipal))
                
{
                    
// ASP.NET's regular forms authentication picked up our cookie, but we
                    
// haven't replaced the default context user with our own. Let's do that
                    
// now. We know that the previous context.user.identity.name is the e-mail
                    
// address (because we forced it to be as such in the login.aspx page)                
                    PhilePrincipal newUser = new PhilePrincipal( Context.User.Identity.Name );
                    Context.User 
= newUser;
                }

                
//此处是当前的Context.User不是PihlePrincipal的。转换一下
                
//再赋给Context.User
            }

        }

    
    }

}


上面是PhilePage类。在Web页调用时继承一下就行了
此处有一个问题。当ASPX页继承此类时。
Web 窗体设计器生成的代码


请看OnInit方法。是选调用了InitializeComponent()后调用父类的base.OnInit(e)
呵。这里可折腾了好几天。如果这样的话就在页面载入是先调用的是本页的Page_Load()方法
后调用父类的OnInit(e),这样PhilePage的Phile_Load()就形同虚设了。
在Thephile工程中它的页面的OnInit都是base.OnInit(e)在前面.而如果你新建一个页面的话就是在后面了
这可能与.Net版本有关。在书的封面上有Writeen and tested for final release of .Net V1.0
我这没有.Net v1.0所以也无法测试了。所以现在用2003 Vs.Net 的IDe时新建的页想要继承PhilePage需要把这两个方法的默认顺序手动改一下.

再看siteHeader控件.是通过验证显示用户名相关信息。否则显示未登录信息

private void Page_Load(object sender, System.EventArgs e)
        
{
            
// Put user code to initialize the page here
            Greeting.Text = "Welcome, ";
            
///是否验证过
            if (Context.User.Identity.IsAuthenticated)
            
{
                Greeting.Text 
+= "<b>" + Context.User.Identity.Name + "</b>"
                UserLink.Text 
= "My Account";
                UserLink.NavigateUrl 
= "/ThePhile/Modules/Users/MyAccount.aspx";
                SignOut.Visible 
= true;
            }

            
else
            
{
                Greeting.Text 
+= "Guest User.";
                UserLink.Text 
= "Click to Login";
                UserLink.NavigateUrl 
= "/ThePhile/Modules/Users/Login.aspx";
                SignOut.Visible 
= false;
            }
        
        }

            
///这是退出
        private void SignOut_Click(object sender, System.EventArgs e)
        
{
            FormsAuthentication.SignOut();
            Response.Redirect(
"/thephile");
        }

这样就实现了登录验证。这里一定要注意的地方是。呵要先启用Forms验证方可使上面的代码奏效

<identity impersonate="true" />
    
<!--  AUTHENTICATION 
          This section sets the authentication policies of the application. Possible modes are "Windows", "Forms", 
          "Passport" and "None"
    
-->
    
<authentication mode="Forms">
        
<forms name="ThePhile" path="/" loginUrl="/ThePhile/Modules/Users/Login.aspx"
            protection
="All" timeout="30">
        
</forms>
    
</authentication>

 


具体的代码请参看ThePhile.早就应该写了。出于自己懒。一看12月快过了一个随笔都没有可不行。
急急忙瞎写了一大堆。有错误和不妥地方请大家见谅!
提前祝所有博客。圣诞快乐!