Guest User

Google Calendar OAuth 2.0 Example

a guest
Mar 1st, 2013
2,027
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.75 KB | None | 0 0
  1. using System;
  2. using System.Data;
  3. using System.Linq;
  4. using System.Threading;
  5. using System.Web;
  6. using DotNetOpenAuth.Messaging;
  7. using DotNetOpenAuth.OAuth2;
  8. using Google.Apis.Authentication.OAuth2;
  9. using Google.Apis.Calendar.v3;
  10. using Google.Apis.Calendar.v3.Data;
  11. using Google.Apis.Util;
  12.  
  13. namespace GoogleCalendar
  14. {
  15.     public partial class _Default : System.Web.UI.Page
  16.     {
  17.         private static CalendarService _service; // We don't need individual service instances for each client.
  18.         private static OAuth2Authenticator<WebServerClient> _authenticator;
  19.         private DataSet dsCalendars = new DataSet("Calendars");
  20.  
  21.         protected void Page_Load(object sender, EventArgs e)
  22.         {
  23.             // Create the Tasks-Service if it is null.
  24.             if (_service == null)
  25.             {
  26.                 _service = new CalendarService(_authenticator = CreateAuthenticator());
  27.             }
  28.             var state = _authenticator.State;
  29.         }
  30.  
  31.         protected void listButton_Click(object sender, EventArgs e)
  32.         {
  33.             FetchCalendarlists();
  34.         }
  35.  
  36.         public void FetchCalendarlists()
  37.         {
  38.             try
  39.             {
  40.                 // Fetch all TasksLists of the user asynchronously.
  41.                 CalendarList response = _service.CalendarList.List().Fetch();
  42.                 ShowCalendarslists(response);
  43.             }
  44.             catch (ThreadAbortException)
  45.             {
  46.                 // User was not yet authenticated and is being forwarded to the authorization page.
  47.                 throw;
  48.             }
  49.             catch (Exception ex)
  50.             {
  51.                 output.Text = ex.Message.ToString();
  52.             }
  53.         }
  54.  
  55.         private void ShowCalendarslists(CalendarList response)
  56.         {
  57.             if (response.Items == null) // If no item is in the response, .Items will be null.
  58.             {
  59.                 return;
  60.             }
  61.  
  62.             foreach (CalendarListEntry list in response.Items)
  63.             {
  64.                 var events = _service.Events.List(list.Id).Fetch();
  65.                 var table = events.Items.OfType<Event>().ToDataTable(list.Id);
  66.                 dsCalendars.Tables.Add(table);
  67.             }
  68.         }
  69.  
  70.         private OAuth2Authenticator<WebServerClient> CreateAuthenticator()
  71.         {
  72.             // Register the authenticator.
  73.             var provider = new WebServerClient(GoogleAuthenticationServer.Description);
  74.             provider.ClientIdentifier = ClientCredentials.ClientID;
  75.             provider.ClientSecret = ClientCredentials.ClientSecret;
  76.             var authenticator =
  77.                 new OAuth2Authenticator<WebServerClient>(provider, GetAuthorization) { NoCaching = false };
  78.             return authenticator;
  79.         }
  80.  
  81.         private static IAuthorizationState GetAuthorization(WebServerClient client)
  82.         {
  83.             // If this user is already authenticated, then just return the auth state.
  84.  
  85.             IAuthorizationState state = new AuthorizationState(new[] { CalendarService.Scopes.Calendar.GetStringValue() });
  86.             string refreshToken = LoadRefreshToken();
  87.             if (!String.IsNullOrWhiteSpace(refreshToken))
  88.             {
  89.                 state.RefreshToken = refreshToken;
  90.  
  91.                 if (client.RefreshToken(state))
  92.                     return state;
  93.             }
  94.  
  95.             // Check if an authorization request already is in progress.
  96.             state = client.ProcessUserAuthorization(new HttpRequestInfo(HttpContext.Current.Request));
  97.             if (state != null && (!string.IsNullOrEmpty(state.AccessToken) || !string.IsNullOrEmpty(state.RefreshToken)))
  98.             {
  99.                 // Store and return the credentials.
  100.                 StoreRefreshToken(state);
  101.                 return state;
  102.             }
  103.  
  104.             // Otherwise do a new authorization request.
  105.             string scope = CalendarService.Scopes.Calendar.GetStringValue();
  106.             OutgoingWebResponse response = client.PrepareRequestUserAuthorization(new[] { scope });
  107.             response.Send(); // Will throw a ThreadAbortException to prevent sending another response.
  108.  
  109.             return null;
  110.         }
  111.  
  112.         private static string LoadRefreshToken()
  113.         {
  114.             DBDataContext db = new DBDataContext();
  115.             var token = string.Empty;
  116.  
  117.             var userToken = db.UserTokens.SingleOrDefault(o => o.UserName == HttpContext.Current.User.Identity.Name);
  118.             if (userToken != null)
  119.             {
  120.                 token = userToken.Token;
  121.             }
  122.             return token;
  123.         }
  124.  
  125.         private static void StoreRefreshToken(IAuthorizationState state)
  126.         {
  127.             DBDataContext db = new DBDataContext();
  128.  
  129.             UserToken userToken = db.UserTokens.SingleOrDefault(o => o.UserName == HttpContext.Current.User.Identity.Name);
  130.             if (userToken == null)
  131.             {
  132.                 userToken = new UserToken()
  133.                 {
  134.                     UserName = HttpContext.Current.User.Identity.Name
  135.                 };
  136.                 db.UserTokens.InsertOnSubmit(userToken);
  137.             }
  138.             userToken.Token = state.RefreshToken;
  139.  
  140.             db.SubmitChanges();
  141.         }
  142.     }
  143.  
  144.     internal static class ClientCredentials
  145.     {
  146.         /// <summary>
  147.         /// The OAuth2.0 Client ID of your project.
  148.         /// </summary>
  149.         public static readonly string ClientID = "Your Client ID";
  150.  
  151.         /// <summary>
  152.         /// The OAuth2.0 Client secret of your project.
  153.         /// </summary>
  154.         public static readonly string ClientSecret = "Your Client Secret";
  155.  
  156.         /// <summary>
  157.         /// Your Api/Developer key.
  158.         /// </summary>
  159.         public static readonly string ApiKey = "Your API Key";
  160.     }
  161. }
Advertisement
Add Comment
Please, Sign In to add comment