c# - OAuth 2.0 与 REST WCF 服务应用程序集成

标签 c# oauth-2.0 wcf-security

我需要帮助使用 C# 中的 VS 2012 WCF 服务应用程序模板将身份验证层 OAuth2.0 与 REST 服务集成。在允许客户端(消费者)访问其任何资源之前,此 WCF 需要为服务的授权和身份验证颁发 token 。我正在看的是三足认证。很像 Twitter、LinkedIn、Google OAuth 实现。

已在互联网上广泛搜索与 OAuth 集成的 REST WCF API,但没有找到任何合适的线索来帮助我。我看过一个旧例子 http://weblogs.asp.net/cibrax/archive/2008/11/14/using-the-wcf-oauth-channel-with-an-ado-net-service.aspx

我已使用此示例与现有的 Rest WCF 集成。当我运行该服务时,我收到“500 内部服务器错误”,有时操作会超时。

这是导致问题的实现。

我必须如下添加拦截器并在 .svc 中引用 Factory="DemoRESTOAuthService.AppServiceHostFactory":

class AppServiceHostFactory : System.ServiceModel.Activation.ServiceHostFactory
{
     //<summary>
     //Factory method called by WCF to create a <see cref="ServiceHost"/>.
     //</summary>
     //<param name="serviceType">The type of the service to be created.</param>
     //<param name="baseAddresses">Collection of base addresses where the <see cref="ServiceHost"/> can listen.</param>
     //<returns>An instance of <see cref="ServiceHost"/>.</returns>
    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
    {
        try
        {
            Microsoft.ServiceModel.Web.WebServiceHost2 result = new Microsoft.ServiceModel.Web.WebServiceHost2(serviceType, true, baseAddresses);

            result.Interceptors.Add(new OAuthChannel.OAuthInterceptor(DemoRESTOAuthService.OAuth.OAuthServicesLocator.Provider, DemoRESTOAuthService.OAuth.OAuthServicesLocator.AccessTokenRepository));

            return result;
        }
        catch(Exception e)
        {
           throw e;
        }
    }
}

当我使用日志文件进行调试时,我只能知道在 OAuthChannel 程序集的 OAuthInterceptor.cs 中抛出了异常。我使用了 tracelog 和 fiddler,但除了 500 内部服务器错误之外,我没有得到太多帮助来理解错误。

public override void ProcessRequest(ref RequestContext requestContext)
    {
        if (requestContext == null || requestContext.RequestMessage == null)
        {
            return;
        }

        Message request = requestContext.RequestMessage;


        HttpRequestMessageProperty requestProperty = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];


        OAuthContext context = new OAuthContextBuilder().FromUri(requestProperty.Method, request.Headers.To);


        try
        {
            _provider.AccessProtectedResourceRequest(context);


            OAuthChannel.Models.AccessToken accessToken = _repository.GetToken(context.Token);


            TokenPrincipal principal = new TokenPrincipal(
                new GenericIdentity(accessToken.UserName, "OAuth"),
                accessToken.Roles,
                accessToken);

            InitializeSecurityContext(request, principal);
        }
        catch (OAuthException authEx)
        {
            XElement response = XElement.Load(new StringReader("<?xml version=\"1.0\" encoding=\"utf-8\"?><html xmlns=\"http://www.w3.org/1999/xhtml\" version=\"-//W3C//DTD XHTML 2.0//EN\" xml:lang=\"en\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.w3.org/1999/xhtml http://www.w3.org/MarkUp/SCHEMA/xhtml2.xsd\"><HEAD><TITLE>Request Error</TITLE></HEAD><BODY><DIV id=\"content\"><P class=\"heading1\"><B>" + HttpUtility.HtmlEncode(authEx.Report.ToString()) + "</B></P></DIV></BODY></html>"));
            Message reply = Message.CreateMessage(MessageVersion.None, null, response);
            HttpResponseMessageProperty responseProperty = new HttpResponseMessageProperty() { StatusCode = HttpStatusCode.Forbidden, StatusDescription = authEx.Report.ToString() };
            responseProperty.Headers[HttpResponseHeader.ContentType] = "text/html";
            reply.Properties[HttpResponseMessageProperty.Name] = responseProperty;
            requestContext.Reply(reply);

            requestContext = null;
        }
    }

有人可以帮我了解发生了什么吗?

或者您能否帮助我提供任何其他适用于三足 OAuth 提供程序实现的示例、指针、提示或文档。在过去的一周里,我真的被这个问题困住了。感谢您的帮助。

提前致谢

最佳答案

您为什么不使用诸如 ServiceStack 之类的框架,它已经构建了 OAuth2 身份验证提供程序: https://github.com/ServiceStack/ServiceStack/wiki/Authentication-and-authorization

或者如果您不想使用整个堆栈,请查看他们的代码以了解它与您自己的代码有何不同。

关于c# - OAuth 2.0 与 REST WCF 服务应用程序集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15137510/

相关文章:

来自 HAProxy 或 Apache mod_proxy 的 OAuth token 验证

facebook-graph-api - Grails Spring Security如何在自定义身份验证中记住Me?

c# - 我如何识别我的服务的客户?

c# - StorageFile.OpenAsync 中的 UnauthorizedAccessException

c# - 我可以在 C# 中的一行上锁定(某物)吗?

java - 无法使用javax从android使用gmail帐户发送电子邮件

WCF如何传递 token 进行身份验证?

c# - HTTP 和 HTTP WCF 服务

c# - Unity 5 中的 GUIText(需要替代方案)

c# - x64 SQL Server 检测网络实例名称