使用带有C#的Google OAuth 2.0登录 [英] Login using Google OAuth 2.0 with C#
问题描述
我想允许用户使用 Gmail
登录。因此,我在Google上搜索并获得了许多示例,但是所有示例都在使用OpenID,并且正如我检查过Google文档一样,它们已经停止了OpenID的新域注册,从现在开始,开发人员将需要使用OAuth API。
我已经注册了我的项目并获得了Secrey KEY& ;;客户编号。现在,我想将其集成到我的项目中,但是找不到任何可运行的项目示例。
请对此提供帮助。我没有使用MVC。
I want to allow User to login using 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.
I have registered my Project and got Secrey KEY & Client 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.
推荐答案
我正在解释基于Google+ API的方法,该方法使用Gmail ID进行登录。因此,您将对用户进行身份验证以登录Gmail。
I am explaining based on Google+ API, which uses Gmail ID to login. So, you will be authenticating your users to login with Gmail.
1:您需要打开 Google+ API
:
2:打开Google+ API后,您需要添加新的客户ID
。
2: Once you turned on the Google+ API, then you need to add new Client ID
.
Step 2
Step 3
此处,在第2步中,添加重定向URL时,您需要添加网站的URL
创建了Web应用程序的客户端ID后。
Once you have created your Client ID for Web Application.
然后在您的应用程序,您需要添加两个软件包
Then in your application, you need to add two packages
1: Newtonsoft.Json
2: 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");
}
}
}
现在将调用的事件google API
Now the event that will call the 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);
}
添加此 GooglePlusAccessToken
class;
Add this GooglePlusAccessToken
class;
// 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
和访问令牌
来检索某些用户信息。
Also you can call other oauth API
with the Access Token
to retrieve some of users information.
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.
这篇关于使用带有C#的Google OAuth 2.0登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!