[转]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 ...
随机推荐
- javascript做的一个根据table中某个td的值为日期时的倒计时
JavaScript代码: <script> window.onload = window.onload = function () { getTdValue(); } //根据传过来的天 ...
- Enabling Remote Errors in SSRS
January 18, 2011 By default the remote errors property in SQL Server Reporting Services is set to fa ...
- oracle根据四位年周取当周周一的日期函数
create or replace function FUNC_GET_DATE_BY_WEEK( theYearWeek IN VARCHAR2)return date is normalDate ...
- ZJOI2019 游记
Day -2 入住酒店,跟 Sooke 一个房间 酒店还是很好的呢 然后就是颓废 Sooke 和 zxy,ljx,lyt,xx 一起打 lol,我孤独的打着坦克和 MC 然后复习了一下板子 Day - ...
- Using the JDBC Driver
Download JDBC Driver This section provides quick start instructions for making a simple connection t ...
- SQL查询表结构的语句
SELECT tableName=CASE WHEN a.colorder=1 THEN d.name ELSE '' END ,表说明 =CASE WHEN a.colorder=1 THEN IS ...
- [转]NSProxy实现AOP方便为ios应用实现异常处理策略
[转载自:http://blog.csdn.net/yanghua_kobe/article/details/8395535] 前段时间关注过objc实现的AOP,在GitHub找到了其中的两个库:A ...
- Java中常用到的文件操作那些事(二)——使用POI解析Excel的两种常用方式对比
最近生产环境有个老项目一直内存报警,不时的还出现内存泄漏,导致需要重启服务器,已经严重影响正常服务了.获取生成dump文件后,使用MAT工具进行分析,发现是其中有个Excel文件上传功能时,经常会导致 ...
- Linux 线程调度策略与线程优先级
Linux内核的三种调度策略 SCHED_OTHER 分时调度策略. 它是默认的线程分时调度策略,所有的线程的优先级别都是0,线程的调度是通过分时来完成的.简单地说,如果系统使用这种调度策略,程序将无 ...
- 判断h5页面是小程序环境还是微信环境
1.话不多说直接上代码,已使用有效 <script type="text/javascript" src="https://res.wx.qq.com/open/j ...