Oauth 2.0 如何在WPF中使用Sharp浏览器登录Google?

Oauth 2.0 如何在WPF中使用Sharp浏览器登录Google?,oauth-2.0,google-signin,cefsharp,Oauth 2.0,Google Signin,Cefsharp,我知道这是一个非常基本的问题,但我正在使用CEFSharp在wpf中创建一个浏览器(我几乎完成了),但我在一些帐户上登录google时遇到了一个障碍。我收到一条“此浏览器或应用程序可能不安全。”消息。现在,我研究了如何使用OAuth来获取一个令牌,用于访问和使用Google的某些功能,而不仅仅是如何作为一个整体登录。我只是希望用户能够登录到谷歌,就像他们在Chrome浏览器上一样(当然没有同步选项) 我在Google Console上注册了我的应用程序,收到了一个ClientId和Clien

我知道这是一个非常基本的问题,但我正在使用CEFSharp在wpf中创建一个浏览器(我几乎完成了),但我在一些帐户上登录google时遇到了一个障碍。我收到一条“此浏览器或应用程序可能不安全。”消息。现在,我研究了如何使用OAuth来获取一个令牌,用于访问和使用Google的某些功能,而不仅仅是如何作为一个整体登录。我只是希望用户能够登录到谷歌,就像他们在Chrome浏览器上一样(当然没有同步选项)

我在Google Console上注册了我的应用程序,收到了一个ClientId和ClientSecret,我创建了一个窗口,当在Google页面上单击登录按钮试图获取令牌时调用,但是当用户在电子邮件中键入时,他们会收到相同的消息(见下文)

我不确定是否有一个API可以使用,或者有什么东西可以让我的用户通过我的浏览器登录到google,而不必调用google Chrome浏览器本身,因为这违背了我的浏览器自给自足的目的。好几天来我一直在为这件事绞尽脑汁。有人能帮忙吗

下面是我的Google登录窗口的xaml:

<Window x:Class="MyProject.Windows.GoogleLoginWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:wpf="clr-namespace:CefSharp.Wpf;assembly=CefSharp.Wpf"
    xmlns:local="clr-namespace:NP_Browser.Windows"
    mc:Ignorable="d"
    Title="Google Login Window" Height="450" Width="800" Icon="../Images/NPBrowserLogo.ico">
<Window.Resources>
    <BooleanToVisibilityConverter x:Key="btv" />
</Window.Resources>
<Grid>
    <DockPanel Visibility="{Binding State.IsSigned, Converter={StaticResource btv}}">
        <Label Content="{Binding State.Token.Name}" />
    </DockPanel>
    <Grid Visibility="{Binding State.IsNotSigned, Converter={StaticResource btv}}">
        <wpf:ChromiumWebBrowser x:Name="Wb" FontSize="16"/>
    </Grid>
