|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Net; |
| 4 | +using System.Text; |
| 5 | +using System.Threading.Tasks; |
| 6 | +using SpotifyAPI.Web.Enums; |
| 7 | +using Unosquare.Labs.EmbedIO; |
| 8 | +using Unosquare.Labs.EmbedIO.Constants; |
| 9 | +using Unosquare.Labs.EmbedIO.Modules; |
| 10 | +using SpotifyAPI.Web.Models; |
| 11 | +using Newtonsoft.Json; |
| 12 | +#if NETSTANDARD2_0 |
| 13 | +using System.Net.Http; |
| 14 | +#endif |
| 15 | +#if NET46 |
| 16 | +using System.Net.Http; |
| 17 | +using HttpListenerContext = Unosquare.Net.HttpListenerContext; |
| 18 | +#endif |
| 19 | + |
| 20 | +namespace SpotifyAPI.Web.Auth |
| 21 | +{ |
| 22 | + /// <summary> |
| 23 | + /// <para> |
| 24 | + /// A version of <see cref="AuthorizationCodeAuth"/> that does not store your client secret, client ID or redirect URI, enforcing a secure authorization flow. Requires an exchange server that will return the authorization code to its callback server via GET request. |
| 25 | + /// </para> |
| 26 | + /// <para> |
| 27 | + /// It's recommended that you use <see cref="TokenSwapWebAPIFactory"/> if you would like to use the TokenSwap method. |
| 28 | + /// </para> |
| 29 | + /// </summary> |
| 30 | + public class TokenSwapAuth : SpotifyAuthServer<AuthorizationCode> |
| 31 | + { |
| 32 | + string exchangeServerUri; |
| 33 | + |
| 34 | + /// <summary> |
| 35 | + /// The HTML to respond with when the callback server (serverUri) is reached. The default value will close the window on arrival. |
| 36 | + /// </summary> |
| 37 | + public string HtmlResponse { get; set; } = "<script>window.close();</script>"; |
| 38 | + /// <summary> |
| 39 | + /// If true, will time how long it takes for access to expire. On expiry, the <see cref="OnAccessTokenExpired"/> event fires. |
| 40 | + /// </summary> |
| 41 | + public bool TimeAccessExpiry { get; set; } |
| 42 | + |
| 43 | + /// <param name="exchangeServerUri">The URI to an exchange server that will perform the key exchange.</param> |
| 44 | + /// <param name="serverUri">The URI to host the server at that your exchange server should return the authorization code to by GET request. (e.g. http://localhost:4002)</param> |
| 45 | + /// <param name="scope"></param> |
| 46 | + /// <param name="state">Stating none will randomly generate a state parameter.</param> |
| 47 | + /// <param name="htmlResponse">The HTML to respond with when the callback server (serverUri) is reached. The default value will close the window on arrival.</param> |
| 48 | + public TokenSwapAuth(string exchangeServerUri, string serverUri, Scope scope = Scope.None, string state = "", string htmlResponse = "") : base("code", "", "", serverUri, scope, state) |
| 49 | + { |
| 50 | + if (!string.IsNullOrEmpty(htmlResponse)) |
| 51 | + { |
| 52 | + HtmlResponse = htmlResponse; |
| 53 | + } |
| 54 | + |
| 55 | + this.exchangeServerUri = exchangeServerUri; |
| 56 | + } |
| 57 | + |
| 58 | + protected override void AdaptWebServer(WebServer webServer) |
| 59 | + { |
| 60 | + webServer.Module<WebApiModule>().RegisterController<TokenSwapAuthController>(); |
| 61 | + } |
| 62 | + |
| 63 | + public override string GetUri() |
| 64 | + { |
| 65 | + StringBuilder builder = new StringBuilder(exchangeServerUri); |
| 66 | + builder.Append("?"); |
| 67 | + builder.Append("response_type=code"); |
| 68 | + builder.Append("&state=" + State); |
| 69 | + builder.Append("&scope=" + Scope.GetStringAttribute(" ")); |
| 70 | + builder.Append("&show_dialog=" + ShowDialog); |
| 71 | + return Uri.EscapeUriString(builder.ToString()); |
| 72 | + } |
| 73 | + |
| 74 | + static readonly HttpClient httpClient = new HttpClient(); |
| 75 | + |
| 76 | + /// <summary> |
| 77 | + /// The maximum amount of times to retry getting a token. |
| 78 | + /// <para/> |
| 79 | + /// A token get is attempted every time you <see cref="RefreshAuthAsync(string)"/> and <see cref="ExchangeCodeAsync(string)"/>. |
| 80 | + /// </summary> |
| 81 | + public int MaxGetTokenRetries { get; set; } = 10; |
| 82 | + |
| 83 | + /// <summary> |
| 84 | + /// Creates a HTTP request to obtain a token object.<para/> |
| 85 | + /// Parameter grantType can only be "refresh_token" or "authorization_code". authorizationCode and refreshToken are not mandatory, but at least one must be provided for your desired grant_type request otherwise an invalid response will be given and an exception is likely to be thrown. |
| 86 | + /// <para> |
| 87 | + /// Will re-attempt on error, on null or on no access token <see cref="MaxGetTokenRetries"/> times before finally returning null. |
| 88 | + /// </para> |
| 89 | + /// </summary> |
| 90 | + /// <param name="grantType">Can only be "refresh_token" or "authorization_code".</param> |
| 91 | + /// <param name="authorizationCode">This needs to be defined if "grantType" is "authorization_code".</param> |
| 92 | + /// <param name="refreshToken">This needs to be defined if "grantType" is "refresh_token".</param> |
| 93 | + /// <param name="currentRetries">Does not need to be defined. Used internally for retry attempt recursion.</param> |
| 94 | + /// <returns>Attempts to return a full <see cref="Token"/>, but after retry attempts, may return a <see cref="Token"/> with no <see cref="Token.AccessToken"/>, or null.</returns> |
| 95 | + async Task<Token> GetToken(string grantType, string authorizationCode = "", string refreshToken = "", int currentRetries = 0) |
| 96 | + { |
| 97 | + var content = new FormUrlEncodedContent(new Dictionary<string, string> |
| 98 | + { |
| 99 | + { "grant_type", grantType }, |
| 100 | + { "code", authorizationCode }, |
| 101 | + { "refresh_token", refreshToken } |
| 102 | + }); |
| 103 | + |
| 104 | + try |
| 105 | + { |
| 106 | + var siteResponse = await httpClient.PostAsync(exchangeServerUri, content); |
| 107 | + Token token = JsonConvert.DeserializeObject<Token>(await siteResponse.Content.ReadAsStringAsync()); |
| 108 | + // Don't need to check if it was null - if it is, it will resort to the catch block. |
| 109 | + if (!token.HasError() && !string.IsNullOrEmpty(token.AccessToken)) |
| 110 | + { |
| 111 | + return token; |
| 112 | + } |
| 113 | + } |
| 114 | + catch { } |
| 115 | + |
| 116 | + if (currentRetries >= MaxGetTokenRetries) |
| 117 | + { |
| 118 | + return null; |
| 119 | + } |
| 120 | + else |
| 121 | + { |
| 122 | + currentRetries++; |
| 123 | + // The reason I chose to implement the retries system this way is because a static or instance |
| 124 | + // variable keeping track would inhibit parallelism i.e. using this function on multiple threads/tasks. |
| 125 | + // It's not clear why someone would like to do that, but it's better to cater for all kinds of uses. |
| 126 | + return await GetToken(grantType, authorizationCode, refreshToken, currentRetries); |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + System.Timers.Timer accessTokenExpireTimer; |
| 131 | + /// <summary> |
| 132 | + /// When Spotify authorization has expired. Will only trigger if <see cref="TimeAccessExpiry"/> is true. |
| 133 | + /// </summary> |
| 134 | + public event EventHandler OnAccessTokenExpired; |
| 135 | + |
| 136 | + /// <summary> |
| 137 | + /// If <see cref="TimeAccessExpiry"/> is true, sets a timer for how long access will take to expire. |
| 138 | + /// </summary> |
| 139 | + /// <param name="token"></param> |
| 140 | + void SetAccessExpireTimer(Token token) |
| 141 | + { |
| 142 | + if (!TimeAccessExpiry) return; |
| 143 | + |
| 144 | + if (accessTokenExpireTimer != null) |
| 145 | + { |
| 146 | + accessTokenExpireTimer.Stop(); |
| 147 | + accessTokenExpireTimer.Dispose(); |
| 148 | + } |
| 149 | + |
| 150 | + accessTokenExpireTimer = new System.Timers.Timer |
| 151 | + { |
| 152 | + Enabled = true, |
| 153 | + Interval = token.ExpiresIn * 1000, |
| 154 | + AutoReset = false |
| 155 | + }; |
| 156 | + accessTokenExpireTimer.Elapsed += (sender, e) => OnAccessTokenExpired?.Invoke(this, EventArgs.Empty); |
| 157 | + } |
| 158 | + |
| 159 | + /// <summary> |
| 160 | + /// Uses the authorization code to silently (doesn't open a browser) obtain both an access token and refresh token, where the refresh token would be required for you to use <see cref="RefreshAuthAsync(string)"/>. |
| 161 | + /// </summary> |
| 162 | + /// <param name="authorizationCode"></param> |
| 163 | + /// <returns></returns> |
| 164 | + public async Task<Token> ExchangeCodeAsync(string authorizationCode) |
| 165 | + { |
| 166 | + Token token = await GetToken("authorization_code", authorizationCode: authorizationCode); |
| 167 | + if (token != null && !token.HasError() && !string.IsNullOrEmpty(token.AccessToken)) |
| 168 | + { |
| 169 | + SetAccessExpireTimer(token); |
| 170 | + } |
| 171 | + return token; |
| 172 | + } |
| 173 | + |
| 174 | + /// <summary> |
| 175 | + /// Uses the refresh token to silently (doesn't open a browser) obtain a fresh access token, no refresh token is given however (as it does not change). |
| 176 | + /// </summary> |
| 177 | + /// <param name="refreshToken"></param> |
| 178 | + /// <returns></returns> |
| 179 | + public async Task<Token> RefreshAuthAsync(string refreshToken) |
| 180 | + { |
| 181 | + Token token = await GetToken("refresh_token", refreshToken: refreshToken); |
| 182 | + if (token != null && !token.HasError() && !string.IsNullOrEmpty(token.AccessToken)) |
| 183 | + { |
| 184 | + SetAccessExpireTimer(token); |
| 185 | + } |
| 186 | + return token; |
| 187 | + } |
| 188 | + } |
| 189 | + |
| 190 | + internal class TokenSwapAuthController : WebApiController |
| 191 | + { |
| 192 | + public TokenSwapAuthController(IHttpContext context) : base(context) |
| 193 | + { |
| 194 | + } |
| 195 | + |
| 196 | + [WebApiHandler(HttpVerbs.Get, "/auth")] |
| 197 | + public Task<bool> GetAuth() |
| 198 | + { |
| 199 | + string state = Request.QueryString["state"]; |
| 200 | + SpotifyAuthServer<AuthorizationCode> auth = TokenSwapAuth.GetByState(state); |
| 201 | + |
| 202 | + string code = null; |
| 203 | + string error = Request.QueryString["error"]; |
| 204 | + if (error == null) |
| 205 | + { |
| 206 | + code = Request.QueryString["code"]; |
| 207 | + } |
| 208 | + |
| 209 | + Task.Factory.StartNew(() => auth?.TriggerAuth(new AuthorizationCode |
| 210 | + { |
| 211 | + Code = code, |
| 212 | + Error = error |
| 213 | + })); |
| 214 | + return this.StringResponseAsync(((TokenSwapAuth)auth).HtmlResponse); |
| 215 | + } |
| 216 | + } |
| 217 | +} |
0 commit comments