Google Data API授权重定向URI不匹配 [英] Google Data API Authorization Redirect URI Mismatch

查看:132
本文介绍了Google Data API授权重定向URI不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景



我想在.NET Core 1.1中编写一个小型的个人Web应用程序,以便与YouTube进行交互,并使某些事情对我来说更容易正在遵循

解决方案

原始答案有效,但是不是针对ASP.NET Web应用程序执行此操作的最佳方法。有关处理ASP.NET Web应用程序流程的更好方法,请参见下面的更新。






原始答案

所以,我知道了。问题是Google认为网络应用程序是基于JavaScript的网络应用程序,而不是经过服务器端处理的网络应用程序。因此,您不能在Google Developer Console中为基于服务器的Web应用程序创建Web应用程序OAuth客户端ID。



解决方案是选择类型 Other ,则需要在Google Developer Console中创建OAuth客户端ID。 Google会将其视为已安装的应用程序,而不是JavaScript应用程序,因此不需要重定向URI即可处理回调。



作为Google的文档,这有些令人困惑。 NET告诉您创建一个Web App OAuth客户端ID。






2018年2月16日更新,更好的答案:



我想对此答案进行更新。虽然,我上面说的有效,但这并不是为ASP.NET解决方案实现OAuth工作流的最佳方法。有一种更好的方法实际上使用了正确的OAuth 2.0流。 Google的文档对此非常糟糕(尤其是.NET),因此在此我将提供一个简单的实现示例。该示例使用的是ASP.NET内核,但很容易适应整个.NET框架:)



注意: Google确实有Google .Apis.Auth.MVC软件包可帮助简化此OAuth 2.0流程,但不幸的是,它与特定的MVC实现耦合,并且不适用于ASP.NET Core或Web API。因此,我不会使用它。我将给出的示例将适用于所有ASP.NET应用程序。相同的代码流可以用于您已启用的任何Google API,因为它取决于您所请求的范围。



此外,我假设您拥有在Google Developer信息中心中设置的应用程序。也就是说,您已经创建了一个应用程序,启用了必要的YouTube API,创建了一个Web应用程序客户端,并正确设置了允许的重定向URL。



该流程将起作用像这样:


  1. 用户单击按钮(例如,添加YouTube)

  2. 该视图会控制器上获取授权URL的方法

  3. 在控制器上,我们要求Google根据客户凭据(在Google Developer Dashboard中创建的凭据)为我们提供一个授权URL。向Google提供我们的应用程序的重定向URL(此重定向URL必须在您的Google应用程序接受的重定向URL列表中)

  4. Google为我们提供了授权URL

  5. 我们将用户重定向到该授权URL

  6. 用户授予我们对应用程序的访问权限

  7. Google为我们的应用程序提供了特殊的访问代码使用我们根据请求向Google提供的重定向URL

  8. 我们使用访问代码为用户获取Oauth令牌

  9. 我们为用户保存Oauth令牌

您需要以下NuGet软件包


  1. Google.Apis

  2. Google.Apis.Auth

  3. Google.Apis.Core

  4. Google.apis.YouTube.v3

模型

 公共类ExampleModel 
{
public bool UserHasYoutubeToken {get;组; }
}

