简体   繁体   English

使用谷歌 OAuth 2.0 和 C# 登录

[英]Login using Google OAuth 2.0 with C#

I want to allow User to login using Gmail .我想允许用户使用Gmail登录。 So, I googled and got many samples but all were using OpenID and as I have checked Google Documentation, they have stopped new domain registration for OpenID and from now, Developer will need to use OAuth API.因此,我在谷歌上搜索并获得了很多样本,但所有样本都在使用 OpenID,而且我查看了 Google 文档,他们已经停止了 OpenID 的新域注册,从现在开始,开发人员将需要使用 OAuth API。

I have registered my Project and got Secrey KEY & Client ID.我已经注册了我的项目并获得了 Secrey KEY 和客户 ID。 Now I want to integrate it my Project but I am unable to find any sample working Project.现在我想将它集成到我的项目中,但我找不到任何示例工作项目。

Please help me regarding this.请帮我解决这个问题。 I am not using MVC.我没有使用 MVC。

I am explaining based on Google+ API, which uses Gmail ID to login.我是基于 Google+ API 解释的,它使用 Gmail ID 登录。 So, you will be authenticating your users to login with Gmail.因此,您将验证您的用户以使用 Gmail 登录。

1: You need to turn on the Google+ API : 1:您需要开启Google+ API

谷歌+ API

2: Once you turned on the Google+ API, then you need to add new Client ID . 2:一旦你开启了 Google+ API,那么你需要添加新的Client ID

创建新客户 ID

Step 2

Web 应用程序客户端 ID

Step 3

客户端 ID、秘密和重定向 URL

Here in Step 2, when you add Redirect URL, you will need to add the URL of your website on which page you want user to redirected to.在第 2 步中,当您添加重定向 URL 时,您需要添加您希望用户重定向到的页面的网站 URL。

Once you have created your Client ID for Web Application.一旦您为 Web 应用程序创建了客户端 ID。

Then in your application, you need to add two packages然后在您的应用程序中,您需要添加两个包

1: Newtonsoft.Json

安装包 Newtonsoft.Json

2: Microsoft.Net.Http

安装包 Microsoft.Net.Http

Now add this namespaces;现在添加这个命名空间;

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;

Now in code first your declare this variables at top of your page;现在首先在代码中在页面顶部声明此变量;

protected string googleplus_client_id = "458878619548-khuatamj3qpiccnsm4q6dbulf13jumva.apps.googleusercontent.com";    // Replace this with your Client ID
protected string googleplus_client_secret = "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;

Then in you Page Load event;然后在你的页面加载事件中;

protected void Page_Load(object sender, EventArgs e)
{
    if ((Session.Contents.Count > 0) && (Session["loginWith"] != null) && (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_secret + "&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, 0, 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);
                        }
                    }

                }
            }
        }
        catch (Exception ex)
        {
            //throw new Exception(ex.Message, ex);
            Response.Redirect("index.aspx");
        }
    }
}

Now the event that will call the google API现在将调用 google API 的事件

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

Add this GooglePlusAccessToken class;添加这个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; }
}

Also you can call other oauth API with the Access Token to retrieve some of users information.您也可以使用Access Token调用其他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; }
}

Hope this is what you were looking for, I implemented this and it is working just fine.希望这就是你要找的,我实现了这个,它工作得很好。 Hope this helps.希望这可以帮助。

Based on Google lastest API for DotNet I have used below code which works for Console App, Web Form and Asp.Net MVC as well.基于 Google 最新的 DotNet API,我使用了以下代码,这些代码也适用于控制台应用程序、Web 窗体和 Asp.Net MVC。

 public async Task<UserCredential> getUserCredential()
    {
        UserCredential credential;
        string[] scopes = new string[] {  }; // user basic profile

        //Read client id and client secret from Web config file

        credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                   new ClientSecrets
                   {
                       ClientId = ConfigurationManager.AppSettings["ClientId"],
                       ClientSecret = ConfigurationManager.AppSettings["ClientSecret"]
                   }, scopes,
            "user", CancellationToken.None, new FileDataStore("Auth.Api.Store"));

        return credential;
    }

Here ClientId and ClientSecret stored in web.config file which can be modified later easily if requires.这里 ClientId 和 ClientSecret 存储在 web.config 文件中,以后可以根据需要轻松修改。

If you are using Asp.Net MVC or Asp.Net Core and you want some east setup for Google Login than you can try package Install-Package GoogleAuthentication -Version 1.0.0.如果您使用的是 Asp.Net MVC 或 Asp.Net Core,并且您想要 Google 登录的一些东部设置,那么您可以尝试 package Install-Package GoogleAuthentication -Version 1.0.0。 This package help you in getting Google sign In data using three methods.此 package 可帮助您使用三种方法获取 Google 登录数据。

 public async Task<ActionResult> GoogleLoginCallback(string code)
    {
        try
        {
            var ClientSecret = "Enter Client Secret here";
            var ClientID = "Enter Client Id here";
            var url = "https://localhost:44375/Login/GoogleLoginCallback";
            var token = await GoogleAuth.GetAuthAccessToken(code, ClientID, ClientSecret, url);
            var userProfile = await GoogleAuth.GetProfileResponseAsync(token.AccessToken.ToString());
            var googleUser = JsonConvert.DeserializeObject<GoogleProfile>(userProfile);
           
        }
        catch (Exception ex)
        {
            
        }
        return RedirectToAction("index", "Users");
    }

You can check out the installation steps for this package and also all steps for getting clientId and Client Secret from Google Sign In using GoogleAuthentication Nuget Package in detailed steps and also with sample code provided您可以查看此 package 的安装步骤以及使用 GoogleAuthentication Nuget Package 从 Google Sign In获取 clientId 和 Client Secret 的所有步骤的详细步骤以及提供的示例代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM