खोज…


परिचय

JSON वेब टोकन (JWTs) दो दलों के बीच सुरक्षित रूप से दावों का प्रतिनिधित्व करने के लिए एक लोकप्रिय तरीका है। वेब एप्लिकेशन या एप्लिकेशन प्रोग्रामिंग इंटरफेस विकसित करते समय उनके साथ काम करना समझना महत्वपूर्ण है।

टिप्पणियों

संदर्भ। कॉन्टेक्स्ट और HTTP मिडलवेयर इस विषय के दायरे से बाहर हैं, लेकिन फिर भी उन जिज्ञासु, भटकती आत्माओं को https://github.com/goware/jwtauth , https://github.com/auth0-go-jwt- की जाँच करनी चाहिए मिडलवेयर , और https://github.com/dgrijalva/jwt-go

गो-जेडटी पर अपने अद्भुत काम के लिए डेव ग्रिजालवा को विशाल कुदोस।

HMAC हस्ताक्षर विधि का उपयोग करके एक टोकन को पार्स करना और मान्य करना

// sample token string taken from the New example
tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJuYmYiOjE0NDQ0Nzg0MDB9.u1riaD1rW97opCoAuRCTy4w58Br-Zk-bh7vLiRIsrpU"

// Parse takes the token string and a function for looking up the key. The latter is especially
// useful if you use multiple keys for your application.  The standard is to use 'kid' in the
// head of the token to identify which key to use, but the parsed token (head and claims) is provided
// to the callback, providing flexibility.
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
    // Don't forget to validate the alg is what you expect:
    if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
        return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
    }

    // hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
    return hmacSampleSecret, nil
})

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

आउटपुट:

bar 1.4444784e+09

( दस्तावेज से , दवे गृजालवा के सौजन्य से।)

कस्टम दावे प्रकार का उपयोग करके एक टोकन बनाना

StandardClaim आसान एन्कोडिंग, पार्स और मानक दावों के सत्यापन के लिए अनुमति देने के लिए कस्टम प्रकार में एम्बेडेड है।

tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c"

type MyCustomClaims struct {
    Foo string `json:"foo"`
    jwt.StandardClaims
}

// sample token is expired.  override time so it parses as valid
at(time.Unix(0, 0), func() {
    token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
        return []byte("AllYourBase"), nil
    })

    if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
        fmt.Printf("%v %v", claims.Foo, claims.StandardClaims.ExpiresAt)
    } else {
        fmt.Println(err)
    }
})

आउटपुट:

bar 15000

( दस्तावेज से , दवे गृजालवा के सौजन्य से।)

HMW हस्ताक्षर विधि का उपयोग करके एक JWT टोकन बनाना, हस्ताक्षर करना और एन्कोडिंग करना

// Create a new token object, specifying signing method and the claims
// you would like it to contain.
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
    "foo": "bar",
    "nbf": time.Date(2015, 10, 10, 12, 0, 0, 0, time.UTC).Unix(),
})

// Sign and get the complete encoded token as a string using the secret
tokenString, err := token.SignedString(hmacSampleSecret)

fmt.Println(tokenString, err)

आउटपुट:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJuYmYiOjE0NDQ0Nzg0MDB9.u1riaD1rW97opCoAuRCTy4w58Br-Zk-bh7vLiRIsrpU <nil>

( दस्तावेज से , दवे गृजालवा के सौजन्य से।)

एक टोकन को पार्स करने के लिए StandardClaims प्रकार का उपयोग करके

StandardClaims प्रकार को मानक सत्यापन सुविधाएँ प्रदान करने के लिए आपके कस्टम प्रकारों में एम्बेड किया गया है। आप इसे अकेले उपयोग कर सकते हैं, लेकिन पार्स करने के बाद अन्य क्षेत्रों को पुनः प्राप्त करने का कोई तरीका नहीं है। इच्छित उपयोग के लिए कस्टम दावे उदाहरण देखें।

mySigningKey := []byte("AllYourBase")

// Create the Claims
claims := &jwt.StandardClaims{
    ExpiresAt: 15000,
    Issuer:    "test",
}

token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
ss, err := token.SignedString(mySigningKey)
fmt.Printf("%v %v", ss, err)

आउटपुट:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.QsODzZu3lUZMVdhbO76u3Jv02iYCvEHcYVUI1kOWEU0 <nil>

( दस्तावेज से , दवे गृजालवा के सौजन्य से।)

बिटफील्ड चेक का उपयोग करके त्रुटि प्रकारों को पार्स करना

// Token from another example.  This token is expired
var tokenString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c"

token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
    return []byte("AllYourBase"), nil
})

if token.Valid {
    fmt.Println("You look nice today")
} else if ve, ok := err.(*jwt.ValidationError); ok {
    if ve.Errors&jwt.ValidationErrorMalformed != 0 {
        fmt.Println("That's not even a token")
    } else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
        // Token is either expired or not active yet
        fmt.Println("Timing is everything")
    } else {
        fmt.Println("Couldn't handle this token:", err)
    }
} else {
    fmt.Println("Couldn't handle this token:", err)
}

आउटपुट:

Timing is everything

( दस्तावेज से , दवे गृजालवा के सौजन्य से।)

HTTP प्राधिकरण हेडर से टोकन प्राप्त करना

type contextKey string

const (
    // JWTTokenContextKey holds the key used to store a JWT Token in the
    // context.
    JWTTokenContextKey contextKey = "JWTToken"

    // JWTClaimsContextKey holds the key used to store the JWT Claims in the
    // context.
    JWTClaimsContextKey contextKey = "JWTClaims"
)

// ToHTTPContext moves JWT token from request header to context.
func ToHTTPContext() http.RequestFunc {
    return func(ctx context.Context, r *stdhttp.Request) context.Context {
        token, ok := extractTokenFromAuthHeader(r.Header.Get("Authorization"))
        if !ok {
            return ctx
        }

        return context.WithValue(ctx, JWTTokenContextKey, token)
    }
}

( गो-किट / किट से , पीटर बॉबरन के सौजन्य से)



Modified text is an extract of the original Stack Overflow Documentation
के तहत लाइसेंस प्राप्त है CC BY-SA 3.0
से संबद्ध नहीं है Stack Overflow