加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 如何在Google.Apis调用中使用ASP.NET MVC Owin A

发布时间:2020-12-16 07:06:34 所属栏目:asp.Net 来源:网络整理
导读:我正在尝试使用Owin在Google.Apis请求中提供的AccessToken,但我收到异常System.InvalidOperationException(附加信息:访问令牌已过期但我们无法刷新它). 我的Google身份验证配置正常,我可以使用它成功登录我的应用程序.我将context.AccessToken存储为身份验
我正在尝试使用Owin在Google.Apis请求中提供的AccessToken,但我收到异常System.InvalidOperationException(附加信息:访问令牌已过期但我们无法刷新它).

我的Google身份验证配置正常,我可以使用它成功登录我的应用程序.我将context.AccessToken存储为身份验证回调中的声明(GoogleOAuth2AuthenticationProvider的OnAuthenticated“event”).

我的Startup.Auth.cs配置(app.UseGoogleAuthentication(ConfigureGooglePlus()))

private GoogleOAuth2AuthenticationOptions ConfigureGooglePlus()
{
var goolePlusOptions = new GoogleOAuth2AuthenticationOptions()
{
    ClientId = "Xxxxxxx.apps.googleusercontent.com",ClientSecret = "YYYYYYzzzzzz",Provider = new GoogleOAuth2AuthenticationProvider()
    {
        OnAuthenticated = context =>
        {
            context.Identity.AddClaim(new System.Security.Claims.Claim("Google_AccessToken",context.AccessToken));
            return Task.FromResult(0);
        }
    },SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie
};

goolePlusOptions.Scope.Add("https://www.googleapis.com/auth/plus.login");
goolePlusOptions.Scope.Add("https://www.googleapis.com/auth/userinfo.email");

return goolePlusOptions;

}

抛出异常的代码(Execute()方法)

var externalIdentity = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);

var accessTokenClaim = externalIdentity.FindAll(loginProvider + "_AccessToken").First();

var secrets = new ClientSecrets()
{
    ClientId = "Xxxxxxx.apps.googleusercontent.com",ClientSecret = "YYYYYYzzzzzz"
};

IAuthorizationCodeFlow flow =
    new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
    {
        ClientSecrets = secrets,Scopes = new[] { PlusService.Scope.PlusLogin,PlusService.Scope.UserinfoEmail }
    });

UserCredential credential = new UserCredential(flow,"me",new TokenResponse() { AccessToken = accessTokenClaim.Value });

var ps = new PlusService(
    new BaseClientService.Initializer()
    {
        ApplicationName = "My App Name",HttpClientInitializer = credential
    });

var k = ps.People.List("me",PeopleResource.ListRequest.CollectionEnum.Visible).Execute();

有没有其他方法来获取原始的AccessToken或刷新它而不通过整个身份验证过程(用户已经过身份验证)?

我需要查询一些GooglePlus个人资料数据,例如GivenName,familyName,gender,个人资料图片和个人资料网址.

解决方法

Linda帮我一个指向新的asp.net mvc样本的URL( https://codereview.appspot.com/194980043/).

我只需将AccessType =“offline”添加到GoogleOAuth2AuthenticationOptions并保存一些额外的信息,以便在需要时创建一个新的TokenResponse实例.

Google身份验证选项

private GoogleOAuth2AuthenticationOptions ConfigureGooglePlus()
{

    var goolePlusOptions = new GoogleOAuth2AuthenticationOptions()
    {
        AccessType = "offline",ClientId = "Xxxxxxx.apps.googleusercontent.com",ClientSecret = "Yyyyyyyyyy",Provider = new GoogleOAuth2AuthenticationProvider()
        {
            OnAuthenticated = context =>
            {
                context.Identity.AddClaim(new System.Security.Claims.Claim("Google_AccessToken",context.AccessToken));

                if (context.RefreshToken != null)
                {
                    context.Identity.AddClaim(new Claim("GoogleRefreshToken",context.RefreshToken));
                }
                context.Identity.AddClaim(new Claim("GoogleUserId",context.Id));
                context.Identity.AddClaim(new Claim("GoogleTokenIssuedAt",DateTime.Now.ToBinary().ToString()));
                var expiresInSec = (long)(context.ExpiresIn.Value.TotalSeconds);
                context.Identity.AddClaim(new Claim("GoogleTokenExpiresIn",expiresInSec.ToString()));


                return Task.FromResult(0);
            }
        },SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie
    };

    goolePlusOptions.Scope.Add("https://www.googleapis.com/auth/plus.login");
    goolePlusOptions.Scope.Add("https://www.googleapis.com/auth/plus.me");
    goolePlusOptions.Scope.Add("https://www.googleapis.com/auth/userinfo.email");

    return goolePlusOptions;
}

如何检索凭证(使用“存储”作为声明的令牌信息)

private async Task<UserCredential> GetCredentialForApiAsync()
{
    var initializer = new GoogleAuthorizationCodeFlow.Initializer
    {
        ClientSecrets = new ClientSecrets
        {
            ClientId = "Xxxxxxxxx.apps.googleusercontent.com",ClientSecret = "YYyyyyyyyyy",},Scopes = new[] { 
        "https://www.googleapis.com/auth/plus.login","https://www.googleapis.com/auth/plus.me","https://www.googleapis.com/auth/userinfo.email" }
    };
    var flow = new GoogleAuthorizationCodeFlow(initializer);

    var identity = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ApplicationCookie);

    var userId = identity.FindFirstValue("GoogleUserId");

    var token = new TokenResponse()
    {
        AccessToken = identity.FindFirstValue("Google_AccessToken"),RefreshToken = identity.FindFirstValue("GoogleRefreshToken"),Issued = DateTime.FromBinary(long.Parse(identity.FindFirstValue("GoogleTokenIssuedAt"))),ExpiresInSeconds = long.Parse(identity.FindFirstValue("GoogleTokenExpiresIn")),};

    return new UserCredential(flow,userId,token);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读