Asp.net mvc 3 如何在OAuth资源服务器中验证访问令牌

Asp.net mvc 3 如何在OAuth资源服务器中验证访问令牌,asp.net-mvc-3,rest,oauth,oauth-2.0,Asp.net Mvc 3,Rest,Oauth,Oauth 2.0,我有3个应用程序;生成令牌的OAuth 2.0身份验证服务器、请求令牌的OAuth客户端、提供Restful API的OAuth资源服务器。这些都是MVC3Web应用程序。 我的问题是如何验证从客户端到达OAuth资源服务器的访问令牌? 例如,OAuth客户端接收到来自OAuth服务器的带有访问令牌的响应。然后,客户机在请求OAuth资源服务器调用其中一个API函数之前,将该令牌添加到报头中。 尽管我可以在头文件[Authentication]中看到acces令牌,但我找不到验证该令牌的方法。

我有3个应用程序;生成令牌的OAuth 2.0身份验证服务器、请求令牌的OAuth客户端、提供Restful API的OAuth资源服务器。这些都是MVC3Web应用程序。 我的问题是如何验证从客户端到达OAuth资源服务器的访问令牌? 例如,OAuth客户端接收到来自OAuth服务器的带有访问令牌的响应。然后,客户机在请求OAuth资源服务器调用其中一个API函数之前,将该令牌添加到报头中。 尽管我可以在头文件[Authentication]中看到acces令牌,但我找不到验证该令牌的方法。 因为我使用MVC3通过Area设计Restful API,所以我不能使用下面的函数,它与SOAP web服务一起使用

private static IPrincipal VerifyOAuth2(HttpRequestMessageProperty httpDetails, Uri requestUri, params string[] requiredScopes) {
        // for this sample where the auth server and resource server are the same site,
        // we use the same public/private key.
        using (var signing = PixidoRest.MvcApplication.CreateAuthorizationServerSigningServiceProvider())
        {
            using (var encrypting = PixidoRest.MvcApplication.CreateResourceServerEncryptionServiceProvider())
            {
                var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(signing, encrypting));
                return resourceServer.GetPrincipal(httpDetails, requestUri, requiredScopes);
            }
        }
    }
因为我无法找到“HttpRequestMessageProperty”的路径,所以我被困在那里验证从客户端收到的AccesToken。如何在MVC3RESTfulAPI应用程序上作为OAuth客户机的资源服务器进行验证

以下是我的其他代码:

internal static RSACryptoServiceProvider CreateResourceServerEncryptionServiceProvider()
    {
        var resourceServerEncryptionServiceProvider = new RSACryptoServiceProvider();
        resourceServerEncryptionServiceProvider.ImportParameters(ResourceServerEncryptionPrivateKey);
        return resourceServerEncryptionServiceProvider;
    }

    /// <summary>
    /// Creates the crypto service provider for the authorization server that contains the public key used to verify an access token signature.
    /// </summary>
    /// <returns>An RSA crypto service provider.</returns>
    internal static RSACryptoServiceProvider CreateAuthorizationServerSigningServiceProvider()
    {
        var authorizationServerSigningServiceProvider = new RSACryptoServiceProvider();
        authorizationServerSigningServiceProvider.ImportParameters(AuthorizationServerSigningPublicKey);
        return authorizationServerSigningServiceProvider;
    }

public class RequireAuthorization : ActionFilterAttribute
{
    public string Scope { get; set; }

