在项目开发,我们经常会使用WebService,但在使用WebService时我们经常会考虑到了WebService是安全问题,很容易想到通过一组用户名与密码来防止非法用户的调用 。

一、NetworkCredential方式
  在 System.Net 命名空间中提供了一个NetworkCredential,通过它我们可以在网络中提供一个凭证,只有获得该凭证的用户才能访问相应的服务的权限。在NetworkCredential 中,我们通过提供WebService发布所在的服务器名称,以及登录服务器并调用该WebService的用户名及密码(在IIS中配置)。
  在调用WebService时设置其Credential属性,把上面得到的Credential凭证赋值给它,这样只有使用提供的用户名及密码才能调用WebService服务了而其他用户则无法访问,这样就能能满足防止WebService被别人调用了。
  至于主机名,用户名及密码,对于B/S可以通过webconfig来配置;对于C/S可以使用应用程序配置文件。如下以C/S为例来说明,首先我们提供一个服务器网络凭证,然后通过WebRequest来验证连接是否成功。当然了,为了保存用户名与密码等的安全,可以对其进行加密等手段来保证其安全。

        /// <summary>
/// 服务器网络凭证
/// </summary>
/// <returns></returns>
public static NetworkCredential MyCred()
{
string loginUser = Properties.Settings.Default.UserName;//用户名
string loginPSW = Properties.Settings.Default.UserPSW;//密码
string loginHost = Properties.Settings.Default.HostName;//主机名,可以是IP地址,也可以服务器名称
NetworkCredential myCred = new NetworkCredential(loginUser, loginPSW, loginHost);
//NetworkCredential myCred = new NetworkCredential("username", "123456", "yourip");//"username", "123456", "yourservername"
return myCred;
}
/// <summary>
/// 验证是否成功连接到服务器,若连接成功,则返回TRUE
/// </summary>
/// <param name="url">服务器WebService URL</param>
/// <returns></returns>
public static bool Credential(string url)
{
//定义局部变量
string url = G_Url; //服务器验证只验证到机器
try
{
if (myWebResponse == null)
{
WebRequest myWebRequest = WebRequest.Create(url);//根据URL创建一个连接请求
myWebRequest.Credentials = MyCred();//获取验证的凭证,这是最重要的一句
myWebRequest.Timeout = ;//单位为毫秒
myWebResponse = myWebRequest.GetResponse();//返回连接成功时的信息
}
}
catch (WebException wex)//无法连接到服务器,可能是因为服务器错误或用户名与密码错误
{
if (myWebResponse != null)//毁销
{
myWebResponse.Close();
myWebResponse = null;
} return false;
}
catch (Exception ex)
{
if (myWebResponse != null)
{
myWebResponse.Close();
myWebResponse = null;
} return false; }
finally
{
} return true;
} private static WS_Webasic.WS_Webasic webasic = null;//实现华WS_Webasic.WS_Webasic  /// <summary>
/// WS_Webasic初始化
/// </summary>
public static WS_Webasic.WS_Webasic WS_Webasic
{
get
{
if (webasic == null)//若webasic 为空,则重新实例化,这样可以减少验证的时间,提高效率
{
//webasic = new ZEDI.WS_Webasic.WS_Webasic();
//wsBool = Credential(webasic.Url);//URL改为服务器地址 2009-02-25 陈辉聪 chhuic@163.com
wsBool = Credential(G_Url);
if (wsBool == true)  //服务器连接验证通过
{
webasic = new WS_Webasic.WS_Webasic();//实例化
webasic.Credentials = MyCred();//得到服务器连接凭证,这样该WebService可以放心的连接了
}
}
return webasic;
}
}

注:
(1)必须引用 System.Net;
(2)对WebService发访问,在IIS里取消匿名访问权限,若允许匿名访问,就没有必须提供验证凭证了。

