簡體   English   中英

如何使用用戶名和密碼獲取 API 響應?

[英]How get API response using username and password?

API 受登錄保護。 我在直接站點上輸入登錄后,它顯示 curl 結果,其中包含一個令牌。 在某些時候,我可以通過以下方式獲得結果:

const headers = new HttpHeaders()
    .set('accept', 'application/json')
    .set('Authorization', `Bearer xxxx<); //xxx is the token

    this.data = this.http.get(url, { headers: headers }) 

但它不再起作用了。

另外,我認為我應該能夠使用用戶憑據執行 http.post,獲取令牌並使用令牌從 API 獲取 json。 我有點困惑。 我閱讀了很多 SO 帖子,但對我的情況都沒有幫助。 我仍然一無所獲。

此外,令牌會一次又一次地更改。 會不會是這個原因?

這似乎有效:

this.data = this.http.post(this.url, { headers: headers })
    .subscribe((res) => {
        return res
    })

但這並不

this.data = this.http.post(this.url, { username: 'username', password: 'password' }) //with real credentials
    .subscribe((res) => {
        return res
    })

此請求給出 405 錯誤:(

this.http.post(this.url, { username: 'username', password: 'password' })
            .subscribe((res) => {
                return res
            })

您可能需要身份驗證攔截器,並且需要使用刷新令牌。 一時興起有很多發現,但實際上你會在你的應用程序中存儲一個刷新令牌(附帶一個 jwt),設置一個身份驗證攔截器,然后在 400 秒時你會嘗試用你的刷新令牌獲取一個新令牌,並且再次嘗試端點。

這有點令人費解,但在高層次上它是有道理的。 訪問令牌僅持續 15 分鍾,而刷新令牌持續時間更長,並且用於在訪問令牌到期時不斷循環訪問令牌。 您只需要粘貼一些有趣的中間件來無縫處理錯誤情況,而無需再考慮它。

窺視https://www.bezkoder.com/angular-12-refresh-token/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM