本文整理汇总了Golang中github.com/dgrijalva/jwt-go.Parse函数的典型用法代码示例。如果您正苦于以下问题:Golang Parse函数的具体用法?Golang Parse怎么用?Golang Parse使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Parse函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: readToken
func (m *defaultSessionManager) readToken(r *http.Request) (string, error) {
tokenString := r.Header.Get(tokenHeader)
if tokenString == "" {
return "", nil
}
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return m.verifyKey, nil
})
switch err.(type) {
case nil:
if !token.Valid {
return "", nil
}
claims := token.Claims.(jwt.MapClaims)
houseID := claims["houseID"].(string)
return houseID, nil
case *jwt.ValidationError:
return "", nil
default:
return "", errgo.Mask(err)
}
}
示例2: ParseToken
func (authen *Authen) ParseToken(tokenString string) (*jwt.Token, error) {
myToken, err := jwt.Parse(tokenString, func(tokenWithin *jwt.Token) (interface{}, error) {
if _, ok := tokenWithin.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", tokenWithin.Header["alg"])
}
if tokenWithin.Method.Alg() != "HS512" {
return nil, fmt.Errorf("Unexpected signing method string: %v", tokenWithin.Header["alg"])
}
exp, ok := tokenWithin.Claims["exp"].(float64)
if !ok {
return nil, fmt.Errorf("Token does not contain expiry claim")
}
if exp < float64(time.Now().Unix()) {
return nil, fmt.Errorf("Token expired")
}
return authen.privateKey, nil
})
if err != nil {
return nil, err
}
if !myToken.Valid {
return nil, fmt.Errorf("Token is invalid")
}
return myToken, err
}
示例3: Auth
func (s *Server) Auth() gin.HandlerFunc {
return func(c *gin.Context) {
pubKey := s.Tables["divan"].PubKey
if pubKey == "" {
c.Next()
return
}
token := c.Query("token")
if token == "" {
c.JSON(401, gin.H{"error": "missing token"})
c.Abort()
return
}
out, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return []byte(pubKey), nil
})
if err != nil {
c.JSON(400, gin.H{"error": err.Error()})
c.Abort()
return
}
if !out.Valid {
c.JSON(403, gin.H{"error": "Token invalid"})
c.Abort()
return
}
c.Set("token", out)
c.Next()
}
}
示例4: Extract
func (mgm tokenManager) Extract(tokenString string) (*account.Identity, error) {
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return mgm.publicKey, nil
})
if err != nil {
return nil, errors.WithStack(err)
}
if !token.Valid {
return nil, errors.New("Token not valid")
}
claimedUUID := token.Claims.(jwt.MapClaims)["sub"]
if claimedUUID == nil {
return nil, errors.New("Subject can not be nil")
}
// in case of nil UUID, below type casting will fail hence we need above check
id, err := uuid.FromString(token.Claims.(jwt.MapClaims)["sub"].(string))
if err != nil {
return nil, errors.WithStack(err)
}
ident := account.Identity{
ID: id,
Username: token.Claims.(jwt.MapClaims)["preferred_username"].(string),
}
return &ident, nil
}
示例5: getAuth
// returns username and boolean indicating if the token was valid
func getAuth(r *http.Request) (string, bool) {
// check if we have a cookie with our tokenName
tokenCookie, err := r.Cookie(tokenName)
if err != nil {
return "", false
}
// validate the token
token, err := jwt.Parse(tokenCookie.Value, func(token *jwt.Token) (interface{}, error) {
return verifyKey, nil
})
if err == nil && token.Valid {
str, ok := token.Claims["username"].(string)
if ok {
return str, true
} else {
log.Print("token.Claims[\"username\"] Not a string.")
return "", false
}
}
return "", false
}
示例6: readToken
func (m *defaultSessionManager) readToken(r *http.Request) (int64, error) {
tokenString := r.Header.Get(tokenHeader)
if tokenString == "" {
return 0, nil
}
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return m.verifyKey, nil
})
switch err.(type) {
case nil:
if !token.Valid {
return 0, nil
}
token := token.Claims["uid"].(string)
userID, err := strconv.ParseInt(token, 10, 0)
if err != nil {
return 0, nil
}
return userID, nil
case *jwt.ValidationError:
return 0, nil
default:
return 0, errgo.Mask(err)
}
}
示例7: Auth
func Auth(rw http.ResponseWriter, req *http.Request) bool {
if !config.Config.Auth {
return true
}
tokenString := req.URL.Query().Get("token")
if len(tokenString) == 0 {
return false
}
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return config.Config.ParsedPublicKey, nil
})
SetToken(req, token)
if err != nil {
common.CheckError(err, 2)
return false
}
if !token.Valid {
return false
}
if config.Config.HostUuidCheck && token.Claims["hostUuid"] != config.Config.HostUuid {
glog.Infoln("Host UUID mismatch , authentication failed")
return false
}
return true
}
示例8: getTokenData
func getTokenData(jwtSigningKey string, r *http.Request) (*TokenData, error) {
encToken, err := r.Cookie(CookieName)
if err != nil {
return nil, err
}
token, err := jwt.Parse(encToken.Value, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return []byte(jwtSigningKey), nil
})
if err != nil {
return nil, err
}
if !token.Valid {
return nil, fmt.Errorf("invalid token")
}
userInterface, hasUser := token.Claims["user"]
roleInterface, hasRole := token.Claims["role"]
user, userIsStr := userInterface.(string)
role, roleIsStr := roleInterface.(string)
if !hasUser || !hasRole || !userIsStr || !roleIsStr {
// we signed it: this should never happen
return nil, fmt.Errorf("token missing claims")
}
return &TokenData{User: user, Role: role}, nil
}
示例9: TestJWTToken
func TestJWTToken(t *testing.T) {
var err error
if privateKey, err = ioutil.ReadFile("rsa-test.key"); err != nil {
t.Fatal(err)
}
if publicKey, err = ioutil.ReadFile("rsa-test.pub"); err != nil {
t.Fatal(err)
}
token := jwt.New(jwt.GetSigningMethod("RS256"))
token.Claims["PERMISSION"] = "[email protected]"
token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
ts, err := token.SignedString(privateKey)
if err != nil {
t.Fatal(err)
}
if token, err = jwt.Parse(ts, func(ts *jwt.Token) (interface{}, error) {
return publicKey, nil
}); err != nil {
t.Fatal(err)
}
if token.Valid {
t.Log(token)
} else {
t.Log(token)
t.Fail()
}
}
示例10: subjectFromBearerToken
func subjectFromBearerToken(core *roll.Core, r *http.Request) (string, error) {
//Check for header presence
authzHeader := r.Header.Get("Authorization")
if authzHeader == "" {
return "", errors.New("Authorization header missing from request")
}
//Header format should be Bearer token
parts := strings.SplitAfter(authzHeader, "Bearer")
if len(parts) != 2 {
return "", errors.New("Unexpected authorization header format - expecting bearer token")
}
//Parse the token
bearerToken := strings.TrimSpace(parts[1])
token, err := jwt.Parse(bearerToken, rolltoken.GenerateKeyExtractionFunction(core.SecretsRepo))
if err != nil {
return "", err
}
//Grab the subject from the claims
subject, ok := token.Claims["sub"].(string)
if !ok {
return "", errors.New("problem with subject claim")
}
//Is the subject something other than an empty string?
if subject == "" {
return "", errors.New("empty subject claim")
}
return subject, nil
}
示例11: showToken
// showToken pretty-prints the token on the command line.
func showToken() error {
// get the token
tokData, err := loadData(*flagShow)
if err != nil {
return fmt.Errorf("Couldn't read token: %v", err)
}
// trim possible whitespace from token
tokData = regexp.MustCompile(`\s*$`).ReplaceAll(tokData, []byte{})
if *flagDebug {
fmt.Fprintf(os.Stderr, "Token len: %v bytes\n", len(tokData))
}
token, err := jwt.Parse(string(tokData), nil)
if token == nil {
return fmt.Errorf("malformed token: %v", err)
}
// Print the token details
fmt.Println("Header:")
if err := printJSON(token.Header); err != nil {
return fmt.Errorf("Failed to output header: %v", err)
}
fmt.Println("Claims:")
if err := printJSON(token.Claims); err != nil {
return fmt.Errorf("Failed to output claims: %v", err)
}
return nil
}
示例12: GetUserFromToken
func GetUserFromToken(token string) (*rbac.User, error) {
_, err := jwt.Parse(token, 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, errors.New("Unexpected signing method")
}
expiredText, _ := token.Claims["expired"].(string)
expiredTime, err := time.Parse(time.RFC3339, expiredText)
if err != nil {
log.Error("Fail to parse expired time. Token %v error %s", token, err)
return nil, err
}
if expiredTime.Before(time.Now()) {
log.Debug("Token is expired. Token %v ", token)
return nil, errors.New("Token is expired")
}
return []byte(signingKey), nil
})
if err != nil {
return nil, err
} else {
user := rbac.GetCache(token)
if user != nil {
return user, nil
} else {
log.Error("User not in the cache. Token %v", token)
return nil, errors.New("User not in the cache")
}
}
}
示例13: Download
// Download - file download handler.
func (web *webAPIHandlers) Download(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
bucket := vars["bucket"]
object := vars["object"]
token := r.URL.Query().Get("token")
jwt := initJWT()
jwttoken, e := jwtgo.Parse(token, func(token *jwtgo.Token) (interface{}, error) {
if _, ok := token.Method.(*jwtgo.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return []byte(jwt.SecretAccessKey), nil
})
if e != nil || !jwttoken.Valid {
writeWebErrorResponse(w, errInvalidToken)
return
}
// Add content disposition.
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filepath.Base(object)))
objInfo, err := web.ObjectAPI.GetObjectInfo(bucket, object)
if err != nil {
writeWebErrorResponse(w, err)
return
}
offset := int64(0)
err = web.ObjectAPI.GetObject(bucket, object, offset, objInfo.Size, w)
if err != nil {
/// No need to print error, response writer already written to.
return
}
}
示例14: GetUserInfo
func GetUserInfo(res http.ResponseWriter, req *http.Request) {
AuthKey := http.CanonicalHeaderKey("authorization")
tokenString := strings.Replace(req.Header.Get(AuthKey), "Bearer ", "", -1)
// fmt.Println(tokenString)
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
fmt.Println(token)
return loadData("demo.rsa.pub")
})
if err == nil && token.Valid {
fmt.Println("Your token is valid. I like your style.")
rt, _ := json.Marshal(Result{http.StatusOK, "Successful", tokenString})
res.Header().Set("Content-Type", "application/json")
res.WriteHeader(http.StatusOK)
res.Write(rt)
} else {
fmt.Println("This token is terrible! I cannot accept this.")
fmt.Println(err)
rt, _ := json.Marshal(Result{http.StatusUnauthorized, "Token Unauthorized", tokenString})
res.Header().Set("Content-Type", "application/json")
res.WriteHeader(http.StatusUnauthorized)
res.Write(rt)
}
}
示例15: VerifyJWTRSA
// Verify a JWT token using an RSA public key
func VerifyJWTRSA(token, publicKey string) (bool, *jwt.Token, error) {
var parsedToken *jwt.Token
// parse token
state, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
// ensure signing method is correct
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, errors.New("unknown signing method")
}
parsedToken = token
// verify
key, err := jwt.ParseRSAPublicKeyFromPEM([]byte(publicKey))
if err != nil {
return nil, err
}
return key, nil
})
if err != nil {
return false, &jwt.Token{}, err
}
if !state.Valid {
return false, &jwt.Token{}, errors.New("invalid jwt token")
}
return true, parsedToken, nil
}