二、

  在第一种方法的基础上对WebService里的方法进行加密,这里面方法很多,下面提供一种比较常用的方法。在调用方法时多提供两个参数用户加密解密用(当然了提供几个参数看自己的需要而定)。比如有个WebService方法是根据顾客ID获取数据库中的顾客的详细资料为GetCustomerDetailByCustomerID(string custID);如果只提供一个参数,则很容易被别人访问调用,从而顾客资料很容易被别人获取,因此我们对这个方法进行加密GetCustomerDetailByCustomerID(string scustID,string custID,ecustID);这样,只有提供正确的scustID与ecustID这二个参数才能成功调用这个方法,而对于这二个参数scustID与ecustID,则可以通过加密方法生成一个字符串,如scustID='C39134558',ecustID='C39223525',只有这二个参数满足一定的条件时才算验证通过,而对于参数来说,我们也可以提供一个验证,如果scustID里的值C39134558,前面三位必须是C39,紧跟5位13455则相加后的值18进行位操作如,对值18加一个因子,如1,则出现以下的运行:(18+1)%11==8,这样只有最后一位为8才算这个参数值是符合要求的,所以随便输入一个参数如:C39134556,则因为不符合要求,所以验证不能通过。在这里即使二个参数scustID='C39134558',ecustID='C39223525'都对了,则还需要通过这二个参数的进一步的验证才能算成功。至于这二个满足什么要求,一种是可以采用现有的加密机制,也可以自己写一个加密类来袜。 上面只是举一个简单的例子。

通过上面的二个步骤,则可以实现比较安全的WebService调用了。

三、通过通过SOAP Header身份验证
  1、我们实现一个用于身份验证的类,文件名MySoapHeader.cs 
  MySoapHeader类继承自System.Web.Services.Protocols.SoapHeader。且定义了两个成员变量,UserName和PassWord,还定义了一个用户认证的函数ValideUser。它提供了对UserName和PassWord检查的功能。

using System.Web.Services;
using System.Web.Services.Protocols;
/// <summary>
///MySoapHeader 的摘要说明
/// </summary>
public class MySoapHeader:SoapHeader
{
    public MySoapHeader()
    {
        //
        //TODO: 在此处添加构造函数逻辑
        //
    }
    public string UserName;
    public string PassWord;
    public bool ValideUser(string in_UserName, string in_PassWord)  
    {
        if ((in_UserName == "zxq") && (in_PassWord == ""))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

2.下面我们创建WebService.asmx,WebService.cs代码如下:

using System;
using System.Collections;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
/// <summary>
///WebService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : WebService
{
    public WebService()
    {
        //如果使用设计的组件,请取消注释以下行 
        //InitializeComponent(); 
    }
    public MySoapHeader header; ////定义用户身份验证类变量header
    [WebMethod(Description = "用户验证测试")]
    [SoapHeader("header")]//用户身份验证的soap头 
    public string HelloWorld(string contents)
    {
        //验证是否有权访问 
        if (header.ValideUser(header.UserName, header.PassWord))
        {
            return contents + "执行了";
        }
        else
        {
            return "您没有权限访问";
        }
    }
}

3.客户端,创建个Default.aspx

using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts; public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        com.cn1yw.WebService test = new com.cn1yw.WebService();//web引用(改成您自己的)
        com.cn1yw.MySoapHeader Header = new com.cn1yw.MySoapHeader();//web引用创建soap头对象(改成您自己的)
        //设置soap头变量
        Header.UserName = "zxq";
        Header.PassWord = "";
        test.MySoapHeaderValue = Header;
        //调用web 方法
        Response.Write(test.HelloWorld("我是强"));
    }
}

四、通过集成windows身份验证

  使用 NTML 或 Kerberos 对客户端进行身份验证。
  1、将web服务程序设为集成windows身份验证  
  2、客户端web引用代码

Test.WebReference.Service1 wr = new Test.WebReference.Service1(); //生成web service实例 
wr.Credentials = new NetworkCredential("guest",""); //guest是用户名,该用户需要有一定的权限 
lblTest.Text = wr.Add(,).ToString(); //调用web service方法

  该方案的优点是比较安全,性能较好,缺点是不便于移植,部署工作量大。

