|
OAuth2
OAuth 2.0 in the client library
Featured An overview on using OAuth2.0 for authentication: OverviewWhile some services do not require authentication at all, or only use your developer key, most of the services require access to some of the users data. The authentication model used to access user data is OAuth2.0. OAuth 2.0 is an emerging standard for accessing protected resources on the web. Google APIs and the google-api-dotnet-client library support OAuth 2.0. Further Reading
RegisteringBefore you can use OAuth 2.0, you must register your application using the Google APIs Console. After you've registered, go to the API Access tab and copy the "Client ID" and "Client secret" values, which you'll need later. If you're writing a web application, then make sure the Redirect URI matches the URI you will use in your application to handle the redirect. For example, the sample below uses the path /Result.aspx, so if the sample application were hosted at example.com, then you would set the Redirect URI in the APIs Console to be http://example.com/Result.aspx. Using OAuth2.0Lets say you want to see all the Tasks a user has created on his Google account. Before you can access that data, you have to ask the user for permission. This process is called "Obtaining an authorization code". Once you get an authorization code, you can use this code to get a refresh-token and an access-token. An access token is usually valid for a maximum of one hour, and allows you to access the user's data. Every time you make a request to protected data, you have to authorize the request using an access token. But what should you do once your short-lived access token expires? When using your authorization code to get an access token, you also received a refresh token. A refresh token can be used to request a new access token once the previous once expired. There are two important things you should now about refresh tokens:
Sample: Tasks.SimpleOAuth2Fortunately you do not have to re-implement the whole authorization process (unless you want to). The GoogleApis.Authentication.OAuth2- and DotNetOpenAuth-library does most of the work for you. Have a look at the Tasks.SimpleOAuth2-sample: /*
Copyright 2011 Google Inc
Licensed under the Apache License, Version 2.0(the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Diagnostics;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Samples.Helper;
using Google.Apis.Tasks.v1;
using Google.Apis.Tasks.v1.Data;
using Google.Apis.Util;
namespace Google.Apis.Samples.TasksOAuth2
{
/// <summary>
/// This sample demonstrates the simplest use case for an OAuth2 service.
/// The schema provided here can be applied to every request requiring authentication.
/// </summary>
public class Program
{
public static void Main(string[] args)
{
// Display the header and initialize the sample.
CommandLine.EnableExceptionHandling();
CommandLine.DisplayGoogleSampleHeader("Tasks API");
// Register the authenticator.
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
provider.ClientIdentifier = "<client id>";
provider.ClientSecret = "<client secret>";
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
// Create the service.
var service = new TasksService(auth);
TaskLists results = service.Tasklists.List().Fetch();
Console.WriteLine("Lists:");
foreach (TaskList list in results.Items)
{
Console.WriteLine("- " + list.Title);
}
Console.ReadKey();
}
private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
{
// Get the auth URL:
IAuthorizationState state = new AuthorizationState(new[] { TasksService.Scopes.Tasks.GetStringValue() });
state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
Uri authUri = arg.RequestUserAuthorization(state);
// Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString());
Console.Write(" Authorization Code: ");
string authCode = Console.ReadLine();
Console.WriteLine();
// Retrieve the access token by using the authorization code:
return arg.ProcessUserAuthorization(authCode, state);
}
}
}What is important here?
What is next?
| ||
Which libraries are needed to support the WinForms? example?
The only external library it needs is DotNetOpenAuth? CTP (http://sourceforge.net/projects/dnoa/files/CTP/OAuth2/). Besides that, it uses GoogleApis? (of course) and ApiExplorerLib?, which is shared between ApiExplorerWeb? and ApiExplorerWinForm? projects. You probably want to download the whole source tree, since DotNetOpenAuth? dll is located outside of SampleSolution? folder, at http://code.google.com/p/google-api-dotnet-client/source/browse/#hg%2FThird%20Party%2FOAuth2. Are you getting errors when trying to build the project?
Very much appreciate your response....I've secured the DotNoetOpenAuth?.dll file but am oddly stuck getting the GoogleApis? and ApiExplorerLib?...could not filnd them in the Google Data API SDK. I signed up and cloned the google-api-dotnet-client library, but the instructions for creating a local copy (hg clone http://... ) don't make sense/don't work down here on my Win7 system...feeling pretty retarded about all this...so am extremely grateful for any patient suggestions...
Try installing "TortoiseHg?", which makes using mercurial much easier on windows. After you have installed it, right click and select "Tortoise Hg > Clone". Enter this repository URL of the repository in the upper text field: "https://google-api-dotnet-client.googlecode.com/hg/" After that enter a directory name of your choice in the second text field, and use the checkout button.
One thing the instruction page did not make clear is that the "hg clone ..." command requires Mercurial (a source control system like TFS or SVN) being already installed on local computer. If not, it might be easier to skip ahead to use TortoiseHg directly.
is it working on win phone 7 development?
Currently, this has not been tested on windows phone 7. It is being considered but has not been decided yet.
i am testing the Tasks.SimpleOAuth2 project.i have set the credentials numbers(ClientID,ClientSecret?,ApiKey?) but when i redirect to browser for the authentication code i am getting a error:"The redirect URI in the request: urn:ietf:wg:oauth:2.0:oob did not match a registered redirect URI"
zipzap:
When you created your credentials, you probably indicated that the client credentials you were creating were for a web application instead of an installed application. When you do that, you enter a Redirect URI for that set of credentials. The sample you are using is using the out of band Redirect URI for installed applications which does not match the one you specified, so it will not allow you to compete the authentication flow. This is to protect you from malicious use of your client credentials. Open the APIs console and create a new client ID for "installed applications" instead of "web applications" and this should work.
Is it so hard to make really useful sample? Code from it even not compiled correctly :(
Sorry, the design of the library has changed slightly over time, and this excerpt was overlooked. It should compile and run fine now.
You can also always find a working implementation of this code in the "Tasks.SimpleOAuth2" project: http://code.google.com/p/google-api-dotnet-client/source/browse/Tasks.SimpleOAuth2/Program.cs?repo=samples
However, I have to say that this sample only shows the basic principle of using OAuth2 -- It does not support any token caching or similar. I recommend looking at the more complex projects in the samples solution once you understand the principle.
this library is working in .net2.0 or not
I found drop dead simple to get started oauth2 documentation for both linkedIn and orkut. Something about this garbage tells me the bus boys have taken over cooking in the kitchen.