本文整理汇总了Golang中github.com/dgrijalva/jwt-go.Parse函数的典型用法代码示例。如果您正苦于以下问题:Golang Parse函数的具体用法?Golang Parse怎么用?Golang Parse使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Parse函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
}
}
开发者ID:writeas,项目名称:htmlhouse,代码行数:28,代码来源:session.go
示例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
}
开发者ID:tianhai82,项目名称:gae_authen,代码行数:25,代码来源:auth.go
示例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()
}
}
开发者ID:lancecarlson,项目名称:divan,代码行数:35,代码来源:server.go
示例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
}
开发者ID:Ritsyy,项目名称:almighty-core,代码行数:29,代码来源:token.go
示例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
}
开发者ID:min2033,项目名称:WebVR-Test,代码行数:27,代码来源:app.go
示例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)
}
}
开发者ID:sandbreaker,项目名称:photoshare,代码行数:25,代码来源:session.go
示例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
}
开发者ID:wlan0,项目名称:host-api,代码行数:31,代码来源:auth.go
示例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
}
开发者ID:CadeLaRen,项目名称:traffic_control,代码行数:31,代码来源:traffic_ops_auth.go
示例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()
}
}
开发者ID:marble58,项目名称:tiedot,代码行数:27,代码来源:rsa_test.go
示例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
}
开发者ID:xtraclabs,项目名称:roll,代码行数:33,代码来源:token.go
示例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
}
开发者ID:wutaizeng,项目名称:kapacitor,代码行数:32,代码来源:app.go
示例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")
}
}
}
开发者ID:cloudawan,项目名称:cloudone,代码行数:34,代码来源:token.go
示例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
}
}
开发者ID:yrashk,项目名称:minio,代码行数:33,代码来源:web-handlers.go
示例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)
}
}
开发者ID:csrgxtu,项目名称:Gosrc,代码行数:27,代码来源:server.go
示例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
}
开发者ID:stonedoc,项目名称:stone,代码行数:34,代码来源:crypto.go
示例16: handleGetKey
func (k *Kontrol) handleGetKey(r *kite.Request) (interface{}, error) {
// Only accept requests with kiteKey because we need this info
// for checking if the key is valid and needs to be regenerated
if r.Auth.Type != "kiteKey" {
return nil, fmt.Errorf("Unexpected authentication type: %s", r.Auth.Type)
}
t, err := jwt.Parse(r.Auth.Key, kitekey.GetKontrolKey)
if err != nil {
return nil, err
}
publicKey, ok := t.Claims["kontrolKey"].(string)
if !ok {
return nil, errors.New("public key is not passed")
}
err = k.keyPair.IsValid(publicKey)
if err == nil {
// everything is ok, just return the old one
return publicKey, nil
}
keyPair, err := k.pickKey(r)
if err != nil {
return nil, err
}
return keyPair.Public, nil
}
开发者ID:gotao,项目名称:kite,代码行数:30,代码来源:handlers.go
示例17: CheckToken
func CheckToken() gin.HandlerFunc {
return func(c *gin.Context) {
// request cookie
tokenCookie, err := c.Request.Cookie("token")
switch {
case err == http.ErrNoCookie:
//c.JSON(http.StatusUnauthorized, gin.H{"message": http.ErrNoCookie.Error()})
c.HTML(http.StatusUnauthorized, "err.tmpl", gin.H{"message": http.ErrNoCookie.Error()})
c.Abort()
return
case err != nil:
c.JSON(http.StatusUnauthorized, gin.H{"message": "something is wrong with the cookie"})
}
// validate the token
token, err := jwt.Parse(tokenCookie.Value, func(token *jwt.Token) (interface{}, error) {
return verifyKey, nil
})
switch err.(type) {
case nil:
if !token.Valid {
c.JSON(http.StatusUnauthorized, gin.H{"StatusUnauthorized": "StatusUnauthorized"})
c.Abort()
return
}
data := struct {
Access string
Username string
}{
token.Claims["access"].(string),
token.Claims["username"].(string),
}
//c.Set("token", token)
//c.Set("admin", token.Claims["access"])
c.Set("data", data)
c.Next()
case *jwt.ValidationError:
vErr := err.(*jwt.ValidationError)
switch vErr.Errors {
case jwt.ValidationErrorExpired:
c.JSON(http.StatusUnauthorized, gin.H{"StatusUnauthorized": "token expired"})
c.Abort()
return
default:
c.JSON(http.StatusUnauthorized, gin.H{"StatusUnauthorized": vErr.Errors})
c.Abort()
return
}
default:
c.JSON(http.StatusUnauthorized, gin.H{"StatusUnauthorized": err.Error()})
c.Abort()
return
}
}
}
开发者ID:ouchkernel,项目名称:blog,代码行数:59,代码来源:main.go
示例18: TestAuthValidateCodeResponseAuthenticateOk
func TestAuthValidateCodeResponseAuthenticateOk(t *testing.T) {
core, coreConfig := NewTestCore()
ln, addr := TestServer(t, core)
defer ln.Close()
privateKey, publicKey, err := secrets.GenerateKeyPair()
assert.Nil(t, err)
secretsMock := coreConfig.SecretsRepo.(*mocks.SecretsRepo)
secretsMock.On("RetrievePrivateKeyForApp", "1111-2222-3333333-4444444").Return(privateKey, nil)
secretsMock.On("RetrievePublicKeyForApp", "1111-2222-3333333-4444444").Return(publicKey, nil)
var loginCalled = false
ls := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
loginCalled = true
w.WriteHeader(http.StatusOK)
}))
defer ls.Close()
//TODO - use a second callback where we serve up a script to extract the page details sent
//on deny and post those details to another test server.
var callbackInvoked = false
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
callbackInvoked = true
code := r.FormValue("code")
token, err := jwt.Parse(code, rolltoken.GenerateKeyExtractionFunction(core.SecretsRepo))
assert.Nil(t, err)
scope, ok := token.Claims["scope"].(string)
assert.True(t, ok)
assert.Equal(t, "xtAuthCode", scope)
}))
defer ts.Close()
lsURL, _ := url.Parse(ls.URL)
returnVal := roll.Application{
DeveloperEmail: "[email protected]",
ClientID: "1111-2222-3333333-4444444",
ApplicationName: "fight club",
ClientSecret: "not for browser clients",
RedirectURI: ts.URL,
LoginProvider: "xtrac://" + lsURL.Host,
}
appRepoMock := coreConfig.ApplicationRepo.(*mocks.ApplicationRepo)
appRepoMock.On("SystemRetrieveApplication", "1111-2222-3333333-4444444").Return(&returnVal, nil)
_, err = http.PostForm(addr+"/oauth2/validate",
url.Values{"username": {"x"},
"password": {"y"},
"authorize": {"allow"},
"response_type": {"code"},
"client_id": {"1111-2222-3333333-4444444"}})
assert.Nil(t, err)
assert.True(t, callbackInvoked)
assert.True(t, loginCalled)
}
开发者ID:xtraclabs,项目名称:roll,代码行数:59,代码来源:authz_test.go
示例19: TestPWGrantLoginOk
func TestPWGrantLoginOk(t *testing.T) {
core, coreConfig := NewTestCore()
ln, addr := TestServer(t, core)
defer ln.Close()
var loginCalled = false
ls := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
loginCalled = true
w.WriteHeader(http.StatusOK)
}))
defer ls.Close()
lsURL, _ := url.Parse(ls.URL)
returnVal := roll.Application{
DeveloperEmail: "[email protected]",
ClientID: "1111-2222-3333333-4444444",
ApplicationName: "fight club",
ClientSecret: "not for browser clients",
RedirectURI: "http://localhost:3000/ab",
LoginProvider: "xtrac://" + lsURL.Host,
}
appRepoMock := coreConfig.ApplicationRepo.(*mocks.ApplicationRepo)
appRepoMock.On("SystemRetrieveApplication", "1111-2222-3333333-4444444").Return(&returnVal, nil)
privateKey, publicKey, err := secrets.GenerateKeyPair()
assert.Nil(t, err)
secretsMock := coreConfig.SecretsRepo.(*mocks.SecretsRepo)
secretsMock.On("RetrievePrivateKeyForApp", "1111-2222-3333333-4444444").Return(privateKey, nil)
secretsMock.On("RetrievePublicKeyForApp", "1111-2222-3333333-4444444").Return(publicKey, nil)
resp, err := http.PostForm(addr+OAuth2TokenBaseURI,
url.Values{"grant_type": {"password"},
"client_id": {"1111-2222-3333333-4444444"},
"client_secret": {"not for browser clients"},
"username": {"abc"},
"password": {"xxxxxxxx"}})
assert.True(t, loginCalled)
assert.Nil(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
body := responseAsString(t, resp)
var jsonResponse accessTokenResponse
err = json.Unmarshal([]byte(body), &jsonResponse)
assert.Nil(t, err)
assert.True(t, jsonResponse.AccessToken != "")
assert.True(t, jsonResponse.TokenType == "Bearer")
token, err := jwt.Parse(jsonResponse.AccessToken, rolltoken.GenerateKeyExtractionFunction(core.SecretsRepo))
assert.Nil(t, err)
fmt.Println(token.Claims)
assert.Equal(t, "1111-2222-3333333-4444444", token.Claims["aud"].(string))
assert.Equal(t, "abc", token.Claims["sub"].(string))
assert.Equal(t, "", token.Claims["scope"].(string))
}
开发者ID:xtraclabs,项目名称:roll,代码行数:58,代码来源:tokenpw_test.go
示例20: Authenticate
func Authenticate() gin.HandlerFunc {
return func(c *gin.Context) {
db := c.MustGet("db").(gorm.DB)
config = c.MustGet("config").(models.Configuration)
tokenString := c.Request.Header.Get("X-Authentication-Token")
if tokenString == "" {
response := make(map[string]string)
response["error"] = "Invalid credentials."
c.JSON(401, response)
c.Abort(401)
} else {
token, err := jwt.Parse(tokenString, verify)
if err != nil {
log.Fatal(err)
} else {
if token.Valid {
now := time.Now().UTC()
expiration, err := time.Parse(time.RFC3339, token.Claims["life"].(string))
if err != nil {
log.Fatal(err)
}
if now.After(expiration) {
response := make(map[string]string)
response["error"] = "Invalid credentials."
c.JSON(401, response)
c.Abort(401)
}
var user models.User
db.First(&user, token.Claims["id"])
if user.Username == "" {
response := make(map[string]string)
response["error"] = "Someone fucked up."
c.JSON(500, response)
c.Abort(500)
} else {
c.Set("consumer", user)
c.Next()
}
} else {
response := make(map[string]string)
response["error"] = "Someone fucked up."
c.JSON(500, response)
c.Abort(500)
}
}
}
}
}
开发者ID:zannet,项目名称:karousel,代码行数:57,代码来源:authenticate.go
注:本文中的github.com/dgrijalva/jwt-go.Parse函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论