WebService 之 身份验证的更多相关文章

  1. 调用webservice进行身份验证

    因为同事说在调用webservice的时候会弹出身份验证的窗口,直接调用会返回401,原因是站点部署的时候设置了身份验证(账号名称自己配置).因而在调用的时候需要加入身份验证的凭证. 至于如何获取身份 ...

  2. 为WebService添加身份验证的两种方法

    方法一:SoapHeader 辅助类:MySoapHeader //SoapHeader 添加引用 using System.Web.Services.Protocols; #region 配置登录标 ...

  3. ASP.NET中WebService的两种身份验证方法

    一.通过SOAP Header身份验证 此方法是通过设置SOAP Header信息来验证身份,主要通过以下几步: 1.在服务端实现一个SOAP Header类 public class Credent ...

  4. webservice安全性之 SoapHeader自定义身份验证

    相信很多开发者都用过WebService来实现程序的面向服务,本文主要介绍WebService的身份识别实现方式,当然本文会提供一个不是很完善的例子,权当抱砖引玉了. 首先我们来介绍webservic ...

  5. android下身份验证方式调用webservice

    在企业开发领域,webservice还是经常被用到的服务体系,因为他对安全事务支持都比较好. 有时候,我们就需要在android下调用后端的webservice服务,因为在内部网络环境下,所有需要ba ...

  6. webservice常用两种身份验证方式

    在项目开发,我们经常会使用WebService,但在使用WebService时我们经常会考虑以下问题:怎么防止别人访问我的WebService?从哪里引用我的WebService?对于第一个问题,就涉 ...

  7. 使用SoapUI测试windows身份验证的webservice

    有个朋友问到用soapui测试wcf服务时如果使用windows身份验证要怎么传输凭据,于是自己试了一下.其实服务端是wcf还是webservice还是webapi都无所谓,关键是windows身份验 ...

  8. WebService基于soapheader的身份验证

    用WebService开发接口十分方便.但接口提供的数据不应是对所有人可见的,我们来利用SoapHeader写一个简单的身份验证Demo 目录 创建WebService项目(带SoapHeader) ...

  9. c# winform访问 带有windows身份验证的webservice

    1 将webservice设置为windows身份验证iis10中,要确认已安装windows身份验证在 控制面板 - >打开或关闭Windows功能 - >万维网服务 - >安全性 ...

随机推荐

  1. [LeetCode] Max Points on a Line 题解

    题意 Given n points on a 2D plane, find the maximum number of points that lie on the same straight lin ...

  2. 在IIS上部署基于django WEB框架的python网站应用

    django是一款基于python语言的WEB开源框架,本文给出了如何将基于django写的python网站部署到window的IIS上. 笔者的运行环境: Window xp sp3 IIS 5.1 ...

  3. How to exit the entire application from a Python thread?

    If all your threads except the main ones are daemons, the best approach is generally thread.interrup ...

  4. Tasker to detect application running in background

    We used to be told that tasker is only capable of detecting foreground application, if the app gets ...

  5. 05引用类型以及特殊引用类型string

    基本 □ 哪些属于引用类型 类(object,string),接口.数组.委托 □ 引用类型分配在哪里 ● 引用类型变量位于线程栈. ● 引用类型实例分配在托管堆上. ● 当引用类型实例的大小小于85 ...

  6. datagrid在MVC中的运用04-同时添加搜索和操作区域

    本文介绍在datagrid上同时添加搜索和操作区域. 仅仅是增加操作区域 □ 方法1 $('#dg').datagrid({ toolbar: '#tb' }); <div id="t ...

  7. 用Redis实现分布式锁以及redission使用

    原文:https://my.oschina.net/wangnian/blog/668830 前言:分布式环境有很多问题,比如你前一个请求访问的是服务器A,第二个请求访问到了服务器B,就会发生并发重复 ...

  8. Linux车载系统的开发方向

    眼下Linux基金会推出了基于Tizen 开源的车载系统平台Automotive Grade Linux (AGL), 眼下早期版本号的AGL已提供下载. UI用HTML5和JavaScript编程. ...

  9. [翻译] AFNetworking 2.0

    大名鼎鼎的开源网络库AFNetworking 2.0,目前只是翻译了Github上的链接文章,使用教程请点击 http://www.cnblogs.com/YouXianMing/p/3651462. ...

  10. 《Windows核心编程》第3章——handle复制相关实验

    先写一个程序,用来查看进程的内核对象,这样我们就能比较子进程是否继承了父进程的某个句柄: #include <windows.h> #include <stdio.h> #de ...