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