• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

在golang提取和验证从前端发送的令牌

用户头像
it1352
帮助1

问题说明

我使用"github.com/dgrijalva/jwt-go",并且能够向我的前端发送令牌,以及我想知道如何才能检索从前端发送的令牌,以便我可以验证是否发送的令牌是有效的,如果是这样,则将交付安全资源.

Am using "github.com/dgrijalva/jwt-go", and able to send a token to my frontend , and what i would like to know how i could retrieve the token sent from the frontend so that i can verify if the token that was sent is valid and if so the secured resource will be delivered.

这是前端javascript发送的令牌...

Here is the token sent from frontend javascript ...

headers: {
       'Authorization':'Bearer'   localStorage.getItem('id_token')
     }

这是发送令牌的代码

    token := jwt.New(jwt.GetSigningMethod("HS256"))
    claims := make(jwt.MapClaims)
    claims["userName"] = loginRequest.UserName
    claims["exp"] = time.Now().Add(time.Minute * 60).Unix()
    token.Claims = claims
    tokenString, err := token.SignedString([]byte(SecretKey))
    tokenByte, err := json.Marshal(data)
    w.WriteHeader(201)
    w.Write(tokenByte)

这是验证令牌的代码

    func VerifyToken(r *http.Request) bool {

    reqToken := r.Header.Get("Authorization")
    token, err := jwt.Parse(reqToken, func(t *jwt.Token) (interface{}, error) {
        return []byte(SecretKey), nil
    })
    if err == nil && token.Valid {
        fmt.Println("valid token")
        return true
    } else {
        fmt.Println("invalid token")
        return false
    }

}

正在获得 nil 令牌作为回报,我猜是我已经发送了不记名令牌,我认为如果需要的话,可能需要进行解析?

Am getting nil token as a return, my guess is i have sent bearer and i think it might need parsing if so how ?

正确答案

#1

在我的情况下,服务器需要令牌字符串而不添加字符串,在向Web服务器发送请求时,我已经在标题的令牌字符串中添加了Bearer字符串,即

The server requires a token string without added strings in my case I have added Bearer string to the token string in the header when sending request to the web server i.e.

'Authorization':'Bearer'   localStorage.getItem('id_token')

在Web服务器上,我们只需要拆分有效令牌,而无需Bearer字符串

At the web server we need to split only the valid token without the Bearer string

reqToken := r.Header.Get("Authorization")
splitToken := strings.Split(reqToken, "Bearer")
reqToken = splitToken[1]

因此,它成为没有nil的有效令牌.

As a result it becomes valid token without nil.

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfaaee
系列文章
更多 icon
同类精品
更多 icon
继续加载