本文转自:https://blogs.msdn.microsoft.com/astoriateam/2010/07/21/odata-and-authentication-part-6-custom-basic-authentication/

You might remember, from Part 5, that Basic Authentication is built-in to IIS.

So why do we need ‘Custom’ Basic Authentication?

Well if you are happy using windows users and passwords you don’t.

That’s because the built-in Basic Authentication, uses the Basic Authentication protocol, to authenticate against the windows user database.

If however you have a custom user/password database, perhaps it’s part of your application database, then you need ‘Custom’ Basic Authentication.

How does basic auth work?

Basic authentication is a very simple authentication scheme, that should only be used in conjunction with SSL or in scenarios where security isn’t paramount.

If you look at how a basic authentication header is fabricated, you can see why it is NOT secure by itself:

var creds = “user” + “:” + “password”;
var bcreds = Encoding.ASCII.GetBytes(creds);
var base64Creds = Convert.ToBase64String(bcreds);
authorizationHeader = “Basic ” + base64Creds; Yes that’s right the username and password are Base64 encoded and shipped on the wire for the whole world to see, unless of course you are also using SSL for transport level security. Nevertheless many systems use basic authentication. So it’s worth adding to your arsenal. Server Code: Creating a Custom Basic Authentication Module: Creating a Custom Basic Authentication module should be no harder than cracking Basic Auth, i.e. it should be child’s play. We can use our HttpModule from Part 5 as a starting point: public class BasicAuthenticationModule: IHttpModule
{
public void Init(HttpApplication context)
{
context.AuthenticateRequest
+= new EventHandler(context_AuthenticateRequest);
}
void context_AuthenticateRequest(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
if (!BasicAuthenticationProvider.Authenticate(application.Context))
{
application.Context.Response.Status = “401 Unauthorized”;
application.Context.Response.StatusCode = 401;
application.Context.Response.AddHeader(“WWW-Authenticate”, “Basic”);
application.CompleteRequest();
}
}
public void Dispose() { }
} The only differences from Part 5 are:
•We’ve changed the name to BasicAuthenticationModule.
•We use a new BasicAuthenticationProvider to do the authentication.
•And if the logon fails we challenge using the “WWW-Authenticate” header. The final step is vital because without this clients that don’t send credentials by default – like HttpWebRequest and by extension DataServiceContext – won’t know to retry with the credentials when their first attempt fails. Implementing the BasicAuthenticationProvider: The Authenticate method is unchanged from our example in Part 5: public static bool Authenticate(HttpContext context)
{
if (!HttpContext.Current.Request.IsSecureConnection)
return false; if (!HttpContext.Current.Request.Headers.AllKeys.Contains(“Authorization”))
return false; string authHeader = HttpContext.Current.Request.Headers[“Authorization”]; IPrincipal principal;
if (TryGetPrincipal(authHeader, out principal))
{
HttpContext.Current.User = principal;
return true;
}
return false;
} Our new TryGetPrincipal method looks like this: private static bool TryGetPrincipal(string authHeader, out IPrincipal principal)
{
var creds = ParseAuthHeader(authHeader);
if (creds != null && TryGetPrincipal(creds, out principal))
return true; principal = null;
return false;
} As you can see it uses ParseAuthHeader to extract the credentials from the authHeader – so they can be checked against our custom user database in the other TryGetPrincipal overload: private static string[] ParseAuthHeader(string authHeader)
{
// Check this is a Basic Auth header
if (
authHeader == null ||
authHeader.Length == 0 ||
!authHeader.StartsWith(“Basic”)
) return null; // Pull out the Credentials with are seperated by ‘:’ and Base64 encoded
string base64Credentials = authHeader.Substring(6);
string[] credentials = Encoding.ASCII.GetString(
Convert.FromBase64String(base64Credentials)
).Split(new char[] { ‘:’ }); if (credentials.Length != 2 ||
string.IsNullOrEmpty(credentials[0]) ||
string.IsNullOrEmpty(credentials[0])
) return null; // Okay this is the credentials
return credentials;
} First this code checks that this is indeed a Basic auth header and then attempts to extract the Base64 encoded credentials from the header. If everything goes according to plan the array returned will have two elements: the username and the password. Next we check our ‘custom’ user database to see if those credentials are valid. In this toy example I have it completely hard coded: private static bool TryGetPrincipal(string[] creds,out IPrincipal principal)
{
if (creds[0] == “Administrator” && creds[1] == “SecurePassword”)
{
principal = new GenericPrincipal(
new GenericIdentity(“Administrator”),
new string[] {“Administrator”, “User”}
);
return true;
}
else if (creds[0] == “JoeBlogs” && creds[1] == “Password”)
{
principal = new GenericPrincipal(
new GenericIdentity(“JoeBlogs”),
new string[] {“User”}
);
return true;
}
else
{
principal = null;
return false;
}
} You’d probably want to check a database somewhere, but as you can see that should be pretty easy, all you need is a replace this method with whatever code you want. Registering our BasicAuthenticationModule: Finally you just need to do is add this to your WebConfig: <system.webServer>
<modules>
<add name=”BasicAuthenticationModule”
type=”SimpleService.BasicAuthenticationModule”/>
</modules>
</system.webServer> Allowing unauthenticated access: If you want to allow some unauthenticated access to your Data Service, you could change your BasicAuthenticationModule so it doesn’t ‘401’ if the Authenticate() returns false. Then if certain queries or updates actually require authentication or authentication, you could check HttpContext.Current.Request.IsAuthenticated or HttpContext.Current.Request.User in QueryInterceptors and ChangeInterceptors as necessary. This approach allows you to mix and match your level of security. See part 4 for more on QueryInterceptors. Client Code: When you try to connect to an OData service protected with Basic Authentication (Custom or built-in) you have two options: Using the DataServiceContext.Credentials: You can use a Credentials Cache like this. var serviceCreds = new NetworkCredential(“Administrator”, “SecurePassword”);
var cache = new CredentialCache();
var serviceUri = new Uri(“http://localhost/SimpleService”);
cache.Add(serviceUri, “Basic”, serviceCreds);
ctx.Credentials = cache; When you do this the first time Data Services attempts to connect to the Service the credentials aren’t sent – so a 401 is received. However so long as the service challenges using the “WWW-Authenticate” response header, it will seamlessly retry under the hood. Using the request headers directly: Another option is to just create and send the authentication header yourself. 1) Hook up to the DataServiceContext’s SendingRequest Event: ctx.SendingRequest +=new EventHandler<SendingRequestEventArgs>(OnSendingRequest); 2) Add the Basic Authentication Header to the request: static void OnSendingRequest(object sender, SendingRequestEventArgs e)
{
var creds = “user” + “:” + “password”;
var bcreds = Encoding.ASCII.GetBytes(creds);
var base64Creds = Convert.ToBase64String(bcreds);
e.RequestHeader.Add(“Authorization”, “Basic ” + base64Creds);
} As you can see this is pretty simple. And has the advantage that it will work even if the server doesn’t respond with a challenge (i.e. WWW-Authenticate header). Summary: You now know how to implement Basic Authentication over a custom credentials database and how to interact with a Basic Authentication protected service using the Data Service Client. Next up we’ll look at Forms Authentication in depth. Alex James
Program Manager
Microsoft.