控制器

 公共类ExampleController:控制器
{
//我假设您拥有某种服务,可以从和中读取用户将用户更新到您的数据库
私有IUserService userService;

public ExampleController(IUserService userService)
{
this.userService = userService;
}

公共异步任务< IActionResult> Index()
{
var userId = //获取用户的ID,但是却获得了

// //我假设您可以通过某种方式知道用户是否具有是否为YouTube访问令牌
var userHasToken = this.userService.UserHasYoutubeToken(userId);

var model = new ExampleModel {UserHasYoutubeToken = userHasToken}
return View(model);
}

//这是一种用于获取授权码流的方法
private AuthorizationCodeFlow GetGoogleAuthorizationCodeFlow(params string [] scopes)
{
var clientIdPath = @ C:\Path\To\My\client_id.json;
使用(var fileStream = new FileStream(clientIdPath,FileMode.Open,FileAccess.Read))
{
var clientSecrets = GoogleClientSecrets.Load(stream).Secrets;
var initializer = new GoogleAuthorizationCodeFlow.Initializer {ClientSecrets = clientSecrets,Scopes = scopes};
var googleAuthorizationCodeFlow =新的GoogleAuthorizationCodeFlow(initializer);

返回googleAuthorizationCodeFlow;
}
}

//这是您的View会调用的路由(我们将使用JQuery对其进行调用)
[HttpPost]
public异步Task< string> GetAuthorizationUrl()
{
//首先,我们需要构建一个重定向URL,在用户授予访问权限后,Google将使用该URL重定向回应用程序
var protocol = Request.IsHttps吗? https: http;
var redirectUrl = $ {protocol}:// {Request.Host} / {Url.Action(nameof(this.GetYoutubeAuthenticationToken)).TrimStart(’/’)} ;;

//接下来,我们定义要访问的范围。我们要求YouTubeForceSsl,以便我们可以管理用户的YouTube帐户。
var scopes = new [] {YouTubeService.Scope.YoutubeForceSsl};

//现在,让我们抓取AuthorizationCodeFlow,它将生成一个唯一的授权URL,以将我们的用户重定向到
var googleAuthorizationCodeFlow = this.GetGoogleAuthorizationCodeFlow(scopes);
var codeRequestUrl = googleAuthorizationCodeFlow.CreateAuthorizationCodeRequest(redirectUrl);
codeRequestUrl.ResponseType =代码;

//建立网址
varauthorizationUrl = codeRequestUrl.Build();

//将其返回给调用方以进行重定向
returnauthorizationUrl;
}

公共异步任务< IActionResult> GetYoutubeAuthenticationToken([FromQuery]字符串代码)
{
if(string.IsNullOrEmpty(code))
{
/ *
这意味着用户已取消且未授予我们访问。在这种情况下,请求网址上会有一个名为错误的查询参数
,其中将包含错误消息。您可以处理这种情况。
在这里,我们什么也不会做,但是您应该编写代码来处理这种情况,但是您的应用程序
需要这样做。
* /
}

// userId是与您的应用程序相关的用户ID(不是他们的Youtube ID)。
//这是您在用户注册时为他们分配的用户ID,但是您可以使用应用程序唯一地标识用户
var userId = //但是却可以获取用户的ID(是否在声明中)或将其存储在会话中或其他地方)

//我们需要再次构建相同的重定向网址。 Google将此用于验证,我认为...?不确定
//在此阶段使用的是什么,我只知道我们需要它:)
var protocol = Request.IsHttps吗? https: http;
var redirectUrl = $ {protocol}:// {Request.Host} / {Url.Action(nameof(this.GetYoutubeAuthenticationToken)).TrimStart(’/’)} ;;

//现在,让我们向Youtube索取我们的OAuth令牌,该令牌将使我们能够为用户做一些很棒的事情
var scope = new [] {YouTubeService.Scope.YoutubeForceSsl};
var googleAuthorizationCodeFlow = this.GetYoutubeAuthorizationCodeFlow(scopes);
var token = await googleAuthorizationCodeFlow.ExchangeCodeForTokenAsync(userId,code,redirectUrl,CancellationToken.None);

//现在,您需要将此令牌按比例存储到您的用户。因此,尽管您保存了用户数据,但只需确保
//为用户保存令牌即可。这是您用来建立代表用户
//所需的UserCredentials的令牌。
var tokenJson = JsonConvert.SerializeObject(token);
等待this.userService.SaveUserToken(userId,tokenJson);

//现在我们已经可以访问用户的YouTube帐户了,让我们回到
//我们的应用程序中:)
return RedirectToAction(nameof(this.Index) );
}
}

视图

  @使用YourApplication.Controllers 
@model YourApplication.Models.ExampleModel

< div>
@if(Model.UserHasYoutubeToken)
{
< p>是!我们可以访问您的YouTube帐户!< / p>
}
其他
{
< button id = addYoutube>添加YouTube< / button>
}
< / div>

< script>
$ {document).ready(function(){
var addYoutubeUrl ='@ Url.Action(nameof(ExampleController.GetAuthorizationUrl))'';

//当用户点击添加YouTube按钮,我们将调用服务器
//以获取Google为我们建立的授权URL,然后将
//用户重定向到该网址。
$(' #addYoutube')。click(function(){
$ .post(addYoutubeUrl,function(result){
if(result){
window.location.href = result;
}
});
});
});
< / script>


Background

I am wanting to write a small, personal web app in .NET Core 1.1 to interact with YouTube and make some things easier for me to do and I am following the tutorials/samples in Google's YouTube documentation. Sounds simple enough, right? ;)

Authenticating with Google's APIs seems impossible! I have done the following:

  1. Created an account in the Google Developer Console
  2. Created a new project in the Google Developer Console
  3. Created a Web Application OAuth Client ID and added my Web App debug URI to the list of approved redirect URIs
  4. Saved the json file provided after generating the OAuth Client ID to my system
  5. In my application, my debug server url is set (and when my application launches in debug, it's using the url I set which is http://127.0.0.1:60077).

However, when I attempt to authenticate with Google's APIs, I recieve the following error:

  1. That’s an error.

Error: redirect_uri_mismatch

The redirect URI in the request, http://127.0.0.1:63354/authorize/, does not match the ones authorized for the OAuth client.

Problem

So now, for the problem. The only thing I can find when searching for a solution for this is people that say

just put the redirect URI in your approved redirect URIs

Unfortunately, the issue is that every single time my code attempts to authenticate with Google's APIs, the redirect URI it is using changes (the port changes even though I set a static port in the project's properties). I cannot seem to find a way to get it to use a static port. Any help or information would be awesome!

