c#实现网站整合google登录前后端完整程序

更新时间:2025/3/12 0:00:00点击: 技术文章

1)html:(login.aspx)

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="YourNamespace.Login" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Login with Google</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Button ID="btnLogin" runat="server" Text="Login with Google" OnClick="btnLogin_Click" />
        </div>
    </form>
</body>
</html>

2)Web.config文件

<configuration>
  <appSettings>
    <add key="google_client_id" value="YOUR_CLIENT_ID"/>
    <add key="google_client_secret" value="YOUR_CLIENT_SECRET"/>
    <add key="google_redirect_uri" value="http://localhost:port/authcallback"/>
  </appSettings>
</configuration>

3.创建登录页面(login.aspx.cs)

using System;
using System.Web;

namespace YourNamespace
{
    public partial class Login : System.Web.UI.Page
    {
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            string clientId = System.Configuration.ConfigurationManager.AppSettings["google_client_id"];
            string redirectUri = System.Configuration.ConfigurationManager.AppSettings["google_redirect_uri"];
            string authUrl = $"https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id={clientId}&redirect_uri={HttpUtility.UrlEncode(redirectUri)}&scope=openid%20profile%20email";

            Response.Redirect(authUrl);
        }
    }
}

4. 实现回调页面

AuthCallback.aspx 
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AuthCallback.aspx.cs" Inherits="YourNamespace.AuthCallback" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Auth Callback</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Label ID="lblMessage" runat="server"></asp:Label>
        </div>
    </form>
</body>
</html>

AuthCallback.aspx.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace YourNamespace
{
    public partial class AuthCallback : System.Web.UI.Page
    {
        protected async void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack && Request.QueryString["code"] != null)
            {
                string code = Request.QueryString["code"];
                string clientId = System.Configuration.ConfigurationManager.AppSettings["google_client_id"];
                string clientSecret = System.Configuration.ConfigurationManager.AppSettings["google_client_secret"];
                string redirectUri = System.Configuration.ConfigurationManager.AppSettings["google_redirect_uri"];

                var tokenRequestParameters = new Dictionary<string, string>
                {
                    { "code", code },
                    { "client_id", clientId },
                    { "client_secret", clientSecret },
                    { "redirect_uri", redirectUri },
                    { "grant_type", "authorization_code" }
                };

                using (HttpClient client = new HttpClient())
                {
                    var content = new FormUrlEncodedContent(tokenRequestParameters);
                    HttpResponseMessage response = await client.PostAsync("https://oauth2.googleapis.com/token", content);

                    if (response.IsSuccessStatusCode)
                    {
                        string jsonResponse = await response.Content.ReadAsStringAsync();
                        JObject jsonObject = JObject.Parse(jsonResponse);
                        string accessToken = jsonObject.Value<string>("access_token");

                        // Use the access token to fetch user info
                        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://www.googleapis.com/oauth2/v3/userinfo");
                        request.Headers.Add("Authorization", $"Bearer {accessToken}");
                        HttpResponseMessage userInfoResponse = await client.SendAsync(request);

                        if (userInfoResponse.IsSuccessStatusCode)
                        {
                            string userInfoJson = await userInfoResponse.Content.ReadAsStringAsync();
                            JObject userInfoObject = JObject.Parse(userInfoJson);
                            string name = userInfoObject.Value<string>("name");
                            string email = userInfoObject.Value<string>("email");

                            lblMessage.Text = $"Hello, {name}! Your email is {email}.";
                        }
                        else
                        {
                            lblMessage.Text = "Failed to retrieve user information.";
                        }
                    }
                    else
                    {
                        lblMessage.Text = "Failed to obtain access token.";
                    }
                }
            }
        }
    }
}