登录
首页 >  Golang >  Go问答

无需验证即可解码 JWT 并查找范围

来源:stackoverflow

时间:2024-04-06 23:33:35 212浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《无需验证即可解码 JWT 并查找范围》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

我需要解码我的 jwt 令牌并检查范围是否为“doctor”。

我对 go 知之甚少,但我只需要在我的应用程序中编写一个小片段来扩展现有的应用程序,因此它需要用 go 编写。

这是我尝试解码令牌并检查“doctor”是否在解码的令牌中,因为我无法独占访问范围。

for k, v := range props {
        token_value := fmt.sprint(v)
        token_key := fmt.sprint(cfg.authkey)
        if (k == "custom_token_header") && strings.contains(token_value, token_key) {
            if token, _ := jwt.parse(token_value, nil); token != nil {
                parsed_token := fmt.sprint(token)
                log.infof("parsed token: " ,parsed_token)
                if strings.contains(parsed_token, "doctor")  {
                    log.infof("user is a doctor, perform checks...")
                    loc, _ := time.loadlocation("gmt")
                    now := time.now().in(loc)
                    hr, _, _ := now.clock()
                    if hr >= 9 && hr < 5 {
                        log.infof("success, inside of work hours!!")
                        return &v1beta1.checkresult{
                            status: status.ok,
                        }, nil
                    }
                    log.infof("failure; outside of work hours!!")
                    return &v1beta1.checkresult{
                        status: status.withpermissiondenied("unauthorized..."),
                    }, nil
                }
            }
            log.infof("success, as you're not a doctor!!")
            return &v1beta1.checkresult{
                status: status.ok,
            }, nil
        }
    }

它在我的应用程序之外工作正常,但是当在我的应用程序内部运行时,它很奇怪,并返回这个 map[] false 声明的位置,但是当在应用程序外部运行时,它给了我

map[alg:rs256 kid:nuvgodixqthbqky2njexqjgzmejemjvbqtc3qthbnty4qty3mzhema typ:jwt] map[aud:https://rba.com/doctor azp:3xfbbjtl6tsl9wh6izqtkz3rkggeilwh exp:1.55546266e+09 gty:client-credentials iat:1.55537626e+09 iss:https://jor2.eu.auth0.com/ scope:doctor sub:3xfbbjtl6tsl9wh6izqtkz3rkggeilwh@clients]  false

感谢 devdotlog,我能够通过此更改来实现此功能:

for k, v := range props {
        tokenString := fmt.Sprint(v)
        tokenKey := fmt.Sprint(cfg.AuthKey)
        if (k == "custom_token_header") && strings.Contains(tokenString, tokenKey) {
            tokenString = strings.Replace(tokenString, "Bearer ", "", -1)
            token, _, err := new(jwt.Parser).ParseUnverified(tokenString, jwt.MapClaims{})
            if err != nil {
                fmt.Println(err)
                return nil, nil
            }
            if claims, ok := token.Claims.(jwt.MapClaims); ok {
                tokenScope := fmt.Sprint(claims["scope"])
                log.Infof("Scope: ", tokenScope)
                if tokenScope == "Doctor" {
                    log.Infof("user is a Doctor, perform checks...")
                    loc, _ := time.LoadLocation("GMT")
                    now := time.Now().In(loc)
                    hr, _, _ := now.Clock()
                    if hr >= 9 && hr < 5 {
                        log.Infof("success, inside of work hours!!")
                        return &v1beta1.CheckResult{
                            Status: status.OK,
                        }, nil
                    }
                    log.Infof("failure; outside of work hours!!")
                    return &v1beta1.CheckResult{
                        Status: status.WithPermissionDenied("Unauthorized..."),
                    }, nil
                }
                fmt.Println(claims["scope"])
            } else {
                fmt.Println(err)
            }
            log.Infof("success, as you're not a doctor!!")
            return &v1beta1.CheckResult{
                Status: status.OK,
            }, nil
        }
    }

解决方案


您使用 github.com/dgrijalva/jwt-go。是这样吗?

您在未经验证的情况下使用 parseunverified(https://godoc.org/github.com/dgrijalva/jwt-go#Parser.ParseUnverified)。

下面的代码是 parseunverified()' 示例。

package main

import (
    "fmt"

    "github.com/dgrijalva/jwt-go"
)

func main() {
    // This token is expired
    var tokenString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c"

    token, _, err := new(jwt.Parser).ParseUnverified(tokenString, jwt.MapClaims{})
    if err != nil {
        fmt.Println(err)
        return
    }

    if claims, ok := token.Claims.(jwt.MapClaims); ok {
        fmt.Println(claims["foo"], claims["exp"])
    } else {
        fmt.Println(err)
    }
}

parseunverified() 仅用于调试。

警告:除非您知道自己在做什么,否则不要使用此方法

此方法解析令牌但不验证签名。仅当您知道签名有效(因为之前已在堆栈中检查过它)并且您想从中提取值时,它才有用。

好了,本文到此结束,带大家了解了《无需验证即可解码 JWT 并查找范围》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>