c#实现Google账号登入授权(OAuth 2.0)并获取个人信息

时间:2021-09-12 21:09:28

此博主要介绍通过google 账号(gmail)实现登入,授权方式OAuth2.0,下面我们开始介绍。

1.去google官网注册一个gmail账号:https://accounts.google.com/SignUp?service=devconsole&continue=https%3A%2F%2Fcode.google.com%2Fapis%2Fconsole%2F,

然后去https://cloud.google.com/console?redirected=true#/project新建一个project(如果有可以不用新建),然后https://cloud.google.com/console?redirected=true#/project/apps~steady-observer-413/apiui/app?show=allapp注册一个APP,如果是注册web app,设置好回调地址,详细如下图

 c#实现Google账号登入授权(OAuth 2.0)并获取个人信息

c#实现Google账号登入授权(OAuth 2.0)并获取个人信息

c#实现Google账号登入授权(OAuth 2.0)并获取个人信息

c#实现Google账号登入授权(OAuth 2.0)并获取个人信息

 

 

2.注册好了APP,接下来新建一个解决方案,本例用的是asp.net mvc4 web应用。

c#实现Google账号登入授权(OAuth 2.0)并获取个人信息

 

 

3.对web.config做点设置,把注册APP时得到的Client ID 和 Client Secret,Redirect Uri添加到config文件中,如下:

c#实现Google账号登入授权(OAuth 2.0)并获取个人信息

 

 

 4.一切准备就绪,开始coding了,不过在coding之前,有必要找出google oauth2.0的api,参考地址:https://developers.google.com/accounts/docs/OAuth2Login#libraries

其他更多信息参考地址:https://developers.google.com/google-apps/

c#实现Google账号登入授权(OAuth 2.0)并获取个人信息c#实现Google账号登入授权(OAuth 2.0)并获取个人信息
public class GoogleController : Controller
    {
        //
        // GET: /Google/

        private static string accessToken;
        private static string redirectUri = ConfigurationSettings.AppSettings["GL_RedirectUri"].ToString();
        private static string clientID = ConfigurationSettings.AppSettings["GL_ClientID"].ToString();
        private static string clientSecret = ConfigurationSettings.AppSettings["GL_ClientSecret"].ToString();

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Login()
        {
            //get login url
            string loginUrl = string.Format("https://accounts.google.com/o/oauth2/auth?" +
                          "scope={0}&redirect_uri={1}&response_type=code&client_id={2}&approval_prompt=force",
                          HttpUtility.HtmlEncode("https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/userinfo.email"),
                          HttpUtility.HtmlEncode(redirectUri),
                          HttpUtility.HtmlEncode(clientID));
            if (!string.IsNullOrEmpty(loginUrl))
                return Redirect(loginUrl);
            else
                return Content("Login failed!");
        }

        public ActionResult CallBack()
        {
            //get access token with code value
            string code = Request.Params["code"];

            string tokenUrl = string.Format("https://accounts.google.com/o/oauth2/token");
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(tokenUrl);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            var post = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code",
                                      code,
                                      HttpUtility.HtmlEncode(clientID),
                                      clientSecret,
                                      HttpUtility.HtmlEncode(redirectUri));

            using (var sw = new StreamWriter(request.GetRequestStream()))
            {
                sw.Write(post);
            }
            var resonseJson = "";
            using (var response = request.GetResponse())
            {
                using (var sr = new StreamReader(response.GetResponseStream()))
                {
                    resonseJson = sr.ReadToEnd();
                }
            }
            accessToken = JsonConvert.DeserializeAnonymousType(resonseJson, new { access_token = "" }).access_token;

            //get user profile
            string result = "";
            string profileUrl = string.Format("https://www.googleapis.com/oauth2/v1/userinfo?access_token={0}", accessToken);
            HttpWebRequest requestUser = (HttpWebRequest)HttpWebRequest.Create(profileUrl);
            //request.Headers.Add("Accept-Language", "zh-en");
            using (var response = requestUser.GetResponse())
            {
                using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                {
                    result = sr.ReadToEnd();
                }
            }

            UserProfile data = JsonConvert.DeserializeAnonymousType(result, new UserProfile());
            if (data != null)
                return View(data);
            else
                return View();
        }

        public class UserProfile
        {
            public string id { get; set; }
            public string email { get; set; }
            public string verified_email { get; set; }
            public string name { get; set; }
            public string given_name { get; set; }
            public string family_name { get; set; }
            public string link { get; set; }
            public string picture { get; set; }
            public string gender { get; set; }
            public string timezone { get; set; }
            public string locale { get; set; }
            public string updated_datetime { get; set; }
        }
    }
View Code
c#实现Google账号登入授权(OAuth 2.0)并获取个人信息c#实现Google账号登入授权(OAuth 2.0)并获取个人信息
@{
    ViewBag.Title = "CallBack";
}

@model GoogleSample.Controllers.GoogleController.UserProfile

<table>
    <tr>
        <td>id:</td>
        <td>
            @Html.DisplayFor(model => model.id)
        </td>
    </tr>
    <tr>
        <td>email:</td>
        <td>@Html.DisplayFor(model => model.email)</td>
    </tr>
    <tr>
        <td>family_name:</td>
        <td>@Html.DisplayFor(model => model.family_name)</td>
    </tr>
    <tr>
        <td>gender:</td>
        <td>@Html.DisplayFor(model => model.gender)</td>
    </tr>
    <tr>
        <td>given_name:</td>
        <td>@Html.DisplayFor(model => model.given_name)</td>
    </tr>
    <tr>
        <td>link:</td>
        <td>@Html.DisplayFor(model => model.link)</td>
    </tr>
    <tr>
        <td>locale:</td>
        <td>@Html.DisplayFor(model => model.locale)</td>
    </tr>
    <tr>
        <td>name:</td>
        <td>@Html.DisplayFor(model => model.name)</td>
    </tr>
    <tr>
        <td>picture:</td>
        <td>@Html.DisplayFor(model => model.picture)</td>
    </tr>
    <tr>
        <td>timezone:</td>
        <td>@Html.DisplayFor(model => model.timezone)</td>
    </tr>
    <tr>
        <td>updated_datetime:</td>
        <td>@Html.DisplayFor(model => model.updated_datetime)</td>
    </tr>
    <tr>
        <td>verified_email:</td>
        <td>@Html.DisplayFor(model => model.verified_email)</td>
    </tr>
</table>
View Code

c#实现Google账号登入授权(OAuth 2.0)并获取个人信息

c#实现Google账号登入授权(OAuth 2.0)并获取个人信息

c#实现Google账号登入授权(OAuth 2.0)并获取个人信息

以上就是google oauth2.0 授权登入的全部过程,拿到access token之后可以call google相关api,更多api请参考:https://developers.google.com/google-apps/