NOTE: Please don't say things like "why don't you just do it this other way that doesn't answer your question at all".

The code

client_id.json

{
    "web": {
        "client_id": "[MY_CLIENT_ID]",
        "project_id": "[MY_PROJECT_ID]",
        "auth_uri": "https://accounts.google.com/o/oauth2/auth",
        "token_uri": "https://accounts.google.com/o/oauth2/token",
        "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
        "client_secret": "[MY_CLIENT_SECRET]",
        "redirect_uris": [
            "http://127.0.0.1:60077/authorize/"
        ]
    }
}

Method That Is Attempting to Use API

public async Task<IActionResult> Test()
{
    string ClientIdPath = @"C:\Path\To\My\client_id.json";
    UserCredential credential;

    using (var stream = new FileStream(ClientIdPath, FileMode.Open, FileAccess.Read))
    {
        credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(stream).Secrets,
            new[] { YouTubeService.Scope.YoutubeReadonly },
            "user",
            CancellationToken.None,
            new FileDataStore(this.GetType().ToString())
        );
    }

    var youtubeService = new YouTubeService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = this.GetType().ToString()
    });

    var channelsListRequest = youtubeService.Channels.List("contentDetails");
    channelsListRequest.Mine = true;

    // Retrieve the contentDetails part of the channel resource for the authenticated user's channel.
    var channelsListResponse = await channelsListRequest.ExecuteAsync();

    return Ok(channelsListResponse);
}

Project Properties

解决方案

The Original Answer works, but it is NOT the best way to do this for an ASP.NET Web Application. See the update below for a better way to handle the flow for an ASP.NET Web Application.


Original Answer

So, I figured this out. The issue is that Google thinks of a web app as a JavaScript based web application and NOT a web app with server side processing. Thus, you CANNOT create a Web Application OAuth Client ID in the Google Developer Console for a server based web application.

The solution is to select the type Other when creating an OAuth Client ID in the Google Developer Console. This will have Google treat it as an installed application and NOT a JavaScript application, thus not requiring a redirect URI to handle the callback.

It's somewhat confusing as Google's documentation for .NET tells you to create a Web App OAuth Client ID.


Feb 16, 2018 Updated Better Answer:

I wanted to provide an update to this answer. Though, what I said above works, this is NOT the best way to implement the OAuth workflow for a ASP.NET solution. There is a better way which actually uses a proper OAuth 2.0 flow. Google's documentation is terrible in regards to this (especially for .NET), so I'll provide a simple implementation example here. The sample is using ASP.NET core, but it's easily adapted to the full .NET framework :)

Note: Google does have a Google.Apis.Auth.MVC package to help simplifiy this OAuth 2.0 flow, but unfortunately it's coupled to a specific MVC implementation and does not work for ASP.NET Core or Web API. So, I wouldn't use it. The example I'll be giving will work for ALL ASP.NET applications. This same code flow can be used for any of the Google APIs you've enabled as it's dependent on the scopes you are requesting.

Also, I am assuming you have your application set up in your Google Developer dashboard. That is to say that you have created an application, enabled the necessary YouTube APIs, created a Web Application Client, and set your allowed redirect urls properly.

The flow will work like this:

  1. The user clicks a button (e.g. Add YouTube)
  2. The View calls a method on the Controller to obtain an Authorization URL
  3. On the controller method, we ask Google to give us an Authorization URL based on our client credentials (the ones created in the Google Developer Dashboard) and provide Google with a Redirect URL for our application (this Redirect URL must be in your list of accepted Redirect URLs for your Google Application)
  4. Google gives us back an Authorization URL
  5. We redirect the user to that Authorization URL
  6. User grants our application access
  7. Google gives our application back a special access code using the Redirect URL we provided Google on the request
  8. We use that access code to get the Oauth tokens for the user
  9. We save the Oauth tokens for the user

You need the following NuGet Packages

  1. Google.Apis
  2. Google.Apis.Auth
  3. Google.Apis.Core
  4. Google.apis.YouTube.v3

The Model

public class ExampleModel
{
    public bool UserHasYoutubeToken { get; set; }
}

The Controller

public class ExampleController : Controller
{
    // I'm assuming you have some sort of service that can read users from and update users to your database
    private IUserService userService;

    public ExampleController(IUserService userService)
    {
        this.userService = userService;
    }

    public async Task<IActionResult> Index()
    {
        var userId = // Get your user's ID however you get it

        // I'm assuming you have some way of knowing if a user has an access token for YouTube or not
        var userHasToken = this.userService.UserHasYoutubeToken(userId);

        var model = new ExampleModel { UserHasYoutubeToken = userHasToken }
        return View(model);
    }

