Google
Authentication
@using Skybrud.Social.Google
@using Skybrud.Social.Google.OAuth
@inherits WebViewPage
@{
// Initialize a new instance of the OAuth client
GoogleOAuthClient oauth = new GoogleOAuthClient {
ClientId = "The client ID of your project",
ClientSecret = "The client secret of your project",
RedirectUri = "The return URI (where users should be redirected after the login)"
};
// Read some input from the query string
string code = Request.QueryString["code"];
string action = Request.QueryString["do"];
string error = Request.QueryString["error"];
// Handle the state when the user clicks our login button
if (action == "login") {
// Get the redirect URI (if present)
string redirect = (Request.QueryString["redirect"] ?? "/");
// Set the state (a unique/random value)
string state = Guid.NewGuid().ToString();
Session["Google_" + state] = redirect;
// Construct the authorization URL
string authorizationUrl = oauth.GetAuthorizationUrl(state, GoogleScopes.Email + GoogleScopes.Profile, GoogleAccessType.Online, GoogleApprovalPrompt.Force);
// Redirect the user to the OAuth dialog
Response.Redirect(authorizationUrl);
return;
}
// Handle if an error occurs during the Google authentication (eg. if the user cancels the login)
if (!String.IsNullOrWhiteSpace(error)) {
<div class="alert alert-danger">
<strong>Login failed</strong><br />
Error received from Google: @error
</div>
return;
}
// Handle the state when the user is redirected back to our page after a successful login with the Google API
if (!String.IsNullOrWhiteSpace(code)) {
// Get the state from the query string
string state = Request.QueryString["state"];
// Validate state - Step 1
if (state == null) {
<div class="alert alert-danger">No <strong>state</strong> specified in the query string.</div>
return;
}
// Validate state - Step 2
string session = Session["Google_" + state] as string;
if (session == null) {
<div class="alert alert-danger">Session expired?</div>
return;
}
// Remove the state from the session
Session.Remove("Google_" + state);
// Exchange the authorization code for an access token
GoogleAccessTokenResponse response = oauth.GetAccessTokenFromAuthorizationCode(code);
string accessToken = response.AccessToken;
// Print out the access token to the user (we really shouldn't do this in a live environment)
<div class="alert alert-info">
<strong>Access token:</strong> @accessToken
</div>
// Initialize a new instance of the GoogleService class so we can make calls to the API
GoogleService service = GoogleService.CreateFromAccessToken(accessToken);
// Make a call to the API to get information about the authenticated user
GoogleUserInfo user = service.GetUserInfo();
<div class="alert alert-info">
<strong>ID:</strong> @user.Id<br />
<strong>Name:</strong> @user.Name<br />
<strong>Email:</strong> @user.Email
</div>
return;
}
<a href="?do=login" class="btn btn-primary">Login with Google</a>
}