asp.net 内置票据认证+securitySwitch 的实现

http://www.codeproject.com/Articles/7206/Switching-Between-HTTP-and-HTTPS-Automatically-Ver

步骤 先下载dll文件 http://code.google.com/p/securityswitch/downloads/list 我选择的是 SecuritySwitch v4.2.0.0 - Binary.zip这个版本

image

1: 我们来看看测试项目

image

admin 文件夹,需要登录之后,才能访问。admin里面的 login.aspx 可以访问。整个admin文件夹都需要https访问

image

contact.aspx 需要https 访问

image

default.aspx 和 view.aspx 采用 http 访问

image

链接我们都采用相对路径,并没有写死成 http://www.xx.com/a.aspx 或者是 https://www.xx.com/a.aspx

image

下面我们开始用SecuritySwith来实现上面的https和http访问的规则

2:在项目上,添加引用 SecuritySwitch.dll ,并且添加 智能提示

image

image

image

这样,只能提示就有了。

image

3:然后我们在web.config里面添加设置 。根据IIS的不同,还分为 IIS6+ IIS7.X(经典模式) 以及 IIS7(集成模式) 的不同的配置,这里我们是按照IIS6+IIS7.X的(经典模式)来配置的.

由于在项目里面增加了 内置票据认证,所以代码有些多

<?xml version="1.0"?>
<configuration>

    <!--SSL配置1开始-->
    <configSections>
        <section name="securitySwitch" type="SecuritySwitch.Configuration.Settings, SecuritySwitch" />
    </configSections>

    <securitySwitch    baseInsecureUri="http://webjoeyssl" baseSecureUri="https://webjoeyssl" xmlns="http://SecuritySwitch-v4.xsd" mode="On">
        <!--如果你的http和https仅仅只有一个s的区别,那么这里的base的2个url可以不写,那为什么还要搞这2个url呢?因为比如
        你的 baseInsecureUri (基本不安全网址) 是 http://www.qq.com
        而你的  baseSecureUri (基本安全网址)  是 https://safe.qq.com  
        然后这个时候你访问一个需要https的页面,假如是 login.aspx?return=joey 
        假如你是通过http://www.qq.com/login.aspx?return=joey访问的,那么这个
        页面会跳转到http://safe.qq.com/login.aspx?return=joey 
        -->
        <paths>
            <add path="~/contact.aspx"/>
            <add path="~/admin/login.aspx"/>
            <add path="~/admin" />
            <!--这里的admin因为不仅是 admin 文件夹,而且还包含类似的 adminNews.aspx  adminQQ.aspx 页面"-->
            <!--但是如果是  ~/admin/   就是专门指admin文件夹-->

        </paths>
    </securitySwitch>
    <!--SSL配置1结束-->
    <appSettings />
    <system.web>
        <compilation debug="true">

        </compilation>
        <!--  内置票据认证 start-->
        <authentication mode="Forms">
            <forms name="mycook" loginUrl="admin/login.aspx" protection="All" path="/" />
        </authentication>
        <!--  内置票据认证 end-->
        <!--
            如果在执行请求的过程中出现未处理的错误,
            则通过 <customErrors> 节
            可以配置相应的处理步骤。具体而言,
            开发人员通过该节可配置要显示的 html 错误页,
            以代替错误堆栈跟踪。

        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
        -->
        <!--SSL配置2  如果是 IIS <= 6.x, IIS 7.x + 经典模式-->
        <httpModules>
            <add name="SecuritySwitch" type="SecuritySwitch.SecuritySwitchModule, SecuritySwitch" />
        </httpModules>
        <!--SSL配置2结束-->
    </system.web>

    <!--如果是IIS7.X + 集成模式-->
    
    <!--<system.webServer>
        <validation validateIntegratedModeConfiguration="false" />
        <modules>
            --><!-- for IIS 7.x + 集成模式 --><!--
            <add name="SecuritySwitch" type="SecuritySwitch.SecuritySwitchModule, SecuritySwitch" />
        </modules>
    </system.webServer>-->
    
    <!--如果是IIS7.X+集成模式-->
    
    <!--这里是配置 内置票据认证的权限 start-->
    <location path="admin">
        <system.web>
            <authorization>
                <allow roles="admin" />
                <deny users="*" />
            </authorization>
        </system.web>
    </location>
    <location path="admin/login.aspx">
        <system.web>
            <authorization>
                <allow users="*" />
            </authorization>
        </system.web>
    </location>
    <location path="admin/images">
        <system.web>
            <authorization>
                <allow users="*" />
            </authorization>
        </system.web>
    </location>
    <location path="admin/css">
        <system.web>
            <authorization>
                <allow users="*" />
            </authorization>
        </system.web>
    </location>
    <!--这里是配置 内置票据认证的权限 end  -->
</configuration>

4: 由于用到了内置票据认证,所以要在 Global.asax添加以下代码

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 tiecket = id.Ticket;

                        string userData = tiecket.UserData;

                        string[] roles = userData.Split(',');

                        HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, roles);

                    }

                }

            }

        }

 

5: 后台登陆界面  admin/login.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="login.aspx.cs" Inherits="web.admin.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>
</head>
<body>
    <form id="form1" runat="server">
    用户名:<asp:TextBox ID="txtUser" runat="server"></asp:TextBox><br />
    密码:<asp:TextBox ID="txtPass" runat="server"></asp:TextBox><br />
    记住用户名:<asp:CheckBox ID="chkUsername" runat="server"  Checked="true"/> 
    <br />
    <asp:Literal ID="litResult" runat="server"></asp:Literal>
    <br />
    <asp:Button ID="btnSubmit" runat="server" Text="提交" onclick="btnSubmit_Click" />
    </form>
</body>
</html>

后台登陆界面 cs   admin/login.aspx.cs

using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

namespace web.admin
{
    public partial class login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string username = txtUser.Text;
            string pass = txtPass.Text;
            bool ischeck=chkUsername.Checked;
            if (username=="admin" && pass=="admin")
            {
                SaveLogin(username, ischeck);
            }
            
        }

        private void SaveLogin(string username, bool ischeck)
        {
            HttpCookie cook;
            string strReturnURL;
            string roles = "admin";//将用户的usernameid,保存到cookies,身份是 admin 身份
            //要引用 using System.Web.Security;
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(

            1, username, DateTime.Now, DateTime.Now.AddMinutes(30), ischeck, roles);

            cook = new HttpCookie("mycook");//对应webconfig里面的 验证里面的 forms name="mycook"

            cook.Value = FormsAuthentication.Encrypt(ticket);

            Response.Cookies.Add(cook);

            strReturnURL = Request.Params["ReturnUrl"];

            if (strReturnURL != null)
            {
                Response.Redirect(strReturnURL);
            }
            else
            {
                Response.Redirect("default.aspx");
            }
        }
    }
}
posted @ 2012-11-23 15:46  那年那月  阅读(2812)  评论(0编辑  收藏  举报