Advertisement
sheveron

Google OAuth example

Jun 22nd, 2011
4,751
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.56 KB | None | 0 0
  1. /*
  2. Copyright 2011 Google Inc
  3.  
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7.  
  8.     http://www.apache.org/licenses/LICENSE-2.0
  9.  
  10. Unless required by applicable law or agreed to in writing, software
  11. distributed under the License is distributed on an "AS IS" BASIS,
  12. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. See the License for the specific language governing permissions and
  14. limitations under the License.
  15. */
  16.  
  17. using System;
  18. using System.Configuration;
  19. using System.Collections.Generic;
  20. using System.IO;
  21. using System.Linq;
  22. using System.Web;
  23. using System.Web.UI;
  24. using System.Web.UI.WebControls;
  25.  
  26. using DotNetOpenAuth.Messaging;
  27. using DotNetOpenAuth.OAuth2;
  28. using DotNetOpenAuth.OAuth2.ChannelElements;
  29. using DotNetOpenAuth.OAuth2.Messages;
  30.  
  31. using Google.Apis.Authentication;
  32. using Google.Apis.Discovery;
  33. using GoogleRequests = Google.Apis.Requests;
  34.  
  35. namespace Google.Apis.Samples.ApiExplorer.Web
  36. {
  37.     public partial class Result : System.Web.UI.Page
  38.     {
  39.         private ApiUtility Api
  40.         {
  41.             get
  42.             {
  43.                 ApiUtility ret = Application["ApiUtility"] as ApiUtility;
  44.                 if (ret == null)
  45.                 {
  46.                     ret = new ApiUtility();
  47.                     Application["ApiUtility"] = ret;
  48.                 }
  49.                 return ret;
  50.             }
  51.         }
  52.  
  53.         protected void Page_Load(object sender, EventArgs e)
  54.         {
  55.             this.ExecuteMethod();
  56.         }
  57.  
  58.         /// <summary>
  59.         /// Execute selected API method
  60.         /// </summary>
  61.         private void ExecuteMethod()
  62.         {
  63.             string clientId = "911517695146.apps.googleusercontent.com";
  64.             string clientSecret = "zuTjuK3Nfj6PhddQ9J3y9xRl";
  65.  
  66.             MethodCallContext callContext = Session["callContext"] as MethodCallContext;
  67.             AuthorizationServerDescription serviceDescription = this.GetAuthorizationServerDescription();
  68.             WebServerClient client = new WebServerClient(serviceDescription, clientId, clientSecret);
  69.             IAuthorizationState authState = client.ProcessUserAuthorization(new HttpRequestInfo(Request));
  70.             if (authState != null && authState.AccessToken != null)
  71.             {
  72.                 Dictionary<string, string> tokens = this.AccessTokens;
  73.                 if (!tokens.ContainsKey(callContext.Service))
  74.                 {
  75.                     tokens.Add(callContext.Service, authState.AccessToken);
  76.                 }
  77.                 else
  78.                 {
  79.                     tokens[callContext.Service] = authState.AccessToken;
  80.                 }
  81.                 this.AccessTokens = tokens;
  82.  
  83.                 foreach (KeyValuePair<string, string> kvp in this.AccessTokens)
  84.                 {
  85.                     Page.Response.Write("Key = "+kvp.Key+", Value = "+kvp.Value+"<br />\n");
  86.                 }
  87.             }
  88.             else if (!this.AccessTokens.ContainsKey(callContext.Service))
  89.             {
  90.                 this.RequestAuthorization(client, callContext.Service);
  91.             }
  92.  
  93.             IAuthenticator authenticator = new OAuth2Authenticator("Test A", clientId, clientSecret, this.AccessTokens[callContext.Service]);
  94.             IService service = Api.GetService(callContext.Service, callContext.Version);
  95.             IMethod method = Api.GetMethod(callContext.Service, callContext.Resource, callContext.Method, callContext.Version);
  96.             GoogleRequests.IRequest request = GoogleRequests.Request.CreateRequest(service, method)
  97.                 .WithAuthentication(authenticator)
  98.                 .WithParameters(callContext.Parameters);
  99.  
  100.             using(Stream stream = request.ExecuteRequest()) {
  101.                 using(StreamReader reader = new StreamReader(stream)) {
  102.                     Response.Write(reader.ReadToEnd());
  103.                 }
  104.             }
  105.         }
  106.  
  107.         private void RequestAuthorization(WebServerClient client, string serviceName)
  108.         {
  109.             string scope = Scopes.GetScope(serviceName);
  110.             Dictionary<string, string> extraParameters = new Dictionary<string, string> { { "scope", scope } };
  111.             Uri callback = MessagingUtilities.GetRequestUrlFromContext().StripQueryArgumentsWithPrefix("oauth_");
  112.             OutgoingWebResponse response = client.PrepareRequestUserAuthorization(new string[] { scope }, null);
  113.             response.Send();
  114.         }
  115.  
  116.         private AuthorizationServerDescription GetAuthorizationServerDescription()
  117.         {
  118.             AuthorizationServerDescription serviceDescription = new AuthorizationServerDescription
  119.             {
  120.                 AuthorizationEndpoint = new Uri("https://accounts.google.com/o/oauth2/auth"),
  121.                 ProtocolVersion = ProtocolVersion.V20,
  122.                 TokenEndpoint = new Uri("https://accounts.google.com/o/oauth2/token"),
  123.             };
  124.  
  125.             return serviceDescription;
  126.         }
  127.  
  128.         /// <summary>
  129.         /// Map between service name and access tokens
  130.         /// </summary>
  131.         private Dictionary<string, string> AccessTokens
  132.         {
  133.             get
  134.             {
  135.                 Dictionary<string, string> tokens = Session["AccessToken"] as Dictionary<string, string>;
  136.                 if (tokens == null)
  137.                 {
  138.                     tokens = new Dictionary<string, string>();
  139.                 }
  140.                 return tokens;
  141.             }
  142.             set
  143.             {
  144.                 Session["AccessToken"] = value;
  145.             }
  146.         }
  147.  
  148.     }
  149. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement