0
votes

Basically, I have a button that executes the following code

 $(document).ready(function (){
        $("#login-button").click(function () {
            var parameters = "@Model.parameters";
            parameters = parameters.replace(/&/g, "&");
            window.location.href = "https://accounts.spotify.com/authorize/".concat(parameters);
        })
    })

and it successfully gives an access token in https://localhost:44382/Callback#access_token=TOKEN&token_type=Bearer&expires_in=3600&state=586917 .

But I can't figure out how to pull out the access token from the URL so I can use it as a variable. I tried

 public IActionResult OnGet()
    {
        @TempData["access_token"] = (string)HttpContext.Request.Query["access_token"];

        return Page();
    }

on the Callback.cshtml.cs file, but it seems to return null(the whole Query contains no elements), because as I suspect, it executes prior to the URL actually containing the token. And also, I tried putting in the following code to Callback.cshtml, but it runs into the same issue. In addition to the $window.location.href not actually redirecting.

 $(document).load(function () {
         @TempData["access_token"] = @HttpContext.Request.Query["access_token"];
            $window.location.href = "/Overview";

    })
1

1 Answers

0
votes

https://developer.spotify.com/documentation/general/guides/authorization-guide/

Try adding a variable and declaring So you may need to add an $.ajax call, before the window.location.href. .. generic example for brevity (not tested)


         $(document).ready(function (){
            var url = "https://accounts.spotify.com/authorize/";
            var parameters = "@Model.parameters";
            $("#login-button").click(function () {
            $.ajax({
                url: 'https://api.spotify.com/v1/browse/new-releases',
                type: 'GET',
                headers: {
                    'Authorization' : 'Bearer ' + accessToken
                },
            success: function(response) {
            parameters = parameters.replace(/&/g, "&");
            window.location.href = url.concat(parameters);
                }
            });
          })
       })

Without setting up a test application and diving deep into this, you could also build up your request via c#. You can still have the ajax call, that simply calls the action method in your controller, but the controll can build up the request. Example below....


public IList<SearchResult> GetSpotifyAuthorization(string parameters)
    {
        IList<SearchResult> searchResults = new List<SearchResult>();
        ParseElementViewModel parseElement = new ParseElementViewModel();

        parameters = Regex.Replace(parameters, "[^A-Za-z0-9]", ""); // just an example
        string url = $"https://accounts.spotify.com/authorize/{parameters}? format=json";
        HttpClient client = new HttpClient();

        client.BaseAddress = new Uri(url);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        try
        {
            var request = client.GetAsync(url).Result;
            if (request.IsSuccessStatusCode)
            {
                var res = request.Content.ReadAsStringAsync().Result;
                JObject search = JObject.Parse(res);
                IList<JToken> results = search["Results"].Children().ToList();

                foreach (JToken result in results)
                {
                    SearchResult jsonResults = JsonConvert.DeserializeObject<SearchResult>(result.ToString());
                    searchResults.Add(jsonResults);
                }

            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            return null;
        }
        return searchResults;
    }