</Grid>
namespace MyProject.Windows
{ 公共部分类GoogleLoginWindows:窗口 { 公共谷歌登录窗口() { 初始化组件(); State=新的OAuthState(); DataContext=this; 最顶端=真; var thread=新线程(HandleRedirect); thread.Start(); }

public OAuthState状态{get;}
私有异步void HandleRedirect()
{
State.Token=null;
var request=OAuthRequest.BuildLoopbackRequest();
var listener=newhttplistener();
listener.Prefixes.Add(request.RedirectUri);
listener.Start();
//注意:添加对System.Windows.Presentation的引用和“使用System.Windows.Threading”以编译此文件
等待调度程序。开始调用(()=>
{
Wb.Address=request.AuthorizationRequestUri;
});
//在这里,我们将等待来自托管webbrowser的重定向
var context=await listener.GetContextAsync();
//浏览器已导航到我们的小型http服务器,请在此处回答任何问题
字符串html=string.Format(“”);
var buffer=Encoding.UTF8.GetBytes(html);
context.Response.ContentLength64=buffer.Length;
var stream=context.Response.OutputStream;
var responseTask=stream.WriteAsync(buffer,0,buffer.Length).ContinueWith((任务)=>
{
stream.Close();
listener.Stop();
});
字符串错误=context.Request.QueryString[“error”];
if(错误!=null)
返回;
字符串状态=context.Request.QueryString[“state”];
if(state!=request.state)
返回;
字符串代码=context.Request.QueryString[“code”];
State.Token=request.ExchangeCodeForAccessToken(代码);
}
}
//状态模型
公共类OAuthState:INotifyPropertyChanged
{
公共事件属性更改事件处理程序属性更改;
专用OAuthToken(uToken);
公共OAuthToken令牌
{
get=>\u令牌;
设置
{
如果(_标记==值)
返回;
_代币=价值;
PropertyChanged?.Invoke(这是新的PropertyChangedEventArgs(nameof(Token));
PropertyChanged?.Invoke(这是新的propertychangedventargs(nameof(IsSigned));
PropertyChanged?.Invoke(这是新的propertychangedventargs(nameof(IsNotSigned));
}
}
public bool IsSigned=>Token!=null&&Token.ExpirationDate>DateTime.Now;
公共布尔未签名=>!未签名;
}
//这是一个示例。填写信息(电子邮件等)可能取决于范围
[数据合同]
公共类OAuthToken
{
[DataMember(Name=“访问令牌”)]
公共字符串AccessToken{get;set;}
[DataMember(Name=“token\u type”)]
公共字符串标记类型{get;set;}
[DataMember(Name=“expires\u in”)]
公共int ExpiresIn{get;set;}
[DataMember(Name=“刷新令牌”)]
公共字符串刷新标记{get;set;}
[数据成员]
公共字符串名称{get;set;}
[数据成员]
公共字符串电子邮件{get;set;}
[数据成员]
公共字符串图片{get;set;}
[数据成员]
公共字符串区域设置{get;set;}
[数据成员]
公共字符串FamilyName{get;set;}
[数据成员]
公共字符串GivenName{get;set;}
[数据成员]
公共字符串Id{get;set;}
[数据成员]
公共字符串配置文件{get;set;}
[数据成员]
公共字符串[]作用域{get;set;}
//不是来自谷歌的回应,但我们存储了这个
公共日期时间过期日期{get;set;}
}
//主要灵感来自
// https://github.com/googlesamples/oauth-apps-for-windows
公开密封类OAuthRequest
{
private const string ClientId=“我的客户端Id”;
private const string ClientSecret=“我的客户机密码”;
私有常量字符串授权端点=”https://accounts.google.com/o/oauth2/v2/auth";
私有常量字符串标记端点=”https://www.googleapis.com/oauth2/v4/token";
私有常量字符串UserInfoEndpoint=”https://www.googleapis.com/oauth2/v3/userinfo";
私有OAuthRequest()
{
}
公共字符串授权请求URI{get;private set;}
公共字符串状态{get;private set;}
公共字符串重定向URI{get;private set;}
公共字符串代码验证程序{get;private set;}
公共字符串[]作用域{get;private set;}
// https://developers.google.com/identity/protocols/OAuth2InstalledApp
公共静态OAuthRequest BuildLoopbackRequest(参数字符串[]范围)
{
var请求=新的OAuthRequest
{
CodeVerifier=RandomDataBase64Url(32),
范围=范围
};
字符串codechalenge=Base64UrlEncodeNoPadding(Sha256(request.CodeVerifier));
常量字符串编解码器挑战方法
    public OAuthState State { get; }

    private async void HandleRedirect()
    {
        State.Token = null;

        var request = OAuthRequest.BuildLoopbackRequest();
        var listener = new HttpListener();
        listener.Prefixes.Add(request.RedirectUri);
        listener.Start();

        // note: add a reference to System.Windows.Presentation and a 'using System.Windows.Threading' for this to compile
        await Dispatcher.BeginInvoke(() =>
        {
            Wb.Address = request.AuthorizationRequestUri;
        });

        // here, we'll wait for redirection from our hosted webbrowser
        var context = await listener.GetContextAsync();

        // browser has navigated to our small http server answer anything here
        string html = string.Format("<html><body></body></html>");
        var buffer = Encoding.UTF8.GetBytes(html);
        context.Response.ContentLength64 = buffer.Length;
        var stream = context.Response.OutputStream;
        var responseTask = stream.WriteAsync(buffer, 0, buffer.Length).ContinueWith((task) =>
        {
            stream.Close();
            listener.Stop();
        });

        string error = context.Request.QueryString["error"];
        if (error != null)
            return;

        string state = context.Request.QueryString["state"];
        if (state != request.State)
            return;

        string code = context.Request.QueryString["code"];
        State.Token = request.ExchangeCodeForAccessToken(code);
    }
}

// state model
public class OAuthState : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private OAuthToken _token;
    public OAuthToken Token
    {
        get => _token;
        set
        {
            if (_token == value)
                return;

            _token = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Token)));
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsSigned)));
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsNotSigned)));
        }
    }

    public bool IsSigned => Token != null && Token.ExpirationDate > DateTime.Now;
    public bool IsNotSigned => !IsSigned;
}

