为Web Api实施两脚架OAuth 2.0

时间:2012-09-07 12:44:12

标签: asp.net-mvc-4 oauth-2.0 asp.net-web-api two-legged

我使用VS2012RC创建了一个mvc4 webapi项目。我试图在我的项目中实现两条腿的Oauth 2。我按照教程“http://community.codesmithtools.com/CodeSmith_Community/b/tdupont/archive/2011/03/18/oauth-2-0-for-mvc-two-legged-implementation.aspx”,尽管它是为mvc我实现它为web api。但是不起作用

我为我的客户端创建了一个html页面。当html页面加载时,它执行一个ajax函数,该函数用于返回“访问令牌”。

       <script type="text/javascript">
        $(document).ready(function () {
        var url = 'http://localhost:9792/api/Login';
            $.get(url, function(data) {

            alert(data);
            }, "jsonp");
        });
        </script>

服务器端代码是

[NoCache]
public class LoginController : ApiController
{

    public LoginModelOAuth GetLogin()
    {

        var response = OAuthServiceBase.Instance.RequestToken();

        LoginModelOAuth lmo = new LoginModelOAuth();
         lmo.RequestToken = response.RequestToken;

        return lmo;
    }

}

RequestToken()方法看起来像,

    public override OAuthResponse RequestToken()
    {
        var token = Guid.NewGuid().ToString("N");
        var expire = DateTime.Now.AddMinutes(5);
        RequestTokens.Add(token, expire);

        return new OAuthResponse
        {
            Expires = (int)expire.Subtract(DateTime.Now).TotalSeconds,
            RequestToken = token,
            RequireSsl = false,
            Success = true
        };
    }

LoginModelOAuth 模型看起来像,

public class LoginModelOAuth
{

    public string RequestToken { get; set; }      


    public string ErrorMessage { get; set; }

    public string ReturnUrl { get; set; }
}

当我执行客户端代码时,我收到以下错误

"500 Internal Server Error"

所以我调试了服务器端代码,在服务器端,我收到了与此代码相对应的错误

“var response = OAuthServiceBase.Instance.RequestToken();” ,错误是

  NullReferenceException was unhandled by user code

  "Object reference not set to an instance of an object."

我的webconfig文件看起来像,

  <configuration>
  <configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<section name="oauth" type="OAuth2.Mvc.Configuration.OAuthSection, OAuth2.Mvc, Version=1.0.0.0, Culture=neutral"/>
<sectionGroup name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection, DotNetOpenAuth.Core">
  <section name="messaging" type="DotNetOpenAuth.Configuration.MessagingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" />
  <section name="reporting" type="DotNetOpenAuth.Configuration.ReportingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" />
</sectionGroup>
 </configSections>
   <oauth defaultProvider="DemoProvider" defaultService="DemoService">
    <providers>
      <add name="DemoProvider" type="MillionNodesApi.OAuth.DemoProvider, MillionNodesApi" />
    </providers>
<services>
  <add name="DemoService" type="MillionNodesApi.OAuth.DemoService, MillionNodesApi" />
</services>
  </oauth>
    <system.web>
    <httpModules>
      <add name="OAuthAuthentication"     type="OAuth2.Mvc.Module.OAuthAuthenticationModule, OAuth2.Mvc, Version=1.0.0.0, Culture=neutral"/>
    </httpModules>
    <compilation debug="true" targetFramework="4.0" />
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880" />
    </authentication>
     <pages>
     <namespaces>
    <add namespace="System.Web.Helpers" />
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Optimization" />
    <add namespace="System.Web.Routing" />
    <add namespace="System.Web.WebPages" />
  </namespaces>
</pages>
</system.web>
 <dotNetOpenAuth>
    <messaging>
      <untrustedWebRequest>
    <whitelistHosts>
      <!-- Uncomment to enable communication with localhost (should generally not activate in production!) -->
      <!--<add name="localhost" />-->
    </whitelistHosts>
  </untrustedWebRequest>
</messaging>
<!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. -->
<reporting enabled="true" />

它适用于web api吗?

如果没有,请向我推荐任何有用的教程。

感谢。

1 个答案:

答案 0 :(得分:2)

我认为问题是你在IIS7 with integrated mode so you will need to migarate your config从system.web / httpModules到system.webServer / modules

<system.web>
    <httpModules>
       <add name="OAuthAuthentication"     type="OAuth2.Mvc.Module.OAuthAuthenticationModule, OAuth2.Mvc, Version=1.0.0.0, Culture=neutral"/>
    </httpModules>

变为

<system.webServer>
    <modules>
        <add name="OAuthAuthentication"     type="OAuth2.Mvc.Module.OAuthAuthenticationModule, OAuth2.Mvc, Version=1.0.0.0, Culture=neutral" preCondition="" />
    </modules>

同时尝试

您可以尝试通过设置此

来获取模块
<modules runAllManagedModulesForAllRequests="true">

或者

如果您仍然遇到问题,可能是模块的执行顺序尝试删除路由,并将您的OAuth放在顶部......

<modules>
  <remove name="UrlRoutingModule-4.0" />
<add name="OAuthAuthentication"     type="OAuth2.Mvc.Module.OAuthAuthenticationModule, OAuth2.Mvc, Version=1.0.0.0, Culture=neutral" preCondition="" />
  <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />