近期一个项目中用到Restful WCF提供服务,但是需要验证机制,网上搜刮了一些,都是太复杂。翻墙找到了一篇不错的文章分享一下。

原地址连接:http://vgolovchenko.wordpress.com/2012/05/20/wcf-soaprest-ssl-basic-authentification-iis/

如何实现REST + Basic auth?

1. 创建WCF lib宿主到iis上

参考:http://www.cnblogs.com/yongqiangyue/p/4050258.html

参考:http://www.cnblogs.com/wlflovenet/archive/2011/10/28/WCFREST.html

2. 利用类BasicAuthenticationManager来解析BasicAuth http-header并且验证

代码如下:

    public class BasicAuthenticationManager : ServiceAuthorizationManager
{
protected override bool CheckAccessCore(OperationContext operationContext)
{
try
{
var msg = operationContext.RequestContext.RequestMessage; // If user requests standart help-page then ignore authentication check.
if (msg.Properties.ContainsKey("HttpOperationName") && msg.Properties["HttpOperationName"].ToString() == "HelpPageInvoke")
{
return base.CheckAccessCore(operationContext);
} var httpRequestHeaders = ((HttpRequestMessageProperty) msg.Properties[HttpRequestMessageProperty.Name]).Headers; // Is Authorization-header contained in http-headers?
if (!httpRequestHeaders.AllKeys.Contains(HttpRequestHeader.Authorization.ToString()))
{
return false;
} // Try to parse standart Basic-auth header.
var authenticationHeaderBase64Value = httpRequestHeaders[HttpRequestHeader.Authorization.ToString()];
var basicAuthenticationFormatString = Base64EncodeHelper.DecodeUtf8From64(authenticationHeaderBase64Value).Remove(0, "Basic ".Length);
var basicAuthenticationParams = basicAuthenticationFormatString.Split(new[] {':'}, 2);
var login = basicAuthenticationParams.FirstOrDefault();
var password = basicAuthenticationParams.LastOrDefault(); // Check credentials.
                // 自定义验证方式:CAuthorizationAPI是自己封装的验证用户名和密码的方法类
if(!CAuthorizationAPI.Validate(login, password))
{
return false;
}
}
catch (Exception ex)
{
return false;
} return base.CheckAccessCore(operationContext);
}
}
对应的配置文件修改(behavior-section部分的修改)
 
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<behaviors>
<!--<endpointBehaviors>
<behavior name="">
<webHttp helpEnabled="true" faultExceptionEnabled="true" />
</behavior>
</endpointBehaviors>-->
<serviceBehaviors>
<behavior>
<!-- 为避免泄漏元数据信息,
请在部署前将以下值设置为 false 并删除上面的元数据终结点 -->
<serviceMetadata httpGetEnabled="True" />
<!-- 要接收故障异常详细信息以进行调试,
请将以下值设置为 true。在部署前设置为 false
以避免泄漏异常信息-->
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceAuthorization serviceAuthorizationManagerType="DMService.Infrastructure.BasicAuthenticationManager, DMService" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
3. 写一个测试程序:增加basic auth http-header
 
    private static void Main(string[] args)
{
try
{
var request = WebRequest.Create(string.Format("http://localhost:21568/api/test/yueyq/{0}", Uri.EscapeDataString("rest-client (ssl-basic auth)"))); // ! Remove this string in production code. Emulate working with the trusted certificate.
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; // The straightforward passing of credential parameter for demo.
const string login = "user";
const string password = "password"; request.Headers.Add(
HttpRequestHeader.Authorization,
Base64EncodeHelper.EncodeUtf8To64(string.Format("Basic {0}:{1}", login, password))); using (var reader = new StreamReader(request.GetResponse().GetResponseStream()))
{
Console.WriteLine(reader.ReadToEnd());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
} Console.WriteLine("\n press Enter to exit..");
Console.ReadLine();
}
}
 
4. 类Base64EncodeHelper的实现
 
public static class Base64EncodeHelper
{
/// <summary>
/// The method create a Base64 encoded string from a normal string.
/// </summary>
/// <param name="toEncode">The String containing the characters to encode.</param>
/// <returns>The Base64 encoded string.</returns>
public static string EncodeUtf8To64(string toEncode)
{
var toEncodeAsBytes = Encoding.UTF8.GetBytes(toEncode);
var returnValue = Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
} /// <summary>
/// The method to Decode your Base64 strings.
/// </summary>
/// <param name="encodedData">The String containing the characters to decode.</param>
/// <returns>A String containing the results of decoding the specified sequence of bytes.</returns>
public static string DecodeUtf8From64(string encodedData)
{
var encodedDataAsBytes = Convert.FromBase64String(encodedData);
var returnValue = Encoding.UTF8.GetString(encodedDataAsBytes);
return returnValue;
}
}
更多的关于WCF安全可以详细的查看下面链接:
http://wcfsecurityguide.codeplex.com/
 

