-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathWnsTokenAccessManager.cs
More file actions
79 lines (66 loc) · 2.5 KB
/
WnsTokenAccessManager.cs
File metadata and controls
79 lines (66 loc) · 2.5 KB
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
using System;
using System.Threading.Tasks;
using System.Net.Http;
using PushSharp.Core;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
namespace PushSharp.Windows
{
public class WnsAccessTokenManager
{
Task renewAccessTokenTask = null;
string accessToken = null;
HttpClient http;
public WnsAccessTokenManager (WnsConfiguration configuration)
{
http = new HttpClient ();
Configuration = configuration;
}
public WnsConfiguration Configuration { get; private set; }
public async Task<string> GetAccessToken ()
{
if (accessToken == null) {
if (renewAccessTokenTask == null) {
Log.Info ("Renewing Access Token");
renewAccessTokenTask = RenewAccessToken ();
await renewAccessTokenTask;
renewAccessTokenTask = null;
} else {
Log.Info ("Waiting for access token");
await renewAccessTokenTask;
}
}
return accessToken;
}
public void InvalidateAccessToken (string currentAccessToken)
{
if (accessToken == currentAccessToken)
accessToken = null;
}
async Task RenewAccessToken ()
{
var p = new Dictionary<string, string> {
{ "grant_type", "client_credentials" },
{ "client_id", Configuration.PackageSecurityIdentifier },
{ "client_secret", Configuration.ClientSecret },
{ "scope", "notify.windows.com" }
};
var result = await http.PostAsync ("https://login.live.com/accesstoken.srf", new FormUrlEncodedContent (p));
var data = await result.Content.ReadAsStringAsync ();
var token = string.Empty;
var tokenType = string.Empty;
try {
var json = JObject.Parse (data);
token = json.Value<string> ("access_token");
tokenType = json.Value<string> ("token_type");
} catch {
}
if (!string.IsNullOrEmpty (token) && !string.IsNullOrEmpty (tokenType)) {
accessToken = token;
} else {
accessToken = null;
throw new UnauthorizedAccessException ("Could not retrieve access token for the supplied Package Security Identifier (SID) and client secret");
}
}
}
}