加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

用C#登录Google OAuth 2.0

发布时间:2020-12-15 17:43:05 所属栏目:百科 来源:网络整理
导读:我想允许用户使用Gmail登录.所以,我google了很多样本??,但都使用OpenID,而且我检查了Google文档,他们已经停止了对OpenID的新域名注册,从现在起,开发人员将需要使用OAuth API. 我已经注册了我的项目,并获得了Secrey KEY客户端ID.现在我想将它整合到我的项目中
我想允许用户使用Gmail登录.所以,我google了很多样本??,但都使用OpenID,而且我检查了Google文档,他们已经停止了对OpenID的新域名注册,从现在起,开发人员将需要使用OAuth API.
我已经注册了我的项目,并获得了Secrey KEY&客户端ID.现在我想将它整合到我的项目中,但是我无法找到任何示例工程项目.
请帮我解决这个问题.我没有使用MVC.

解决方法

我正在基于Google API进行解释,该API使用Gmail ID进行登录.所以,您将验证您的用户使用Gmail登录.

1:您需要启用Google API:

2:打开Goog??le API后,您需要添加新的客户端ID.

Step 2
Step 3

在步骤2中,当您添加重定向网址时,您需要将用户要重定向到的网页的网址添加到网站.

为Web应用程序创建客户端ID后.

然后在应用程序中,您需要添加两个包

1: Newtonsoft.Json
2: Microsoft.Net.Http

现在添加这个命名空间;

using Newtonsoft.Json;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

现在在代码中,你的页面顶部声明这个变量;

protected string googleplus_client_id = "458878619548-khuatamj3qpiccnsm4q6dbulf13jumva.apps.googleusercontent.com";    // Replace this with your Client ID
        protected string googleplus_client_sceret = "4hiVJYlomswRd_PV5lyNQlfN";                                                // Replace this with your Client Secret
        protected string googleplus_redirect_url = "http://localhost:2443/Index.aspx";                                         // Replace this with your Redirect URL; Your Redirect URL from your developer.google application should match this URL.
        protected string Parameters;

然后在你的页面加载事件;

protected void Page_Load(object sender,EventArgs e)
        {
            if (Session.Contents.Count > 0)
            {
                if (Session["loginWith"] != null)
                {
                    if (Session["loginWith"].ToString() == "google")
                    {
                        try
                        {
                            var url = Request.Url.Query;
                            if (url != "")
                            {
                                string queryString = url.ToString();
                                char[] delimiterChars = { '=' };
                                string[] words = queryString.Split(delimiterChars);
                                string code = words[1];

                                if (code != null)
                                {
                                    //get the access token 
                                    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
                                    webRequest.Method = "POST";
                                    Parameters = "code=" + code + "&client_id=" + googleplus_client_id + "&client_secret=" + googleplus_client_sceret + "&redirect_uri=" + googleplus_redirect_url + "&grant_type=authorization_code";
                                    byte[] byteArray = Encoding.UTF8.GetBytes(Parameters);
                                    webRequest.ContentType = "application/x-www-form-urlencoded";
                                    webRequest.ContentLength = byteArray.Length;
                                    Stream postStream = webRequest.GetRequestStream();
                                    // Add the post data to the web request
                                    postStream.Write(byteArray,byteArray.Length);
                                    postStream.Close();

                                    WebResponse response = webRequest.GetResponse();
                                    postStream = response.GetResponseStream();
                                    StreamReader reader = new StreamReader(postStream);
                                    string responseFromServer = reader.ReadToEnd();

                                    GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject<GooglePlusAccessToken>(responseFromServer);

                                    if (serStatus != null)
                                    {
                                        string accessToken = string.Empty;
                                        accessToken = serStatus.access_token;

                                        if (!string.IsNullOrEmpty(accessToken))
                                        {
                                            // This is where you want to add the code if login is successful.
                                            // getgoogleplususerdataSer(accessToken);
                                        }
                                        else
                                        { }
                                    }
                                    else
                                    { }
                                }
                                else
                                { }
                            }
                        }
                        catch (Exception ex)
                        {
                            //throw new Exception(ex.Message,ex);
                            Response.Redirect("index.aspx");
                        }
                    }
                }
            }
        }

现在这个事件会调用google API

protected void Google_Click(object sender,EventArgs e)
{
     var Googleurl = "https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=" +RedirctedUri+ "&scope=https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/userinfo.profile&client_id=" + ClientId;
     Session["loginWith"] = "google";
     Response.Redirect(Googleurl);
}

添加这个GooglePlusAccessToken类;

// Google
    public class GooglePlusAccessToken
    {
        public string access_token { get; set; }
        public string token_type { get; set; }
        public int expires_in { get; set; }
        public string id_token { get; set; }
        public string refresh_token { get; set; }
    }

还可以使用访问令牌调用其他oauth API来检索一些用户信息.

private async void getgoogleplususerdataSer(string access_token)
        {
            try
            {
                HttpClient client = new HttpClient();
                var urlProfile = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + access_token;

                client.CancelPendingRequests();
                HttpResponseMessage output = await client.GetAsync(urlProfile);

                if (output.IsSuccessStatusCode)
                {
                    string outputData = await output.Content.ReadAsStringAsync();
                    GoogleUserOutputData serStatus = JsonConvert.DeserializeObject<GoogleUserOutputData>(outputData);

                    if (serStatus != null)
                    {
                         // You will get the user information here.
                    }
                }
            catch (Exception ex)
            { 
                 //catching the exception
            }
           }
       }

public class GoogleUserOutputData
{
    public string id { get; set; }
    public string name { get; set; }
    public string given_name { get; set; }
    public string email { get; set; }
    public string picture { get; set; }
}

希望这是你正在寻找的,我实现了这一点,它的工作正常.希望这可以帮助.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读