Подтвердить что ты не робот

Войти с помощью Google OAuth 2.0 с помощью С#

Я хочу разрешить Вход пользователя с помощью Gmail. Итак, я googled и получил много образцов, но все использовали OpenID, и поскольку я проверил документацию Google, они прекратили новую регистрацию домена для OpenID, и теперь разработчику необходимо будет использовать API OAuth.

Я зарегистрировал свой проект и получил Secrey KEY и ID клиента. Теперь я хочу интегрировать его в свой проект, но я не могу найти образец рабочего проекта.

Пожалуйста, помогите мне в этом. Я не использую MVC.

4b9b3361

Ответ 1

Я объясняю на Google+ API, который использует идентификатор Gmail для входа в систему. Таким образом, вы будете аутентифицировать своих пользователей для входа в Gmail.

1: вам нужно включить Google+ API:

Google+ API

2: После того, как вы включили API Google+, вам нужно добавить новый Client ID.

Create New Client ID

Step 2

Web Application Client ID

Step 3

Client ID, Secret & Redirect URL

Здесь, на шаге 2, при добавлении URL-адреса переадресации вам нужно будет добавить URL-адрес вашего веб-сайта, на какую страницу вы хотите перенаправить пользователя.

Как только вы создали свой идентификатор клиента для веб-приложения.

Затем в вашем приложении вам нужно добавить два пакета

1: Newtonsoft.Json

Install-Package Newtonsoft.Json

2: Microsoft.Net.Http

Install-Package 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;

Затем в вашем мероприятии 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_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, 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");
        }
    }
}

Теперь событие, которое вызовет API google

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 с помощью Access Token, чтобы получить информацию о некоторых пользователях.

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; }
}

Надеюсь, это то, что вы искали, я реализовал это, и он работает отлично. Надеюсь, это поможет.

Ответ 2

На основе последнего API Google для DotNet я использовал ниже код, который работает для консольного приложения, Web Form и 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;
    }

Здесь ClientId и ClientSecret хранятся в файле web.config, который может быть легко изменен позже, если потребуется.