// This is a sample. Fille information (email, etc.) can depend on scopes
[DataContract]
public class OAuthToken
{
    [DataMember(Name = "access_token")]
    public string AccessToken { get; set; }

    [DataMember(Name = "token_type")]
    public string TokenType { get; set; }

    [DataMember(Name = "expires_in")]
    public int ExpiresIn { get; set; }

    [DataMember(Name = "refresh_token")]
    public string RefreshToken { get; set; }

    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public string Email { get; set; }

    [DataMember]
    public string Picture { get; set; }

    [DataMember]
    public string Locale { get; set; }

    [DataMember]
    public string FamilyName { get; set; }

    [DataMember]
    public string GivenName { get; set; }

    [DataMember]
    public string Id { get; set; }

    [DataMember]
    public string Profile { get; set; }

    [DataMember]
    public string[] Scopes { get; set; }

    // not from google's response, but we store this
    public DateTime ExpirationDate { get; set; }
}

// largely inspired from
// https://github.com/googlesamples/oauth-apps-for-windows
public sealed class OAuthRequest
{
    private const string ClientId = "My-Client-Id";
    private const string ClientSecret = "My-Client-Secret";

    private const string AuthorizationEndpoint = "https://accounts.google.com/o/oauth2/v2/auth";
    private const string TokenEndpoint = "https://www.googleapis.com/oauth2/v4/token";
    private const string UserInfoEndpoint = "https://www.googleapis.com/oauth2/v3/userinfo";

    private OAuthRequest()
    {
    }

    public string AuthorizationRequestUri { get; private set; }
    public string State { get; private set; }
    public string RedirectUri { get; private set; }
    public string CodeVerifier { get; private set; }
    public string[] Scopes { get; private set; }

    // https://developers.google.com/identity/protocols/OAuth2InstalledApp
    public static OAuthRequest BuildLoopbackRequest(params string[] scopes)
    {
        var request = new OAuthRequest
        {
            CodeVerifier = RandomDataBase64Url(32),
            Scopes = scopes
        };

        string codeChallenge = Base64UrlEncodeNoPadding(Sha256(request.CodeVerifier));
        const string codeChallengeMethod = "S256";

        string scope = BuildScopes(scopes);

        request.RedirectUri = string.Format("http://{0}:{1}/", IPAddress.Loopback, GetRandomUnusedPort());
        request.State = RandomDataBase64Url(32);
        request.AuthorizationRequestUri = string.Format("{0}?response_type=code&scope=openid%20profile{6}&redirect_uri={1}&client_id={2}&state={3}&code_challenge={4}&code_challenge_method={5}",
            AuthorizationEndpoint,
            Uri.EscapeDataString(request.RedirectUri),
            ClientId,
            request.State,
            codeChallenge,
            codeChallengeMethod,
            scope);

        return request;
    }

    // https://developers.google.com/identity/protocols/OAuth2InstalledApp Step 5: Exchange authorization code for refresh and access tokens
    public OAuthToken ExchangeCodeForAccessToken(string code)
    {
        if (code == null)
            throw new ArgumentNullException(nameof(code));

        string tokenRequestBody = string.Format("code={0}&redirect_uri={1}&client_id={2}&code_verifier={3}&client_secret={4}&scope=&grant_type=authorization_code",
            code,
            Uri.EscapeDataString(RedirectUri),
            ClientId,
            CodeVerifier,
            ClientSecret
            );

        return TokenRequest(tokenRequestBody, Scopes);
    }

    // this is not used in this sample, but can be used to refresh a token from an old one
    // https://developers.google.com/identity/protocols/OAuth2InstalledApp Refreshing an access token
    public OAuthToken Refresh(OAuthToken oldToken)
    {
        if (oldToken == null)
            throw new ArgumentNullException(nameof(oldToken));

        string tokenRequestBody = string.Format("refresh_token={0}&client_id={1}&client_secret={2}&grant_type=refresh_token",
            oldToken.RefreshToken,
            ClientId,
            ClientSecret
            );

        return TokenRequest(tokenRequestBody, oldToken.Scopes);
    }

    private static T Deserialize<T>(string json)
    {
        if (string.IsNullOrWhiteSpace(json))
            return default(T);

        return Deserialize<T>(Encoding.UTF8.GetBytes(json));
    }

