DotNetOpenAuth ctp 4.0 ResourceServer.VerifyAccess()方法抛出null异常

时间:2012-01-06 20:42:54

标签: c# asp.net-mvc dotnetopenauth oauth-2.0 wcf-web-api

我在尝试使用DotNetOpenAuth ctp 4.0时遇到困难。情况如下: 我有一个资源服务器,就像OAuth2示例中的资源服务器一样,但是我正在使用WCF Web Api预览6,所以我编写了一个可扩展点,负责验证执行操作请求的客户端是否已经授权执行此操作,为了实现这一点,调用方法ResourceServer.VerifyAccess。这个方法抛出一个null异常,我还没找到原因。

这就是我编写操作处理程序的方式:

protected override HttpRequestMessage OnHandle(HttpRequestMessage input)
    {
        var principal = VerifyOAuth2(input);
        if(principal == null)
        {
            throw new HttpResponseException(new HttpResponseMessage
                                                {
                                                    StatusCode = HttpStatusCode.Unauthorized,
                                                    Content = new StringContent("Invalid Access Token")
                                                });
        }

        var roles = _authorizationAttribute.Roles.Split(new[] {" "}, StringSplitOptions.RemoveEmptyEntries);
        if(!roles.Any(role => principal.IsInRole(role)))
        {
            throw new HttpResponseException(new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.Forbidden,
                Content = new StringContent("User has not permission to access this resource")
            });
        }

        return input;
    }

    private static IPrincipal VerifyOAuth2(HttpRequestMessage request)
    {
        var headers = request.Headers;
        var headersCollection = new WebHeaderCollection();
        foreach (var header in headers)
        {
            headersCollection.Add(header.Key, header.Value.ToString());
        }

        using (var signing = MvcApplication.CreateAuthorizationServerSigningServiceProvider())
        {
            using (var encrypting = MvcApplication.CreateResourceServerEncryptionServiceProvider())
            {
                var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(signing, encrypting));

                IPrincipal result;
                var httpRequestInfo = new HttpRequestInfo(request.Method.ToString(), request.RequestUri,
                                                          request.RequestUri.AbsoluteUri, headersCollection, request.Content.ReadAsStreamAsync().Result);//Since I dont have an HttpResourceInfo Object I need to build one from my request, using an overloaded method. 
                var error = resourceServer.VerifyAccess(httpRequestInfo, out result); //here is where the exception is thrown. 
                // TODO: return the prepared error code.
                return error != null ? null : result;
            }
        }

我不知道这段代码是否有帮助,但如果没有,你能告诉我这个方法什么时候抛出空引用异常?也许那会对我有所帮助!提前谢谢你。

1 个答案:

答案 0 :(得分:1)

NullReferenceException的堆栈跟踪会有所帮助。

取而代之的是,您是否尝试过从WCF获取HttpRequestMessageProperty并将其传递给HttpRequestInfo构造函数,与OAuthAuthorizationManager在样本中的方式相同?