    // This is a method we'll use to obtain the authorization code flow
    private AuthorizationCodeFlow GetGoogleAuthorizationCodeFlow(params string[] scopes)
    {
        var clientIdPath = @"C:\Path\To\My\client_id.json";
        using (var fileStream = new FileStream(clientIdPath, FileMode.Open, FileAccess.Read))
        {
            var clientSecrets = GoogleClientSecrets.Load(stream).Secrets;
            var initializer = new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = clientSecrets, Scopes = scopes };
            var googleAuthorizationCodeFlow = new GoogleAuthorizationCodeFlow(initializer);

            return googleAuthorizationCodeFlow;
        }
    }

    // This is a route that your View will call (we'll call it using JQuery)
    [HttpPost]
    public async Task<string> GetAuthorizationUrl()
    {
        // First, we need to build a redirect url that Google will use to redirect back to the application after the user grants access
        var protocol = Request.IsHttps ? "https" : "http";
        var redirectUrl = $"{protocol}://{Request.Host}/{Url.Action(nameof(this.GetYoutubeAuthenticationToken)).TrimStart('/')}";

        // Next, let's define the scopes we'll be accessing. We are requesting YouTubeForceSsl so we can manage a user's YouTube account.
        var scopes = new[] { YouTubeService.Scope.YoutubeForceSsl };

        // Now, let's grab the AuthorizationCodeFlow that will generate a unique authorization URL to redirect our user to
        var googleAuthorizationCodeFlow = this.GetGoogleAuthorizationCodeFlow(scopes);
        var codeRequestUrl = googleAuthorizationCodeFlow.CreateAuthorizationCodeRequest(redirectUrl);
        codeRequestUrl.ResponseType = "code";

        // Build the url
        var authorizationUrl = codeRequestUrl.Build();

        // Give it back to our caller for the redirect
        return authorizationUrl;
    }

    public async Task<IActionResult> GetYoutubeAuthenticationToken([FromQuery] string code)
    {
        if(string.IsNullOrEmpty(code))
        {
            /* 
                This means the user canceled and did not grant us access. In this case, there will be a query parameter
                on the request URL called 'error' that will have the error message. You can handle this case however.
                Here, we'll just not do anything, but you should write code to handle this case however your application
                needs to.
            */
        }

        // The userId is the ID of the user as it relates to YOUR application (NOT their Youtube Id).
        // This is the User ID that you assigned them whenever they signed up or however you uniquely identify people using your application
        var userId = // Get your user's ID however you do (whether it's on a claim or you have it stored in session or somewhere else)

        // We need to build the same redirect url again. Google uses this for validaiton I think...? Not sure what it's used for
        // at this stage, I just know we need it :)
        var protocol = Request.IsHttps ? "https" : "http";
        var redirectUrl = $"{protocol}://{Request.Host}/{Url.Action(nameof(this.GetYoutubeAuthenticationToken)).TrimStart('/')}";

        // Now, let's ask Youtube for our OAuth token that will let us do awesome things for the user
        var scopes = new[] { YouTubeService.Scope.YoutubeForceSsl };
        var googleAuthorizationCodeFlow = this.GetYoutubeAuthorizationCodeFlow(scopes);
        var token = await googleAuthorizationCodeFlow.ExchangeCodeForTokenAsync(userId, code, redirectUrl, CancellationToken.None);

        // Now, you need to store this token in rlation to your user. So, however you save your user data, just make sure you
        // save the token for your user. This is the token you'll use to build up the UserCredentials needed to act on behalf
        // of the user.
        var tokenJson = JsonConvert.SerializeObject(token);
        await this.userService.SaveUserToken(userId, tokenJson);

        // Now that we've got access to the user's YouTube account, let's get back
        // to our application :)
        return RedirectToAction(nameof(this.Index));
    }
}

The View

@using YourApplication.Controllers
@model YourApplication.Models.ExampleModel

<div>
    @if(Model.UserHasYoutubeToken)
    {
        <p>YAY! We have access to your YouTube account!</p>
    }
    else
    {
        <button id="addYoutube">Add YouTube</button>
    }
</div>

<script>
    $(document).ready(function () {
        var addYoutubeUrl = '@Url.Action(nameof(ExampleController.GetAuthorizationUrl))';

        // When the user clicks the 'Add YouTube' button, we'll call the server
        // to get the Authorization URL Google built for us, then redirect the
        // user to it.
        $('#addYoutube').click(function () {
            $.post(addYoutubeUrl, function (result) {
                if (result) {
                    window.location.href = result;
                }
            });
        });
    });
</script>

这篇关于Google Data API授权重定向URI不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