    private static T Deserialize<T>(byte[] json)
    {
        if (json == null || json.Length == 0)
            return default(T);

        using (var ms = new MemoryStream(json))
        {
            return Deserialize<T>(ms);
        }
    }

    private static T Deserialize<T>(Stream json)
    {
        if (json == null)
            return default(T);

        var ser = CreateSerializer(typeof(T));
        return (T)ser.ReadObject(json);
    }

    private static DataContractJsonSerializer CreateSerializer(Type type)
    {
        if (type == null)
            throw new ArgumentNullException(nameof(type));

        var settings = new DataContractJsonSerializerSettings
        {
            DateTimeFormat = new DateTimeFormat("yyyy-MM-dd'T'HH:mm:ss.fffK")
        };
        return new DataContractJsonSerializer(type, settings);
    }

    // https://stackoverflow.com/questions/223063/how-can-i-create-an-httplistener-class-on-a-random-port-in-c/
    private static int GetRandomUnusedPort()
    {
        var listener = new TcpListener(IPAddress.Loopback, 0);
        listener.Start();
        var port = ((IPEndPoint)listener.LocalEndpoint).Port;
        listener.Stop();
        return port;
    }

    private static string RandomDataBase64Url(int length)
    {
        using (var rng = new RNGCryptoServiceProvider())
        {
            var bytes = new byte[length];
            rng.GetBytes(bytes);
            return Base64UrlEncodeNoPadding(bytes);
        }
    }

    private static byte[] Sha256(string text)
    {
        using (var sha256 = new SHA256Managed())
        {
            return sha256.ComputeHash(Encoding.ASCII.GetBytes(text));
        }
    }

    private static string Base64UrlEncodeNoPadding(byte[] buffer)
    {
        string b64 = Convert.ToBase64String(buffer);
        // converts base64 to base64url.
        b64 = b64.Replace('+', '-');
        b64 = b64.Replace('/', '_');
        // strips padding.
        b64 = b64.Replace("=", "");
        return b64;
    }

    private static OAuthToken TokenRequest(string tokenRequestBody, string[] scopes)
    {
        var request = (HttpWebRequest)WebRequest.Create(TokenEndpoint);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        byte[] bytes = Encoding.ASCII.GetBytes(tokenRequestBody);
        using (var requestStream = request.GetRequestStream())
        {
            requestStream.Write(bytes, 0, bytes.Length);
        }

        var response = request.GetResponse();
        using (var responseStream = response.GetResponseStream())
        {
            var token = Deserialize<OAuthToken>(responseStream);
            token.ExpirationDate = DateTime.Now + new TimeSpan(0, 0, token.ExpiresIn);
            var user = GetUserInfo(token.AccessToken);
            token.Name = user.Name;
            token.Picture = user.Picture;
            token.Email = user.Email;
            token.Locale = user.Locale;
            token.FamilyName = user.FamilyName;
            token.GivenName = user.GivenName;
            token.Id = user.Id;
            token.Profile = user.Profile;
            token.Scopes = scopes;
            return token;
        }
    }

    private static UserInfo GetUserInfo(string accessToken)
    {
        var request = (HttpWebRequest)WebRequest.Create(UserInfoEndpoint);
        request.Method = "GET";
        request.Headers.Add(string.Format("Authorization: Bearer {0}", accessToken));
        var response = request.GetResponse();
        using (var stream = response.GetResponseStream())
        {
            return Deserialize<UserInfo>(stream);
        }
    }

    private static string BuildScopes(string[] scopes)
    {
        string scope = null;
        if (scopes != null)
        {
            foreach (var sc in scopes)
            {
                scope += "%20" + Uri.EscapeDataString(sc);
            }
        }
        return scope;
    }

    // https://developers.google.com/+/web/api/rest/openidconnect/getOpenIdConnect
    [DataContract]
    private class UserInfo
    {
        [DataMember(Name = "name")]
        public string Name { get; set; }

        [DataMember(Name = "kind")]
        public string Kind { get; set; }

        [DataMember(Name = "email")]
        public string Email { get; set; }

        [DataMember(Name = "picture")]
        public string Picture { get; set; }

        [DataMember(Name = "locale")]
        public string Locale { get; set; }

        [DataMember(Name = "family_name")]
        public string FamilyName { get; set; }

        [DataMember(Name = "given_name")]
        public string GivenName { get; set; }

        [DataMember(Name = "sub")]
        public string Id { get; set; }

        [DataMember(Name = "profile")]
        public string Profile { get; set; }

        [DataMember(Name = "gender")]
        public string Gender { get; set; }
    }
}