首页 > 其他分享 >对接苹果 https://appleid.apple.com/auth/token

对接苹果 https://appleid.apple.com/auth/token

时间:2022-12-08 17:48:52浏览次数:40  
标签:return apple request System auth token new using string

c#  对接苹果 https://appleid.apple.com/auth/token

using Microsoft.IdentityModel.Tokens;
using MobaFlyx.Utils;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

public partial class AppleLogout : System.Web.UI.Page
{
    private static string teamId = "GT49US5M95";
    private static string keyId = "HGVGH986J4";
    private static string client_id = "com.faloogame.flmoba";
    private static string requestUrl = "https://appleid.apple.com";
    protected void Page_Load(object sender, EventArgs e)
    {
        var secret = CreateSecret();        
        Response.Write(getToken(CreateSecret(), "c98f810b97ad24ceb8bf9abf413065b0f.0.rzyz.AjQFrVwe6WC9SAY59qKdOA"));
    }


    #region 文案一

    public string getToken(string client_secret, string code)
    {
        string url = "https://appleid.apple.com/auth/token";
        
        List<string> list = new List<string>();
        list.Add("client_id=" + client_id);
        list.Add("client_secret=" + client_secret);
        list.Add("code=" + code);
        list.Add("grant_type=authorization_code");
        list.Add("refresh_token=");
        list.Add("redirect_uri=");

        //return HttpClientUtil.Post(url, string.Join("&", list), "application/x-www-form-urlencoded", 3000, null, null, null, null, null);
        return Post(url, string.Join("&", list));
    }

    public String Post(String url, String postData)
    {
        String result = String.Empty;
        if (string.IsNullOrEmpty(url))
        {
            throw new ArgumentNullException("url");
        }

        HttpWebRequest request = null;
        //如果是发送HTTPS请求  
        if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
        {
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            request = WebRequest.Create(url) as HttpWebRequest;
            request.ProtocolVersion = HttpVersion.Version10;
        }
        else
        {
            request = WebRequest.Create(url) as HttpWebRequest;
        }
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.Timeout = 30000;

        postData = postData == null ? String.Empty : postData;
        byte[] byteArray = Encoding.UTF8.GetBytes(postData); //转化
        request.ContentLength = byteArray.Length;
        using (Stream stream = request.GetRequestStream())
        {
            stream.Write(byteArray, 0, byteArray.Length);
        }
        HttpWebResponse response = null;
        try
        {
            response = (HttpWebResponse)request.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            result = sr.ReadToEnd();
            sr.Close();
            response.Close();
        }
        catch (WebException ex)
        {
            if (response != null)
            {
                response.Dispose();
                response.Close();
            }
            return GetResponseAsString((System.Net.HttpWebResponse)ex.Response, Encoding.UTF8);//这样获取web服务器返回数据
        }

        return result;
    }

    /// <summary>
    /// 验证证书
    /// </summary>
    private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
    {
        if (errors == SslPolicyErrors.None)
            return true;
        return false;
    }

    private static string GetResponseAsString(HttpWebResponse res, Encoding encoding)
    {
        try
        {
            StreamReader sr = new StreamReader(res.GetResponseStream(), encoding);
            return sr.ReadToEnd();
        }
        catch (Exception ex)
        {
            return "";
        }
    }


