Google OAuth


SUBMITTED BY: Guest

DATE: May 19, 2013, 3:49 a.m.

FORMAT: C#

SIZE: 6.8 kB

HITS: 2108

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

comments powered by Disqus