你试过DevDefined.OAuth吗?
我用它来保护我的WebApi与2- legs OAuth。我还成功地用PHP客户端测试了它。
使用这个库可以很容易地添加对OAuth的支持。下面是如何实现ASP的提供程序。NET MVC Web API:
1)获取DevDefined的源代码。OAuth: https://github.com/bittercoder/DevDefined.OAuth——最新版本允许OAuthContextBuilder扩展。
2)构建库并在Web API项目中引用它。
3)创建一个自定义上下文构建器来支持从HttpRequestMessage构建上下文:
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http;
using System.Web;
using DevDefined.OAuth.Framework;
public class WebApiOAuthContextBuilder : OAuthContextBuilder
{
public WebApiOAuthContextBuilder()
: base(UriAdjuster)
{
}
public IOAuthContext FromHttpRequest(HttpRequestMessage request)
{
var context = new OAuthContext
{
RawUri = this.CleanUri(request.RequestUri),
Cookies = this.CollectCookies(request),
Headers = ExtractHeaders(request),
RequestMethod = request.Method.ToString(),
QueryParameters = request.GetQueryNameValuePairs()
.ToNameValueCollection(),
};
if (request.Content != null)
{
var contentResult = request.Content.ReadAsByteArrayAsync();
context.RawContent = contentResult.Result;
try
{
// the following line can result in a NullReferenceException
var contentType =
request.Content.Headers.ContentType.MediaType;
context.RawContentType = contentType;
if (contentType.ToLower()
.Contains("application/x-www-form-urlencoded"))
{
var stringContentResult = request.Content
.ReadAsStringAsync();
context.FormEncodedParameters =
HttpUtility.ParseQueryString(stringContentResult.Result);
}
}
catch (NullReferenceException)
{
}
}
this.ParseAuthorizationHeader(context.Headers, context);
return context;
}
protected static NameValueCollection ExtractHeaders(
HttpRequestMessage request)
{
var result = new NameValueCollection();
foreach (var header in request.Headers)
{
var values = header.Value.ToArray();
var value = string.Empty;
if (values.Length > 0)
{
value = values[0];
}
result.Add(header.Key, value);
}
return result;
}
protected NameValueCollection CollectCookies(
HttpRequestMessage request)
{
IEnumerable<string> values;
if (!request.Headers.TryGetValues("Set-Cookie", out values))
{
return new NameValueCollection();
}
var header = values.FirstOrDefault();
return this.CollectCookiesFromHeaderString(header);
}
/// <summary>
/// Adjust the URI to match the RFC specification (no query string!!).
/// </summary>
/// <param name="uri">
/// The original URI.
/// </param>
/// <returns>
/// The adjusted URI.
/// </returns>
private static Uri UriAdjuster(Uri uri)
{
return
new Uri(
string.Format(
"{0}://{1}{2}{3}",
uri.Scheme,
uri.Host,
uri.IsDefaultPort ?
string.Empty :
string.Format(":{0}", uri.Port),
uri.AbsolutePath));
}
}
4)使用本教程创建OAuth提供者:http://code.google.com/p/devdefined-tools/wiki/OAuthProvider。在最后一步(访问受保护资源示例)中,您可以在AuthorizationFilterAttribute属性中使用以下代码:
public override void OnAuthorization(HttpActionContext actionContext)
{
// the only change I made is use the custom context builder from step 3:
OAuthContext context =
new WebApiOAuthContextBuilder().FromHttpRequest(actionContext.Request);
try
{
provider.AccessProtectedResourceRequest(context);
// do nothing here
}
catch (OAuthException authEx)
{
// the OAuthException's Report property is of the type "OAuthProblemReport", it's ToString()
// implementation is overloaded to return a problem report string as per
// the error reporting OAuth extension: http://wiki.oauth.net/ProblemReporting
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
{
RequestMessage = request, ReasonPhrase = authEx.Report.ToString()
};
}
}
我已经实现了我自己的提供者,所以我还没有测试上面的代码(当然除了我在我的提供者中使用的WebApiOAuthContextBuilder),但它应该可以正常工作。