0
votes

I am trying to access Google Tasks using OAuth 2.0 via DotNetOpenAuth and the dotnet library for Google Tasks.

To be honest I am a bit baffled by the whole OAuth process but anyway.

I'm trying to follow the same process that the OAuth2 playground goes through in my app: i.e.

  1. User clicks link to authorize app
  2. App uses DotNetOpenAuth to construct a request to Google
  3. User is presented with "My application would like to.." screen and authorizes the app
  4. Browser redirected to the callback_uri with authorization code
  5. Code is exchanged for access_token
  6. Access token is used in subsequent requests

I'm not worrying about refresh tokens or anything yet.

So I'm up to step 5 and am stuck. I just can't figure out how to exchange the authorization code for an access token.

I am calling a method on the OAuthAuthenticator<T> (part of Google Tasks lib) called LoadAccessToken which sounds like the right method but this results in the following error:

The following required parameters were missing from the
DotNetOpenAuth.OAuth2.Messages.AccessTokenAuthorizationCodeRequest message: redirect_uri

However as you can see from my code I am setting the callback before calling LoadAccessToken.

Here's my code:

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;
    }
}

Any ideas?

2

2 Answers

1
votes

Check out the documentation for an example on how to use the DotNet.OAuth2 code. It has a great example to show you how to get the OAuth dance setup.

1
votes