WCF:REST + Basic authentification + IIS的更多相关文章

  1. WCF学习笔记(2)——使用IIS承载WCF服务

    通过前面的笔记我们知道WCF服务是不能独立存在,必须“寄宿”于其他的应用程序中,承载WCF服务的应用程序我们称之为“宿主”.WCF的多种可选宿主,其中比较常见的就是承载于IIS服务中,在这里我们来学习 ...

  2. [老老实实学WCF] 第三篇 在IIS中寄存服务

    老老实实学WCF 第三篇 在IIS中寄宿服务 通过前两篇的学习,我们了解了如何搭建一个最简单的WCF通信模型,包括定义和实现服务协定.配置服务.寄宿服务.通过添加服务引用的方式配置客户端并访问服务.我 ...

  3. WCF:为 SharePoint 2010 Business Connectivity Services 构建 WCF Web 服务(第 1 部分,共 4 部分)

    转:http://msdn.microsoft.com/zh-cn/library/gg318615.aspx 摘要:通过此系列文章(共四部分)了解如何在 Microsoft SharePoint F ...

  4. (转) [老老实实学WCF] 第三篇 在IIS中寄存服务

    第三篇 在IIS中寄宿服务 通过前两篇的学习,我们了解了如何搭建一个最简单的WCF通信模型,包括定义和实现服务协定.配置服务.寄宿服务.通过添加服务引用的方式配置客户端并访问服务.我们对WCF的编程生 ...

  5. WCF绑定netTcpBinding寄宿到IIS

    继续沿用上一篇随笔中WCF服务类库 Wettery.WcfContract.Services WCF绑定netTcpBinding寄宿到控制台应用程序 服务端 添加WCF服务应用程序 Wettery. ...

  6. 胡喜:从 BASIC 到 basic ,蚂蚁金服技术要解决两个基本的计算问题

    摘要: 揭开 BASIC College 神秘面纱,蚂蚁金服首次揭秘人才培养机制. 导读:5 月 6 日,蚂蚁金服副 CTO 胡喜在 2019 年 QCon 上做了<蚂蚁金服十五年技术架构演进之 ...

  7. 软件分享:网页监测及 IIS 重启工具 IISMonitor

    本人以前编写过一款简单的工具软件 IISMonitor,这几天整理完善并补写了使用说明,分享出来,供大家免费使用.使用过程中,遇到什么问题或有什么建议,也可回帖留言,我尽力提供修改支持. 1.工具简介 ...

  8. WCF:如何将net.tcp协议寄宿到IIS

    1 部署IIS 1.1 安装WAS IIS原本是不支持非HTTP协议的服务,为了让IIS支持net.tcp,必须先安装WAS(Windows Process Activation Service),即 ...

  9. [转]WCF:如何将net.tcp协议寄宿到IIS

    本文转自:http://www.cnblogs.com/Gyoung/archive/2012/12/11/2812555.html 1 部署IIS 1.1 安装WAS IIS原本是不支持非HTTP协 ...

随机推荐

  1. iOS合并真机和模拟器framework

    在实际的项目开发中,我们会碰到某些静态库只能在真机或者模拟器中的一个上可以运行.为了让静态库在模拟器和真机都可以正常的运行,就涉及到如何把一个工程生成的静态库打包以后生成的framework进行合并. ...

  2. mybatis调用存过程返回结果集和out参数值

    Mapper文件: 1.配置一个参数映射集,采用hashMap对象 2.使用call调用存储过,其中in out等标识的参数需要有详细的描述,例如:mode,JavaType,jdbcType等 &l ...

  3. 小心使用replicate_do_db和replicate_ignore_db

    内容来源于网络 使用replicate_do_db和replicate_ignore_db时有一个隐患,跨库更新时会出错 如设置 replicate_do_db=testuse mysql;updat ...

  4. Debian中CodeIgniter+nginx+MariaDB+phpMyAdmin配置

    本文不讲述软件安装过程,记述本人在Debia中配置CodeIgniter时遇到的问题及解决方法,希望能够为有需要的人提供帮助. 一.Debian版本及所需的软件 Debian 9.8 stretch ...

  5. 详解 Python3 正则表达式(一)

    本文翻译自:https://docs.python.org/3.4/howto/regex.html 博主对此做了一些批注和修改 ^_^ 正则表达式介绍 正则表达式(Regular expressio ...

  6. java读写HDFS

    package cn.test.hdfs;   import java.io.IOException; import java.net.URI; import java.net.URISyntaxEx ...

  7. django配置虚拟环境-1

    目录 安装python 使用venv虚拟环境 使用Virtualenv虚拟环境 ### Windows安装 方案一 方案二 Linux安装 其他命令 安装django 安装python https:/ ...

  8. python2.7入门---CGI编程&文件上传&文件下载

        这次我们来看下文件下载和上传的操作.首先是上传,HTML设置上传文件的表单需要设置 enctype 属性为 multipart/form-data,代码如下所示: <!DOCTYPE h ...

  9. 关于java的wait、notify、notifyAll方法

    wait.notify.notifyAll 遇到的问题 之前开发打印机项目,因为需要使用多线程技术,当时并不怎么理解,一开始随意在方法体内使用wait.notify.notifyAll 方法导致出现了 ...

  10. BZOJ1303_中位数图_KEY

    题目传送门 较水,开两个桶即可. 题目可以理解为,将大于B的数看为1,小于B的数看为-1,将以B这个数为中位数的序列左右分为两半,加起来为0. code: #include <cstdio> ...