针对.net后端服务器验证Google ID [英] validate Google ID against a .net backend server

查看:103
本文介绍了针对.net后端服务器验证Google ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的应用实现Google登录。

Im trying to implement google sign in for my app.

后端服务器将为c#.net...。

The backend server will be c# .net....

有人可以指出我的方向,还是解释一下如何在.Net中进行后端验证...他们提供了Java示例并建议使用Google apis

Can Some point me in the direction, or explain how to do the backend verification in .Net... they have provided java examples and suggest using googles apis

https: //developers.google.com/identity/sign-in/android/backend-auth#using-a-google-api-client-library

推荐答案

有相同的问题。
在服务器端,您需要验证在客户端获得的 id令牌。
因此,首先在客户端,您将通过以下方式获得 id令牌:

Had the same problem. What you need on server side is to verify 'id token' you got on client side. So, first on client side you get the 'id token' via:

function onGoogleSignIn(googleUser)
{
    //Here call ajax and pass googleUser.getAuthResponse().id_token
}

好,现在在服务器端,您可以使用以下功能来验证令牌:

Ok, now on server side you can use the following function in order to verify the token:

public sealed class JWTCertificateUrl
{
    private JWTCertificateUrl(string value) { Value = value; }
    public string Value { get; set; }

    public static JWTCertificateUrl Google { get { return new JWTCertificateUrl("https://www.googleapis.com/oauth2/v1/certs"); } }
}

public sealed class JWTIssuer
{
    private JWTIssuer(string value) { Value = value; }
    public string Value { get; set; }

    public static JWTIssuer None { get { return new JWTIssuer(""); } }
    public static JWTIssuer Google { get { return new JWTIssuer("accounts.google.com"); } }
}

public static class Utils
{
    private const string beginCert = "-----BEGIN CERTIFICATE-----\\n";
    private const string endCert = "\\n-----END CERTIFICATE-----\\n";
    private static byte[][] getCertBytes(JWTCertificateUrl certificate)
    {
        // The request will be made to the authentication server.
        WebRequest request = WebRequest.Create(certificate.Value);

        StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream());

        string responseFromServer = reader.ReadToEnd();

        String[] split = responseFromServer.Split(':');

        // There are two certificates returned from Google
        byte[][] certBytes = new byte[2][];
        int index = 0;
        UTF8Encoding utf8 = new UTF8Encoding();
        for (int i = 0; i < split.Length; i++)
        {
            if (split[i].IndexOf(beginCert) > 0)
            {
                int startSub = split[i].IndexOf(beginCert);
                int endSub = split[i].IndexOf(endCert) + endCert.Length;
                certBytes[index] = utf8.GetBytes(split[i].Substring(startSub, endSub).Replace("\\n", "\n"));
                index++;
            }
        }
        return certBytes;
    }

    public static bool CheckJWTToken(JWTCertificateUrl cert, JWTIssuer tokenIssuer, string appId, string idToken, ref Dictionary<string, string> data)
    {
        if (data == null)
            data = new Dictionary<string, string>();

        if (string.IsNullOrEmpty(idToken))
            return false;

        //JwtSecurityToken token = new JwtSecurityToken(idToken);
        JwtSecurityTokenHandler jsth = new JwtSecurityTokenHandler();

        Byte[][] certBytes = getCertBytes(cert);
        Dictionary<String, X509Certificate2> certificates = new Dictionary<String, X509Certificate2>();
        for (int i = 0; i < certBytes.Length; i++)
        {
            X509Certificate2 certificate = new X509Certificate2(certBytes[i]);
            certificates.Add(certificate.Thumbprint, certificate);
        }

        TokenValidationParameters tvp = new TokenValidationParameters()
        {
            ValidateActor = false, // check the profile ID

            ValidateAudience = true,
            ValidAudience = appId,

            ValidateIssuer = !string.IsNullOrEmpty(tokenIssuer.Value),
            ValidIssuer = tokenIssuer.Value,

            ValidateIssuerSigningKey = true,
            RequireSignedTokens = true,
            CertificateValidator = X509CertificateValidator.None,
            IssuerSigningKeyResolver = (s, securityToken, identifier, parameters) =>
            {
                return identifier.Select(x =>
                {
                    if (certificates.ContainsKey(x.Id.ToUpper()))
                    {
                        return new X509SecurityKey(certificates[x.Id.ToUpper()]);
                    }
                    return null;
                }).First(x => x != null);
            },
            ValidateLifetime = true,
            RequireExpirationTime = true,
            ClockSkew = TimeSpan.FromSeconds(300) //5 minutes
        };

        bool res = false;
        try
        {
            // Validate using the provider
            SecurityToken validatedToken;
            ClaimsPrincipal cp = jsth.ValidateToken(idToken, tvp, out validatedToken);
            if (cp != null)
            {
                foreach (var claim in cp.Claims)
                {
                    var name = claim.Type;
                    //Delete the URL part just for convenient
                    if (name.StartsWith("http"))
                        name = name.Remove(0, name.LastIndexOf('/') + 1);
                    data.Add(name, claim.Value);
                }
                res = true;
            }

        }
        catch (Exception ex)
        {
        }

        return res;
    }
}

函数调用:

Dictionary<string, string> data = null;
if (Utils.CheckJWTToken(JWTCertificateUrl.Google, JWTIssuer.Google, "[your google app id].apps.googleusercontent.com", idToken, ref data))
{
  //Here you can take user data for further process
  //data["emailaddress"], data["givenname"], data["surname"]
}

要编译代码,您需要从此处安装.NET JWT库: https://www.nuget.org/packages/System.IdentityModel.Tokens.Jwt/

In order to compile the code you'll need to install .NET JWT library from here: https://www.nuget.org/packages/System.IdentityModel.Tokens.Jwt/

上面的代码是在这里获取的: https://github.com / googleplus / gplus-verifytoken-csharp

The code above was taken here: https://github.com/googleplus/gplus-verifytoken-csharp

这篇关于针对.net后端服务器验证Google ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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