    public override void OnActionExecuting(ActionExecutingContext actionContext)
    {
        string[] scope = null;
        if (!string.IsNullOrEmpty(Scope))
        {
            scope = Scope.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
        }

        var query = actionContext.RequestContext.HttpContext.Request;
        var req = actionContext.HttpContext;
        var authvalue = query.Headers["Authorization"];
        OAuthAuthorizationManager.VerifyOAuth2(query, query.Url.AbsoluteUri);
        //var response = new HttpResponseMessageProperty()
        //{
           //here is my question.
        //};


        base.OnActionExecuting(actionContext);

        //redirect page to
        //if (CheckUrCondition)
        //{
        //actionContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
        //{
        //    controller = "Home",
        //    action = "Index"
        //}));
        ////}
    }
内部静态RSACryptServiceProvider CreateResourceServerEncryptionServiceProvider()
{
var resourceServerEncryptionServiceProvider=新的RSACryptServiceProvider();
resourceServerEncryptionServiceProvider.ImportParameters(ResourceServerEncryptionPrivateKey);
返回resourceServerEncryptionServiceProvider;
}
/// 
///为包含用于验证访问令牌签名的公钥的授权服务器创建加密服务提供程序。
/// 
///RSA加密服务提供商。
内部静态RSACryptServiceProvider CreateAuthorizationServerSigningServiceProvider()
{
var authorizationServerSigningServiceProvider=新的RSACryptServiceProvider();
authorizationServerSigningServiceProvider.ImportParameters(AuthorizationServerSigningPublicKey);
返回授权服务器SigningServiceProvider;
}
公共类需要重新授权:ActionFilterAttribute
{
公共字符串作用域{get;set;}
公共覆盖无效OnActionExecuting(ActionExecutingContext actionContext)
{
string[]scope=null;
如果(!string.IsNullOrEmpty(范围))
{
scope=scope.Split(新[]{,“},StringSplitOptions.RemoveEmptyEntries);
}
var query=actionContext.RequestContext.HttpContext.Request;
var req=actionContext.HttpContext;
var authvalue=query.Headers[“授权”];
OAuthAuthorizationManager.VerifyOAuth2(query,query.Url.AbsoluteUri);
//var response=新的HttpResponseMessageProperty()
//{
//这是我的问题。
//};
base.OnActionExecuting(actionContext);
//将页面重定向到
//如果(检查条件)
//{
//actionContext.Result=新的重定向路由结果(新的路由值字典(新的
//{
//controller=“Home”,
//action=“Index”
//}));
////}
}

提前感谢。

我遇到了同样的问题,并提出了以下适用于我的自定义授权属性。请注意,我的示例依赖于使用依赖项注入注入的ResourceServer属性。当然,您也可以让它指向静态实例

using System;
using System.Threading;
using System.Web;
using System.Web.Mvc;

using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OAuth2;

/// <summary>
/// Allows authorization to be applied to ASP.NET MVC methods where OAuth is used as the authorization mechanism.
/// </summary>
public class OAuthAuthorizeAttribute : AuthorizeAttribute
{
    /// <summary>
    /// Gets or sets the resource server that will be used to process the access token
    /// that will be used to authorized.
    /// </summary>
    /// <value>
    /// The resource server.
    /// </value>
    /// <remarks>
    /// This property will most likely be set using dependency-injection.
    /// </remarks>
    public ResourceServer ResourceServer { get; set; }

    /// <summary>
    /// Gets or sets the scopes.
    /// </summary>
    /// <value>
    /// The required scopes.
    /// </value>
    /// <remarks>
    /// Multiple scopes can be used by separating them with spaces.
    /// </remarks>
    public string Scopes { get; set; }

    /// <summary>
    /// When overridden, provides an entry point for custom authorization checks.
    /// </summary>
    /// <param name="httpContext">The HTTP context, which encapsulates all HTTP-specific information about an individual HTTP request.</param>
    /// <returns>
    /// true if the user is authorized; otherwise, false.
    /// </returns>
    /// <exception cref="System.InvalidOperationException">Thrown when the <see cref="ResourceServer"/> property is <c>null</c>.</exception>
    /// <exception cref="System.InvalidOperationException">Thrown when the <see cref="Scopes"/> property is <c>null</c>.</exception>
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (this.ResourceServer == null)
        {
            throw new InvalidOperationException("The ResourceServer property must not be null.");
        }

        try
        {
            this.StorePrincipalFromAccessToken(httpContext);

            return this.AccessTokenIsAuthorizedForRequestedScopes();
        }
        catch (ProtocolException)
        {
            return false;
        }
    }

    /// <summary>
    /// Processes HTTP requests that fail authorization.
    /// </summary>
    /// <param name="filterContext">Encapsulates the information for using <see cref="T:System.Web.Mvc.AuthorizeAttribute" />. The <paramref name="filterContext" /> object contains the controller, HTTP context, request context, action result, and route data.</param>
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new HttpUnauthorizedResult();
    }

    /// <summary>
    /// Stores the principal contained in the current access token.
    /// </summary>
    /// <param name="httpContext">The HTTP context.</param>
    protected virtual void StorePrincipalFromAccessToken(HttpContextBase httpContext)
    {
        httpContext.User = this.ResourceServer.GetPrincipal();
        Thread.CurrentPrincipal = httpContext.User;
    }

    /// <summary>
    /// Check if the access token provided is authorized for the requested scopes.
    /// </summary>
    /// <returns></returns>
    protected virtual bool AccessTokenIsAuthorizedForRequestedScopes()
    {
        return OAuthUtilities.SplitScopes(this.Scopes ?? string.Empty).IsSubsetOf(this.ResourceServer.GetAccessToken().Scope);
    }
}

你解决了吗?如果是,请分享!
using System.Web.Mvc;

public class DemoController : Controller
{
    [OAuthAuthorize(Scopes = "public")]
    public ActionResult Index()
    {
        return this.View();
    }
}