Golang. How to automatically authorize my app to access spotify APIs?

Viewed 364

I've registered on Spotify my app and I obtained my credentials. I'm using Spotify web api through zmb3/spotify Go wrapper.

const redirectURI = "http://localhost:8080/auth_callback" //Already registered
const CLIENT_ID = "myId"
const CLIENT_SECRET = "mySecret"
const STATE = "myState"

I have a local server (written in Golang) listening for requests on some routes. When I define routes, I create the Spotify Authenticator with desired scopes and I obtain the url. If I print the authorize url to stdout and I click it (or also with copy and paste) redirectURI is correctly called! Here is the code...

var auth  spotify.Authenticator
var token *oauth2.Token
var client spotify.Client
var authorize_url string

func main(){
    fmt.Println("[MAIN] Starting Server")

    auth  = spotify.NewAuthenticator(redirectURI, spotify.ScopeUserReadPrivate, spotify.ScopeUserTopRead)
    auth.SetAuthInfo(CLIENT_ID, CLIENT_SECRET)
    authorize_url = auth.AuthURL(STATE)

    var wg sync.WaitGroup
    router.HandleFunc("/authorize_spotify", authHandler)
    router.HandleFunc("/auth_callback", completeAuth)

    http.Handle("/", router)

    wg.Add(1)
    go start(&wg, 0)
    defer wg.Wait()

    fmt.Println("[MAIN] Running Server... " + url)
}

//SPOTIFY API MANAGEMENT

func completeAuth(w http.ResponseWriter, r *http.Request) {
    fmt.Println("Authentication Redirect Received")
    token, err := auth.Token(STATE, r)
    if err != nil {
        http.Error(w, "Couldn't get token", http.StatusForbidden)
        log.Fatal(err)
    }
    if st := r.FormValue("state"); st != STATE {
        http.NotFound(w, r)
        log.Fatalf("State mismatch: %s != %s\n", st, STATE)
    }
    // use the token to get an authenticated client

    println(token)
    client = auth.NewClient(token)
}

Now I want to make /authorize_spotify automatically call the obtained url. I wrote these two lines.

func authHandler(w http.ResponseWriter, r *http.Request){
    fmt.Println("[AUTH - HANDLER]")
    http.Redirect(w, r, authorize_url, 302)
}

However, when I contact localhost:8080/authorize_spotify authHandler is NEVER Called (no output on stdout, despite the fmt.Println(...)). Misteriously, I'm redirected to the redirectURI at the same way, but it fails.

Seeing network http exchanges I noted that the authorize_url that I printed is a bit different from the authorize request misteriously sent (in the latter the user-top-read scope is missing), that confirms that the authHandler is not called.

How can I achieve my token calling authorize_url from code? Thanks in advance!

0 Answers
Related