首页 > 解决方案 > 戈朗。如何自动授权我的应用访问 spotify API?

问题描述

我已经在 Spotify 上注册了我的应用程序并获得了我的凭据。我通过 zmb3/spotify Go 包装器使用 Spotify web api。

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

我有一个本地服务器(用 Golang 编写)监听某些路由上的请求。当我定义路由时,我创建了具有所需范围的 Spotify Authenticator 并获得了 url。如果我将授权 url 打印到标准输出并单击它(或者也使用复制和粘贴)redirectURI 被正确调用!这是代码...

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)
}

现在我想让 /authorize_spotify 自动调用获得的 url。我写了这两行。

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

但是,当我联系 localhost:8080/authorize_spotify 时,从未调用过 authHandler(尽管有 fmt.Println(...),但 stdout 上没有输出)。神秘地,我以同样的方式被重定向到redirectURI,但它失败了。

看到网络 http 交换,我注意到我打印的 authorize_url 与神秘发送的授权请求有点不同(在后者中缺少 user-top-read 范围),这证实了 authHandler 没有被调用。

如何从代码中实现我的令牌调用 authorize_url?提前致谢!

标签: httpgooauth-2.0spotify

解决方案


推荐阅读