    private string CreateSecret()
    {
        var handler = new JwtSecurityTokenHandler();
        var subject = new Claim("sub", client_id);//需要IOS提供 
        var tokenDescriptor = new SecurityTokenDescriptor()
        {

            Audience = "https://appleid.apple.com",//固定值
            Issuer = teamId,//team ID,需要IOS提供                           
            IssuedAt = DateTime.UtcNow,
            NotBefore = DateTime.UtcNow,
            Expires = DateTime.UtcNow.AddDays(180),
            Subject = new ClaimsIdentity(new[] { subject }),
        };

        var algorithm = new ECDsaCng(GetPrivateKey());
        {
            tokenDescriptor.SigningCredentials = CreateSigningCredentials(keyId, algorithm);//p8私钥文件得Key,需要IOS提供
            var clientSecret = handler.CreateEncodedJwt(tokenDescriptor);
            return clientSecret;
        }
    }
    /// <summary>
    /// 获取P8
    /// </summary>
    /// <returns></returns>
    private CngKey GetPrivateKey()
    {
        const string privateKey = "MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQg4ai6VUnHRHhDRL/DyJN5UfHjO8KyHz+naWJlaNhn/oigCgYIKoZIzj0DAQehRANCAASYqNHbn3l7sDqn1kFk09/nQPR5qG9umc0m0Jkn/sNoGoBsF0RJ5hhFuGirjLbUnJ3FuKp/8zfzTN9Nzmf7sqAY"; // contents of .p8 file
        var cngKey = CngKey.Import(Convert.FromBase64String(privateKey), CngKeyBlobFormat.Pkcs8PrivateBlob);
        return cngKey;
    }

    private static SigningCredentials CreateSigningCredentials(string keyId, ECDsa algorithm)
    {
        var key = new ECDsaSecurityKey(algorithm) { KeyId = keyId };
        return new SigningCredentials(key, SecurityAlgorithms.EcdsaSha256);
    }

    #endregion





}

 

标签:return,apple,request,System,auth,token,new,using,string
From: https://www.cnblogs.com/sjns/p/16966783.html

相关文章

  • Salesforce 中 Security Token 的获取方法
    进入到你的人头像,点击设定选择ResetMySecurityToken点击按钮ResetSecurityToken收到邮件,在邮件中有SecurityToken,拷贝出来,贴到你需要的地方。   ......
  • OAuth2.0实战(三)用户信息加载
    SpringSecurity内置了三种用户存储方式:1、基于内存2、基于数据库查询语句3、自定义UserDetailsService服务来获取这里的用户存储指的是,从哪里获取用户的信息1、基于内......
  • session,cookie,token详解
    session,cookie,token详解1.session1.1session的作用是什么session的作用是用于保存每个用户的专用信息;当用户访问时,服务器都会为每个用户分配唯一的SessionID,而且当......
  • AuthenticationException: The remote certificate is invalid because of errors in
    AuthenticationException:Theremotecertificateisinvalidbecauseoferrorsinthecertificatechain:UntrustedRoot回答1Pleasecheckbelowpoints:Install......
  • C——error: expected ‘:‘, ‘,‘, ‘;‘, ‘}‘ or ‘__attribute__‘ before ‘=‘
    一、原因结构体中包含变量的初始化。二、报错代码structGaitParams{floatstance_height=0.18;//Desiredheightofbodyfromgroundduringwalking(m)flo......
  • Nestjs-Authentication 文档翻译
    Authentication认证是大多数应用程序中非常重要的部分.有很多不同的方法和策略去处理认证,根据不同的要求决定。本章节展示了几种不同方式,这些方式通常是能够适用于......
  • 使用express-jwt解析token时req.user=undefind
    使用express-jwt解析token时req.user=undefind,原因:在路由文件里使用express的实例app来use express-jwt中间件了,这样做是不规范的解决方法:使用router实例来use  expr......
  • 解决添加authorization 请求头后跨域问题
    在做身份认证的时候前端请求头上增加authorization属性后报以下错误: AccesstoXMLHttpRequestat'http://127.0.0.1:500/api/login'fromorigin'http://127.0.0.1:......
  • 自动获取 MFA token
    在mac下,下载 oath-toolkit工具执行brewinstalloath-toolkit 使用虾米啊命令获取aliassmCode="echo`oathtool--totp-bSECKEY`|pbcopy"  参考博客: ......
  • node js的token生成与验证之“jsonwebtoken“
    ❤️在繁华中自律,在落魄中自愈❤️目录​​一、生成token​​​​二、验证token​​​​三、完整的jwt.js代码​​​​四、配合express使用token验证​​​​五、/api/login接......