搜尋
首頁後端開發Golang無法驗證 JWT 令牌

无法验证 JWT 令牌

php小編西瓜為您介紹一個常見的問題:無法驗證JWT令牌。 JWT(JSON Web Token)是一種用於身份驗證和授權的開放標準。然而,有時在PHP應用程式中,我們可能會遇到無法驗證JWT令牌的問題。這可能是由於多種原因引起的,例如密鑰不匹配、令牌過期等。本文將為您詳細解釋這個問題的可能原因,並提供解決方案,幫助您成功驗證JWT令牌。

問題內容

我想做的就是產生一個新的金鑰,建立 jwt 令牌,然後驗證它。

package main

import (
    "crypto/ecdsa"
    "crypto/elliptic"
    "crypto/rand"
    "crypto/x509"
    "encoding/base64"
    "fmt"
    "log"
    "time"

    "github.com/golang-jwt/jwt/v4"
)

func main() {
    key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
    if err != nil {
        log.Fatalln(err)
        return
    }

    privateK, err := x509.MarshalECPrivateKey(key)
    if err != nil {
        log.Fatalln(err)
        return
    }

    claims := jwt.MapClaims{}
    claims["authorized"] = true
    claims["user_id"] = 10
    claims["exp"] = time.Now().Add(time.Hour * time.Duration(1)).Unix()
    t := jwt.NewWithClaims(jwt.SigningMethodES256, claims)

    tokenStr, err := t.SignedString(key)
    if err != nil {
        log.Fatalln(err)
        return
    }

    fmt.Printf("Secret: %s\n", base64.StdEncoding.EncodeToString(privateK))
    fmt.Printf("Token: %s\n", tokenStr)

    // Validate token

    _, err = jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
        if _, ok := token.Method.(*jwt.SigningMethodECDSA); !ok {
            return nil, fmt.Errorf("unexpected signing method %v", token.Header["alg"])
        }
        return key, nil
    })

    if err != nil {
        log.Fatalf("Token is invalid %v", err)
    } else {
        fmt.Println("Token is valid")
    }
}

我得到 token is invalid: key is of invalid type。我做錯了什麼?

解決方法

根據 文件

#

ECDSA 簽章方法(ES256、ES384、ES512)需要 *ecdsa.PrivateKey 進行簽名,*ecdsa.PublicKey 進行驗證

您的 keyfunc 傳回一個 * edcsa.PrivateKey 與上面的不符。若要修正此問題,請將 return key, nil 變更為 return &key.PublicKey, nil (playground)。

以上是無法驗證 JWT 令牌的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:stackoverflow。如有侵權,請聯絡admin@php.cn刪除
去其他語言:比較分析去其他語言:比較分析Apr 28, 2025 am 12:17 AM

goisastrongchoiceforprojectsneedingsimplicity,績效和引發性,butitmaylackinadvancedfeatures and ecosystemmaturity.1)

比較以其他語言的靜態初始化器中的初始化功能比較以其他語言的靜態初始化器中的初始化功能Apr 28, 2025 am 12:16 AM

Go'sinitfunctionandJava'sstaticinitializersbothservetosetupenvironmentsbeforethemainfunction,buttheydifferinexecutionandcontrol.Go'sinitissimpleandautomatic,suitableforbasicsetupsbutcanleadtocomplexityifoverused.Java'sstaticinitializersoffermorecontr

GO中初始功能的常見用例GO中初始功能的常見用例Apr 28, 2025 am 12:13 AM

thecommonusecasesfortheinitfunctionoare:1)加載configurationfilesbeforeThemainProgramStarts,2)初始化的globalvariables和3)runningpre-checkSorvalidationsbeforEtheprofforeTheProgrecce.TheInitFunctionIsautefunctionIsautomentycalomationalmatomatimationalycalmatemationalcalledbebeforethemainfuniinfuninfuntuntion

GO中的頻道:掌握際際交流GO中的頻道:掌握際際交流Apr 28, 2025 am 12:04 AM

ChannelsarecrucialingoforenablingsafeandefficityCommunicationBetnewengoroutines.theyfacilitateSynChronizationAndManageGoroutIneLifeCycle,EssentialforConcurrentProgramming.ChannelSallSallSallSallSallowSallowsAllowsEnderDendingAndReceivingValues,ActassignalsignalsforsynChronization,and actassignalsynChronization and andsupppor

包裝錯誤:將上下文添加到錯誤鏈中包裝錯誤:將上下文添加到錯誤鏈中Apr 28, 2025 am 12:02 AM

在Go中,可以通過errors.Wrap和errors.Unwrap方法來包裝錯誤並添加上下文。 1)使用errors包的新功能,可以在錯誤傳播過程中添加上下文信息。 2)通過fmt.Errorf和%w包裝錯誤,幫助定位問題。 3)自定義錯誤類型可以創建更具語義化的錯誤,增強錯誤處理的表達能力。

使用GO開發時的安全考慮使用GO開發時的安全考慮Apr 27, 2025 am 12:18 AM

Gooffersrobustfeaturesforsecurecoding,butdevelopersmustimplementsecuritybestpracticeseffectively.1)UseGo'scryptopackageforsecuredatahandling.2)Manageconcurrencywithsynchronizationprimitivestopreventraceconditions.3)SanitizeexternalinputstoavoidSQLinj

了解GO的錯誤接口了解GO的錯誤接口Apr 27, 2025 am 12:16 AM

Go的錯誤接口定義為typeerrorinterface{Error()string},允許任何實現Error()方法的類型被視為錯誤。使用步驟如下:1.基本檢查和記錄錯誤,例如iferr!=nil{log.Printf("Anerroroccurred:%v",err)return}。 2.創建自定義錯誤類型以提供更多信息,如typeMyErrorstruct{MsgstringDetailstring}。 3.使用錯誤包裝(自Go1.13起)來添加上下文而不丟失原始錯誤信息,

並發程序中的錯誤處理並發程序中的錯誤處理Apr 27, 2025 am 12:13 AM

對效率的Handleerrorsinconcurrentgopragrs,UsechannelstocommunicateErrors,enplionErrorWatchers,Instertimeout,UsebufferedChannels和Provideclearrormessages.1)USEchannelelStopassErtopassErrorsErtopassErrorsErrorsErrorsFromGoroutInestOthemainFunction.2)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。