GoogleOAuth2AuthenticationOptions将access_type设置为离线

eCo*_*rke 8 c# oauth-2.0 owin asp.net-mvc-5

我正在尝试使用MVC5项目中的Microsoft.Owin.Security.Google获取Google帐户的刷新令牌.要从google服务器获取resposne中的RefreshToken,我需要设置access_type = offline.但我找不到任何合适的属性GoogleOAuth2AuthenticationOptions.

用于允许身份验证的代码

        var gao = new GoogleOAuth2AuthenticationOptions
        {
            ClientId = ConfigurationManager.AppSettings.Get("GoogleClientId"),
            ClientSecret = ConfigurationManager.AppSettings.Get("GoogleClientSecret"),
            Provider = new GoogleOAuth2AuthenticationProvider
            {
                OnAuthenticated = async ctx =>
                {
                    var refreshToken = ctx.RefreshToken;
                    //ctx.Identity.AddClaim(new Claim("refresh_token", refreshToken));                    
                }
            }
        };

        gao.Scope.Add(TasksService.Scope.Tasks);
        gao.Scope.Add("openid");

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

ste*_*ann 5

Microsoft.Owin.Security 库的 3.0.0 版将将此选项添加到 GoogleOAuth2AuthenticationProvider(请参阅已修复的问题 #227)。根据Katana 项目路线图,它将在 2014 年夏末推出。如果您在正式发布之前需要此功能,您可以通过预发布的 NuGet 渠道获取最新版本。

然后你可以像这样配置它(在 Startup.Auth.cs 中):

app.UseGoogleAuthentication(new Microsoft.Owin.Security.Google.GoogleOAuth2AuthenticationOptions {
    ClientId = ...,
    ClientSecret = ...,
    AccessType = "offline",
    Provider = new Microsoft.Owin.Security.Google.GoogleOAuth2AuthenticationProvider {
        OnAuthenticated = context => {
            if (!String.IsNullOrEmpty(context.RefreshToken)) {
                context.Identity.AddClaim(new Claim("RefreshToken", context.RefreshToken));
            }
            return Task.FromResult<object>(null);
        }
    });
Run Code Online (Sandbox Code Playgroud)

并且您可以在 ExternalLoginCallback 中获取刷新令牌(如果您保留默认代码组织,则为 AccountController.cs):

string refreshToken = loginInfo.ExternalIdentity.Claims
    .Where(i => i.Type == "RefreshToken")
    .Select(i => i.Value)
    .SingleOrDefault();
Run Code Online (Sandbox Code Playgroud)