forked from israelgoldstein/sdk-core-dotnet
/
OAuthTokenCredential.cs
196 lines (176 loc) · 6.99 KB
/
OAuthTokenCredential.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
// NuGet Install
// install PayPalCoreSDK -excludeversion -outputDirectory .\Packages
// 2.0
using log4net;
using PayPal.Exception;
using PayPal.Manager;
// install Newtonsoft.Json -excludeversion -outputDirectory .\Packages
// net35
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace PayPal
{
public class OAuthTokenCredential
{
private const string OAUTHTOKENPATH = "/v1/oauth2/token";
/// <summary>
/// Client ID for OAuth
/// </summary>
private String clientID;
/// <summary>
/// Client Secret for OAuth
/// </summary>
private string clientSecret;
/// <summary>
/// Access Token that is generated
/// </summary>
private string accessToken;
/// <summary>
/// Application ID returned by OAuth servers
/// </summary>
private string appID;
/// <summary>
/// Seconds for with access token is valid
/// </summary>
private int secondsToExpire;
/// <summary>
/// Last time when access token was generated
/// </summary>
private long timeInMilliseconds;
/// <summary>
/// Dynamic configuration map
/// </summary>
private Dictionary<string, string> config;
/// <summary>
/// Logs output statements, errors, debug info to a text file
/// </summary>
private static readonly ILog logger = LogManagerWrapper.GetLogger(typeof(OAuthTokenCredential));
/// <summary>
/// Client ID and Secret for the OAuth
/// </summary>
/// <param name="clientID"></param>
/// <param name="clientSecret"></param>
public OAuthTokenCredential(String clientID, String clientSecret)
{
this.clientID = clientID;
this.clientSecret = clientSecret;
this.config = ConfigManager.getConfigWithDefaults(ConfigManager.Instance.GetProperties());
}
/// <summary>
/// Client ID and Secret for the OAuth
/// </summary>
/// <param name="clientID"></param>
/// <param name="clientSecret"></param>
public OAuthTokenCredential(String clientID, String clientSecret, Dictionary<string, string> config)
{
this.clientID = clientID;
this.clientSecret = clientSecret;
if (config != null)
{
ConfigManager.getConfigWithDefaults(config);
}
else
{
this.config = ConfigManager.getConfigWithDefaults(ConfigManager.Instance.GetProperties());
}
}
public string GetAccessToken()
{
// If Access Token is not Null and time has lapsed
if (accessToken != null)
{
// If the token has not expired
// Set TTL as expiresTime - 60000
// If expired set accesstoken == null
if (((DateTime.Now.Millisecond - timeInMilliseconds) / 1000) > (secondsToExpire - 120))
{
// regenerate token
accessToken = null;
}
}
// If accessToken is Null, Compute it
if (accessToken == null)
{
// Write Logic for passing in Detail to Identity Api Serv and
// computing the token
// Set the Value inside the accessToken and result
accessToken = GenerateAccessToken();
}
return accessToken;
}
private string GenerateAccessToken()
{
string generatedToken = null;
string base64ClientID = GenerateBase64String(clientID + ":" + clientSecret);
generatedToken = GenerateOAuthToken(base64ClientID);
return generatedToken;
}
private string GenerateBase64String(string clientCredential)
{
try
{
byte[] bytes = Encoding.UTF8.GetBytes(clientCredential);
string base64ClientID = Convert.ToBase64String(bytes);
return base64ClientID;
}
catch (ArgumentOutOfRangeException ex)
{
throw new PayPalException(ex.Message, ex);
}
catch (ArgumentException ex)
{
throw new PayPalException(ex.Message, ex);
}
catch (NotSupportedException ex)
{
throw new PayPalException(ex.Message, ex);
}
catch (System.Exception ex)
{
throw new PayPalException(ex.Message, ex);
}
}
private string GenerateOAuthToken(string base64ClientID)
{
string response = null;
Uri uniformResourceIdentifier = null;
Uri baseUri = null;
if (config.ContainsKey(BaseConstants.OAUTH_ENDPOINT))
{
baseUri = new Uri(config[BaseConstants.OAUTH_ENDPOINT]);
}
else if (config.ContainsKey(BaseConstants.END_POINT_CONFIG))
{
baseUri = new Uri(config[BaseConstants.END_POINT_CONFIG]);
}
bool success = Uri.TryCreate(baseUri, OAUTHTOKENPATH, out uniformResourceIdentifier);
ConnectionManager connManager = ConnectionManager.Instance;
HttpWebRequest httpRequest = connManager.GetConnection(ConfigManager.Instance.GetProperties(), uniformResourceIdentifier.AbsoluteUri);
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("Authorization", "Basic " + base64ClientID);
string postRequest = "grant_type=client_credentials";
httpRequest.Method = "POST";
httpRequest.Accept = "*/*";
httpRequest.UserAgent = RESTConfiguration.FormUserAgentHeader();
foreach (KeyValuePair<string, string> header in headers)
{
httpRequest.Headers.Add(header.Key, header.Value);
}
HttpConnection httpConnection = new HttpConnection(config);
response = httpConnection.Execute(postRequest, httpRequest);
JObject deserializedObject = (JObject)JsonConvert.DeserializeObject(response);
string generatedToken = (string)deserializedObject["token_type"] + " " + (string)deserializedObject["access_token"];
appID = (string)deserializedObject["app_id"];
secondsToExpire = (int)deserializedObject["expires_in"];
timeInMilliseconds = DateTime.Now.Millisecond;
return generatedToken;
}
}
}