예제 #1
0
        public async Task GetToken_GetTokenCorrectly(string id, string secret, string expectedBase64)
        {
            //prepare
            var obt = createTestObject();

            var httpClientMock = new Mock <IHttpClientWrapper>();

            clientFactoryMock.Setup(m => m.CreateClient()).Returns(httpClientMock.Object);

            var resp = new HttpResponseMessage(System.Net.HttpStatusCode.OK);

            resp.Content = new StringContent(jsonToken, System.Text.Encoding.UTF8, "application/json");
            httpClientMock.Setup(m => m.SendAsync(It.IsAny <HttpRequestMessage>())).ReturnsAsync(resp);

            // execute
            var token = await obt.GetToken(id, secret);

            //Verify
            var expectedRequest = new HttpRequestMessage(HttpMethod.Post, "https://accounts.spotify.com/api/token");

            expectedRequest.Headers.Add("Authorization", $"Basic {expectedBase64}");
            // expectedRequest.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            var nvc = new List <KeyValuePair <string, string> >();

            nvc.Add(new KeyValuePair <string, string>("grant_type", "client_credentials"));
            expectedRequest.Content = new FormUrlEncodedContent(nvc);
            httpClientMock.Verify(m => m.SendAsync(expectedRequest));

            token.Should().BeEquivalentTo(AuthorizationToken.FromJson(jsonToken));

            base64Mock.Verify(m => m.Base64Encode($"{id}:{secret}"));
        }
예제 #2
0
        public async Task <AuthorizationToken> GetToken(string clientId, string clientSecret)
        {
            var request = new HttpRequestMessage(HttpMethod.Post, "https://accounts.spotify.com/api/token");
            var author  = Base64.Base64Encode($"{clientId}:{clientSecret}");

            request.Headers.Add("Authorization", $"Basic {author}");
            var nvc = new List <KeyValuePair <string, string> >();

            nvc.Add(new KeyValuePair <string, string>("grant_type", "client_credentials"));
            request.Content = new FormUrlEncodedContent(nvc);

            var client = ClientFactory.CreateClient();

            var response = await client.SendAsync(request);

            if (response.IsSuccessStatusCode)
            {
                var json = await response.Content
                           .ReadAsStringAsync();

                return(AuthorizationToken.FromJson(json));
            }
            else if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
            {
                throw new SpotifyTokenExpiredException();
            }
            else
            {
                throw new ApplicationException(response.StatusCode.ToString());
            }
        }