[转]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的更多相关文章
- [转]OData and Authentication – Part 5 – Custom HttpModules
本文转自:https://blogs.msdn.microsoft.com/odatateam/2010/07/19/odata-and-authentication-part-5-custom-ht ...
- 一个HTTP Basic Authentication引发的异常
这几天在做一个功能,其实很简单.就是调用几个外部的API,返回数据后进行组装然后成为新的接口.其中一个API是一个很奇葩的API,虽然是基于HTTP的,但既没有基于SOAP规范,也不是Restful风 ...
- Secure Spring REST API using Basic Authentication
What is Basic Authentication? Traditional authentication approaches like login pages or session iden ...
- Atitit HTTP 认证机制基本验证 (Basic Authentication) 和摘要验证 (Digest Authentication)attilax总结
Atitit HTTP认证机制基本验证 (Basic Authentication) 和摘要验证 (Digest Authentication)attilax总结 1.1. 最广泛使用的是基本验证 ( ...
- Nancy 学习-身份认证(Basic Authentication) 继续跨平台
开源 示例代码:https://github.com/linezero/NancyDemo 前面讲解Nancy的进阶部分,现在来学习Nancy 的身份认证. 本篇主要讲解Basic Authentic ...
- HTTP Basic Authentication
Client端发送请求, 要在发送请求的时候添加HTTP Basic Authentication认证信息到请求中,有两种方法:1. 在请求头中添加Authorization: Authoriz ...
- Web services 安全 - HTTP Basic Authentication
根据 RFC2617 的规定,HTTP 有两种标准的认证方式,即,BASIC 和 DIGEST.HTTP Basic Authentication 是指客户端必须使用用户名和密码在一个指定的域 (Re ...
- Web API 基于ASP.NET Identity的Basic Authentication
今天给大家分享在Web API下,如何利用ASP.NET Identity实现基本认证(Basic Authentication),在博客园子搜索了一圈Web API的基本认证,基本都是做的Forms ...
- PYTHON实现HTTP基本认证(BASIC AUTHENTICATION)
参考: http://www.voidspace.org.uk/python/articles/authentication.shtml#id20 http://zh.wikipedia.org/wi ...
随机推荐
- JAVA—IO操作
一.JAVA I/O 输入输出流 1:编码问题 2:File类的使用 3:RandomAccessFile的使用 4:字节流的使用 5:字符流的使用 6:对象的序列化和反序列化 2: file类的使用 ...
- 虚拟化 - VMware
和VirtualBox一样,也需要关掉Hyper-V才能启动虚拟机,否则会报Guard的错误. 网络 [转]VMware网络连接模式-桥接.NAT以及仅主机模式的详细介绍和区别 桥接 就好像在局域网中 ...
- sharepoint 通过数据库擅长列表项
select *from [dbo].[AllLists] where tp_Title='Pages' and tp_WebId='68BDFC9A-4E0C-425E-9985-573CD6716 ...
- [Objective-C语言教程]复合对象(33)
在Objective-C中,可以在类集群中创建子类,该类集合定义了一个嵌入在其中的类. 这些类对象是复合对象.你可能想知道什么是类集群,下面首先了解什么是类集群. 1. 类集群 类集群是基础框架广泛使 ...
- iOS --UIScrollView的学习(三)自动轮播
1.前面两章讲的都是基本的用法,这次讲一下比较重要的功能分页和自动播放 2.UIPageControl--分页 2.1只要将UIScrollView的pageEnabled属性设置为YES,UIScr ...
- STM32-RS232通信软硬件实现
OS:Windows 64 Development kit:MDK5.14 IDE:UV4 MCU:STM32F103C8T6/VET6 AD:Altium Designer 18.0.12 1.RS ...
- C#-WebForm-Request、Response、QueryString
知识点: Request - 获取请求对象 专门用来接传递过来的值 Request["key"](李献策lxc) 1.获取地址栏传递过来的值 get 2.获取表单传递过来的参数值 ...
- 网络基础 09_STP生成树协议
1 STP概念 冗余拓扑结构 冗余拓扑结构能解决单点故障的问题 冗余拓扑结构会引起广播风暴,多帧COPY,MAC地址表错误的问题 广播风暴 当主机X发送一个广播包后 交换机继续没完没了的更新广播流量 ...
- 洛谷 P3757 [CQOI2017]老C的键盘
题面 luogu 题解 其实就是一颗二叉树 我们假设左儿子小于根,右儿子大于根 考虑树形\(dp\) \(f[u][i]\)表示以\(u\)为根的子树,\(u\)为第\(i\)小 那么考虑子树合并 其 ...
- ospf基础理论
OSPF简介 OSPF(Open Shortest Path First 开放式最短路径优先)协议是IETF为IP网络开发的IGP路由选择协议.它是一种典型的链路状态(link-state)路由协议. ...