【问题标题】:How do I exchange an authorization code for an access_token?如何用授权码交换 access_token?
【发布时间】:2013-03-25 07:19:19
【问题描述】:

我正在尝试通过 DotNetOpenAuth 和 the dotnet library for Google Tasks 使用 OAuth 2.0 访问 Google Tasks。

说实话,我对整个 OAuth 过程有点困惑,但无论如何。

我正在尝试遵循 OAuth2 游乐场在我的应用中经历的相同过程:即

  1. 用户点击链接授权应用
  2. 应用使用 DotNetOpenAuth 构造对 Google 的请求
  3. 用户看到“我的应用程序想要..”屏幕并授权应用程序
  4. 浏览器重定向到带有授权码的 callback_uri
  5. 代码交换为 access_token
  6. 访问令牌用于后续请求

我还不担心刷新令牌或其他任何事情。

所以我到了第 5 步,却被卡住了。我只是不知道如何用授权码交换访问令牌。

我在 OAuthAuthenticator<T>(Google 任务库的一部分)上调用了一个名为 LoadAccessToken 的方法,这听起来像是正确的方法,但这会导致以下错误:


中缺少以下必需参数 DotNetOpenAuth.OAuth2.Messages.AccessTokenAuthorizationCodeRequest 消息:redirect_uri

但是,正如您从我的代码中看到的那样,我在调用 LoadAccessToken 之前设置了回调。

这是我的代码:

public class AuthController : Controller
{
    private const string clientId = "xxxx";
    private const string secret = "xxxx";

    public ActionResult Authenticate()
    {
        UserAgentClient consumer = new UserAgentClient(GoogleAuthenticationServer.Description, clientId, secret);
        IAuthorizationState state = new AuthorizationState(new[] { TasksService.Scopes.Tasks.GetStringValue() });
        state.Callback = new Uri(Url.Action("OAuthCallback","Auth",null,"http"));
        var request = consumer.RequestUserAuthorization(state);
        return Redirect(request.ToString());
    }

    public ActionResult OAuthCallback(string code)
    {
        UserAgentClient consumer = new UserAgentClient(GoogleAuthenticationServer.Description, clientId, secret);
        OAuth2Authenticator<UserAgentClient> authenticator = new OAuth2Authenticator<UserAgentClient>(consumer, ProcessAuth);

        IAuthorizationState state = new AuthorizationState(new[] { TasksService.Scopes.Tasks.GetStringValue() });
        state.Callback = new Uri(Url.Action("OAuthSuccess", "Auth", null, "http"));
        authenticator.LoadAccessToken();

        return RedirectToAction("List","Home");
    }

    public ActionResult OAuthSuccess(string access_token)
    {
        Session["token"] = access_token;
        return RedirectToAction("List", "Home");
    }

    private IAuthorizationState ProcessAuth(UserAgentClient arg)
    {
        var state = arg.ProcessUserAuthorization(Request.Url);
        return state;
    }
}

有什么想法吗?

【问题讨论】:

    标签: asp.net-mvc-3 google-api oauth-2.0 dotnetopenauth


    【解决方案1】:

    Check out the documentation 获取有关如何使用 DotNet.OAuth2 代码的示例。它有一个很好的示例向您展示如何获得 OAuth 舞蹈设置。

    【讨论】:

      【解决方案2】:

      这个例子可能更接近你想要做的。 http://www.limilabs.com/blog/oauth2-gmail-imap-web-applications

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-24
        • 2014-11-06
        • 1970-01-01
        • 1970-01-01
        • 2015-02-02
        • 1970-01-01
        • 1970-01-01
        • 2015-06-12
        相关资源
        最近更新 更多