UWP中的Google身份验证错误

时间:2017-11-10 18:53:26

标签: uwp google-authentication

我正在尝试使用WebAuthenticationBroker创建一个使用Google身份验证的应用程序。我已经编写了以下代码来获取谷歌的代码,

public void SignInUserAsync()
{
    var code = await AuthenticateUsingWebAuthenticationBroker();
    if (string.IsNullOrEmpty(code))
        return;
    var account = await ConvertCodeToAccount(code);
}

private async Task<string> AuthenticateUsingWebAuthenticationBroker()
{
    var googleUrl = Common.Constants.AuthorizeUrl + "?client_id=" + Common.Constants.GoogleClientId;
    googleUrl += "&redirect_uri=" + Common.Constants.GoogleCallbackUrl;
    googleUrl += "&response_type=code";
    googleUrl += "&scope=" + Common.Constants.Scope;

    var startUri = new Uri(googleUrl);

    string result = string.Empty;

    try
    {
        var webAuthenticationResult = await
                WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startUri,
                  new Uri(Common.Constants.GoogleCallbackUrl));

            switch (webAuthenticationResult.ResponseStatus)
            {
                case WebAuthenticationStatus.Success:
                    // Successful authentication
                    result = webAuthenticationResult.ResponseData.Substring(webAuthenticationResult.ResponseData.IndexOf('=') + 1);
                    break;
                case WebAuthenticationStatus.UserCancel:
                    break;
                case WebAuthenticationStatus.ErrorHttp:
                    // HTTP Error
                    result = webAuthenticationResult.ResponseErrorDetail.ToString();
                    result = string.Empty;
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
        }

        return result;
    }

获取代码后,我使用以下方法从谷歌获取用户信息。

private async Task<Account> ConvertCodeToAccount(string code)
    {
        var httpClient = new HttpClient();

        IHttpContent content = new HttpFormUrlEncodedContent(new Dictionary<string, string>
        {
            {"code", code },
            {"client_id", Common.Constants.GoogleClientId },
            {"client_secret", Common.Constants.GoogleClientSecret },
            {"redirect_uri", Common.Constants.GoogleCallbackUrl },
            {"grant_type", "authorization_code" }
        });

        var accessTokenResponse = await httpClient.PostAsync(new Uri(Common.Constants.AccessTokenUrl), content);
        var responseDict =
          JsonConvert.DeserializeObject<Dictionary<string, string>>(accessTokenResponse.Content.ToString());

        return new Account(null, responseDict);
    }


public static class Constants
{
    public static string Scope = "https://www.googleapis.com/auth/userinfo.email";
    public static string AuthorizeUrl = "https://accounts.google.com/o/oauth2/auth";
    public static string AccessTokenUrl = "https://www.googleapis.com/oauth2/v4/token";
    public static string UserInfoUrl = "https://www.googleapis.com/oauth2/v2/userinfo";

    public const string GoogleCallbackUrl = "<My-Callback-Url>";
    public const string GoogleClientId = "<My-Client-Id>";
    public const string GoogleClientSecret = "<My-Client-Secret>";
    public const string UwpAccessTokenUrl = "https://accounts.google.com/o/oauth2/token";
    public const string UwpScope = "email";
}

但是当我尝试在Windows 10桌面应用程序上获取用户数据时,它会出现以下错误 Windows 10

在Windows Phone 10上,它运行正常并返回正确的数据。请告诉我如何解决它。感谢。

1 个答案:

答案 0 :(得分:0)

我注意到的第一件事是您缺少令牌交换的请求内容类型。

看看是否有效:

IHttpContent content = new HttpFormUrlEncodedContent(new Dictionary<string, string>
{
    {"code", code },
    {"client_id", Common.Constants.GoogleClientId },
    {"client_secret", Common.Constants.GoogleClientSecret },
    {"redirect_uri", Common.Constants.GoogleCallbackUrl },
    {"grant_type", "authorization_code" }
});

// add this!
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

var accessTokenResponse = await httpClient.PostAsync(new Uri(Common.Constants.AccessTokenUrl), content);