[转]OData and Authentication – Part 6 – Custom Basic Authentication的更多相关文章

  1. [转]OData and Authentication – Part 5 – Custom HttpModules

    本文转自:https://blogs.msdn.microsoft.com/odatateam/2010/07/19/odata-and-authentication-part-5-custom-ht ...

  2. 一个HTTP Basic Authentication引发的异常

    这几天在做一个功能,其实很简单.就是调用几个外部的API,返回数据后进行组装然后成为新的接口.其中一个API是一个很奇葩的API,虽然是基于HTTP的,但既没有基于SOAP规范,也不是Restful风 ...

  3. Secure Spring REST API using Basic Authentication

    What is Basic Authentication? Traditional authentication approaches like login pages or session iden ...

  4. Atitit HTTP 认证机制基本验证 (Basic Authentication) 和摘要验证 (Digest Authentication)attilax总结

    Atitit HTTP认证机制基本验证 (Basic Authentication) 和摘要验证 (Digest Authentication)attilax总结 1.1. 最广泛使用的是基本验证 ( ...

  5. Nancy 学习-身份认证(Basic Authentication) 继续跨平台

    开源 示例代码:https://github.com/linezero/NancyDemo 前面讲解Nancy的进阶部分,现在来学习Nancy 的身份认证. 本篇主要讲解Basic Authentic ...

  6. HTTP Basic Authentication

    Client端发送请求, 要在发送请求的时候添加HTTP Basic Authentication认证信息到请求中,有两种方法:1. 在请求头中添加Authorization:    Authoriz ...

  7. Web services 安全 - HTTP Basic Authentication

    根据 RFC2617 的规定,HTTP 有两种标准的认证方式,即,BASIC 和 DIGEST.HTTP Basic Authentication 是指客户端必须使用用户名和密码在一个指定的域 (Re ...

  8. Web API 基于ASP.NET Identity的Basic Authentication

    今天给大家分享在Web API下,如何利用ASP.NET Identity实现基本认证(Basic Authentication),在博客园子搜索了一圈Web API的基本认证,基本都是做的Forms ...

  9. PYTHON实现HTTP基本认证(BASIC AUTHENTICATION)

    参考: http://www.voidspace.org.uk/python/articles/authentication.shtml#id20 http://zh.wikipedia.org/wi ...

随机推荐

  1. C#基础之流程控制语句详解

    C#程序的执行都是一行接一行.自上而下地进行,不遗漏任何代码.为了让程序能按照开发者所设计的流程进行执行,必然需要进行条件判断.循环和跳转等过程,这就需要实现流程控制.C#中的流程控制包含了条件语句. ...

  2. JS判断时特殊值与boolean类型的转换

    扒开JQuery以及其他一些JS框架源码,常常能看到下面这样的判断,写惯了C#高级语言语法的我,一直以来没能系统的理解透这段代码. var test; //do something... if(tes ...

  3. Java50道经典习题-程序11 求不重复数字

    题目:有1.2.3.4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?分析:可填在百位.十位.个位的数字都是1.2.3.4.组成所有的排列后再去 掉不满足条件的排列. public cla ...

  4. 73. 矩阵置零 leetcode JAVA

    题目: 给定一个 m x n 的矩阵,如果一个元素为 0,则将其所在行和列的所有元素都设为 0.请使用原地算法. 示例 1: 输入: [   [1,1,1],   [1,0,1],   [1,1,1] ...

  5. 栈实现 C语言

    最近上来写了一下栈,理解数据结构的栈. 头文件:stack.h 初始化栈结构与函数定义: #include<stdlib.h> #include <stdio.h> #incl ...

  6. “全栈2019”Java异常第十八章:Exception详解

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java异 ...

  7. “全栈2019”Java第九十七章:在方法中访问局部内部类成员详解

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java第 ...

  8. 腾讯云服务器部署 django项目整个流程

    CentOS7下部署Django项目详细操作步骤 前记:购买腾讯云服务器,配置自选,当然新用户免费体验半个月,我选择的系统是centos7系统版本, 接下来我们来看整个配置项目流程. 部署是基于:ce ...

  9. spring管理hibernate session的问题探究

    我们再用spring管理hibernate的时候, 我们会继承HibernateDaoSupport 或者HibernateTemplate类. 我们不知道这两个类之间有什么关系. 也没有去关闭ses ...

  10. [Flex] 组件Tree系列 —— 作为PopUpButton的弹出菜单

    mxml: <?xml version="1.0" encoding="utf-8"?> <!--功能描述:Tree作为PopUpButton ...