[转]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 ...
随机推荐
- 企业IT架构转型之道 读书笔记-1.阿里巴巴集团中台战略引发的思考
前言 1.为什么选择看这本书 2.Supercell公司的开发模式 3.“烟囱式”系统建设模式弊端,及产生这种现象的原因 4.IT人员在企业信息中心的组织职能 一.为什么选择看这本书 多日没有更新博客 ...
- 多线程并行计算数据总和 —— 优化计算思想(多线程去计算)—— C语言demo
多线程计算整型数组数据总和: #include <stdio.h> #include <stdlib.h> #include <Windows.h> #includ ...
- 常用类(日期时间格式转换,date,枚举)
1 常用类 1.1 日期时间类 计算机如何表示时间? 时间戳(timestamp):距离特定时间的时间间隔. 计算机时间戳是指距离历元(1970-01-01 00:00:00:000)的时间间隔(ms ...
- 动态代理(JDK实现)
JDK动态代理,针对目标对象的接口进行代理 ,动态生成接口的实现类 !(必须有接口) public class ProxyDemo { //通过方法的返回值得到代理对象 方法参数 ...
- [bzoj4444] 国旗计划 双指针+倍增
Description A国正在开展一项伟大的计划--国旗计划.这项计划的内容是边防战士手举国旗环绕边境线奔袭一圈.这项计划需要多名边防战士以接力的形式共同完成,为此,国土安全局已经挑选了N名优秀的边 ...
- BruteXSS(汉化版)
BruteXSS是一个非常强大和快速的跨站点脚本暴力注入.它用于暴力注入一个参数.该BruteXSS从指定的词库加载多种有效载荷进行注入并且使用指定的载荷和扫描检查这些参数很容易受到XSS漏洞.得益于 ...
- java的堆,栈,静态代码区 详解
面试中,有家公司做数据库开发的,对内存要求比较高,考到了这个 一:在JAVA中,有六个不同的地方可以存储数据: 1. 寄存器(register). 这是最快的存储区,因为它位于不同于其他存储区的地方— ...
- [Flex] 组件Tree系列 —— 作为PopUpButton的弹出菜单
mxml: <?xml version="1.0" encoding="utf-8"?> <!--功能描述:Tree作为PopUpButton ...
- [VB6.0-->VB.NET]关于VB6.0升级到VB.NET的微软官方文档
升级流程大体是这样的: 1.用VS2008打开Vb6.0的工程(此时针对语言层面自动升级). 注: VS更新多版了(当前最新VS2017),用最新版再打开2008升级后的工程的时候还是会有自动升级,相 ...
- git 命令摘录
回滚 n 个 commit (增加了revert commit) git revert -n commit_id 回滚到指定的commit_id(不增加commit,回滚的commit_id被删除) ...