ASP.NET MVC - 获取Google OAuth令牌

DLe*_*Leh 2 asp.net asp.net-mvc oauth youtube-api

我已经在服务器端使用google的OAuth成功配置了MVC 5.但是,我还想用用户的身份验证令牌执行javascript,我不想强​​迫他们重新验证此功能.

如何在使用客户端OAuth API时保留用户的OAuth令牌?

具体来说 - 我想加载登录用户的youtube订阅.此页面包含有关如何使用服务器和客户端API的信息,但我无法在服务器回调中查找令牌存在的位置.我查看ExternalLoginCallback了我的方法中AccountController的任何信息,但我无法弄清楚哪些数据包含令牌.如果我可以在服务器端对象上找到它,我可以将它们暴露给视图以用于javascript调用,但我无法找到该令牌的位置.

tim*_*imk 7

您可以在MVC5 Startup.Auth.cs文件中自定义GoogleOAuth2AuthenticationOptions,以请求脱机访问代码和刷新令牌,以用于针对Google的OAuth2 api.

在这个例子中,我收集从谷歌传递到OWIN OAuth2中间件的值,并将它们添加到您的Callback方法中可访问的声明中.

  var googleCreds = new GoogleOAuth2AuthenticationOptions
        {
            ClientId = "[replace with your google console issued client id]",
            ClientSecret = "[replace with your google console issued client secret]",

            Provider = new Microsoft.Owin.Security.Google.GoogleOAuth2AuthenticationProvider
            {
                OnApplyRedirect = context =>
                {


                    string redirect = context.RedirectUri;
                    redirect += "&access_type=offline";
                    redirect += "&approval_prompt=force";
                    redirect += "&include_granted_scopes=true";


                    context.Response.Redirect(redirect);

                },
                OnAuthenticated = context =>
                {
                    TimeSpan expiryDuration = context.ExpiresIn ?? new TimeSpan();
                    context.Identity.AddClaim(new Claim("urn:tokens:google:email", context.Email));
                    context.Identity.AddClaim(new Claim("urn:tokens:google:url", context.GivenName));
                    if (!String.IsNullOrEmpty(context.RefreshToken))
                    {
                        context.Identity.AddClaim(new Claim("urn:tokens:google:refreshtoken", context.RefreshToken));
                    }
                    context.Identity.AddClaim(new Claim("urn:tokens:google:accesstoken", context.AccessToken));
                    if (context.User.GetValue("hd") != null)
                    {

                        context.Identity.AddClaim(new Claim("urn:tokens:google:hd", context.User.GetValue("hd").ToString()));
                    }
                    context.Identity.AddClaim(new Claim("urn:tokens:google:accesstokenexpiry", DateTime.UtcNow.Add(expiryDuration).ToString()));

                    return System.Threading.Tasks.Task.FromResult<object>(null);
                }
            }
        };
        googleCreds.Scope.Add("openid");
        googleCreds.Scope.Add("email");

        app.UseGoogleAuthentication(googleCreds);
Run Code Online (Sandbox Code Playgroud)

现在,您可以从回调方法中访问这些声明值.例如:

   var loginInfo = AuthenticationManager.GetExternalLoginInfo();
string GoogleAccessCode = String.Empty;
if (loginInfo.ExternalIdentity.Claims.FirstOrDefault(c => c.Type.Equals("urn:tokens:google:accesstoken")) != null)
                    {
                       GoogleAccessCode = loginInfo.ExternalIdentity.Claims.FirstOrDefault(c => c.Type.Equals("urn:tokens:google:accesstoken")).toString();
                }
Run Code Online (Sandbox Code Playgroud)

在验证序列开始时,或者在完成AuthenticationManager.GetExternalLoginInfo()之后,您可以清除浮动的外部验证cookie,以防止出现任何有问题的重复cookie:

 if (Request.Cookies[".AspNet.ExternalCookie"] != null)
            {
                var c = new System.Web.HttpCookie(".AspNet.ExternalCookie");
                c.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Add(c);
            }
Run Code Online (Sandbox Code Playgroud)