Cookie的应用

本文介绍了一个使用 ASP.NET 的 Forms 认证实现用户登录的示例应用,包括登录页面的创建、用户验证流程及如何利用 FormsAuthentication 进行用户会话管理。

login页面

 

ContractedBlock.gifExpandedBlockStart.gifCode
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="login.aspx.cs" Inherits="WebApplication1.login" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    
<title></title>
    
<link href="css/demo.css" media="screen" rel="stylesheet" type="text/css" />
</head>
<body>
    
<form id="form1" runat="server">
    
<div id="div1">
     
<asp:TextBox ID="tbUserName" runat="server"></asp:TextBox>
        
<asp:TextBox ID="tbPwd" runat="server"></asp:TextBox>
        
<asp:Button ID="btnLogin" runat="server" Height="26px" 
            Text
="登 陆" onclick="btnLogin_Click" />
            
<asp:CheckBox ID="checkBox" runat="server" />
        
<br />
        
<br />
        用户登录
    
</div>
    
</form>
</body>
</html>


login.cs

ContractedBlock.gifExpandedBlockStart.gifCode
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Data;
using System.Data.SqlClient;

namespace WebApplication1
{
    
public partial class login : System.Web.UI.Page
    {
        
protected void Page_Load(object sender, EventArgs e)
        {
          
                
//判断用户是否已经登陆,且角色为user
            if (User.Identity.IsAuthenticated && User.IsInRole("user"))
                {
//如果通过验证,则直接跳转到index.aspx
                    Response.Redirect("index.aspx");
                }
           
           
        }

        
protected void btnLogin_Click(object sender, EventArgs e)
        {
            
if (ValidateUser(tbPwd.Text,tbUserName.Text))
            {
                
//生成验证票据,其中包括用户名、生效时间、过期时间、是否永久保存和用户数据等。而关于用户角色的信息,我们保存在用户数据中。
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2, tbUserName.Text, DateTime.Now, DateTime.Now.AddDays(1),true"User");
                
string cookieStr = FormsAuthentication.Encrypt(ticket);//对票据进行加密
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieStr);
                
/*保存到cookie中。cookie的名字要与我们前面在配置文件中所写的name值一样。因为,当cookie保留在本地后,下次再检查用户权限的时候就会自动查找与forms名称相同的cookie,并传送给服务器端进行检验。如果在本地找不到cookie,就自然无法通过验证。*/
                cookie.Expires 
= ticket.Expiration;
                cookie.Path 
= FormsAuthentication.FormsCookiePath;
                Response.Cookies.Add(cookie);
                Response.Redirect(
"index.aspx");//登陆成功后跳转到index.aspx
            }
        }


//登陆后index页面

ContractedBlock.gifExpandedBlockStart.gifCode
protected void Page_Load(object sender, EventArgs e)
        {
            
if(!IsPostBack)
            {
                Response.Write(
"用户名:" + User.Identity.Name + "<br />Cookie名称:" + FormsAuthentication.FormsCookieName
                   
+ "<br />Cookie路径:" + FormsAuthentication.FormsCookiePath + "<br />");
            }
           
        }


//全局变量用来设置user

ContractedBlock.gifExpandedBlockStart.gifCode
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Security.Principal;
namespace WebApplication1
{
    
public class Global : System.Web.HttpApplication
    {
        
protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            
if (HttpContext.Current.User != null)
            {
                
if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    
if (HttpContext.Current.User.Identity is FormsIdentity)
                    {
                        FormsIdentity id 
= (FormsIdentity)HttpContext.Current.User.Identity;
                        FormsAuthenticationTicket ticket 
= id.Ticket;

                        
string userData = ticket.UserData;
                        
string[] roles = userData.Split(',');
                        HttpContext.Current.User 
= new GenericPrincipal(id, roles);
                    }
                }
            }
        }
    }
}

// 在配置文件了进行更改

<authentication mode="Forms">//Forms认证
    <forms name="adminlogin" loginUrl="Default.aspx"></forms>//寻找cookie的名字adminlogin判断cookie值是否还有效
   </authentication>
   <authorization>
    <allow users="*"/>//这里是权限
   </authorization>

转载于:https://www.cnblogs.com/xfxr/archive/2009/07/27/1531965.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值