• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Golang jwt-go.New函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/dgrijalva/jwt-go.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了New函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: GenerateToken

func (a *authService) GenerateToken(user *schema.User) (*TokenFields, error) {

	expiresAt := time.Now().Add(time.Hour * 2)

	token := jwt.New(jwt.GetSigningMethod("HS256"))
	token.Claims["uid"] = user.ID
	token.Claims["uname"] = user.Username
	token.Claims["iat"] = expiresAt.Unix()

	accessToken, err := token.SignedString(a.SigningKey)
	if err != nil {
		return nil, err
	}

	// generate JWT access token
	token = jwt.New(jwt.GetSigningMethod("HS256"))
	token.Claims["uid"] = user.ID
	token.Claims["uname"] = user.Username
	token.Claims["iat"] = time.Now().Add(time.Hour * 24 * 14).Unix()

	refreshToken, err := token.SignedString(a.RefreshKey)
	if err != nil {
		return nil, err
	}

	return &TokenFields{AccessToken: accessToken, RefreshToken: refreshToken, ExpiresAt: expiresAt}, nil
}
开发者ID:messagedb,项目名称:messagedb,代码行数:27,代码来源:auth.go


示例2: mockLoginTokenWithoutID

func mockLoginTokenWithoutID(expires time.Time, auth_key []byte) (string, error) {
	token := jwt.New(jwt.SigningMethodHS256)
	// Set some claims
	token.Claims["exp"] = expires.Unix()
	// Sign and get the complete encoded token as a string
	return token.SignedString(auth_key)
}
开发者ID:nazwa,项目名称:Galaxy-Empires,代码行数:7,代码来源:authentication_test.go


示例3: main

func main() {
	r := gin.Default()

	public := r.Group("/api")

	public.GET("/", func(c *gin.Context) {
		// Create the token
		token := jwt_lib.New(jwt_lib.GetSigningMethod("HS256"))
		// Set some claims
		token.Claims["ID"] = "Christopher"
		token.Claims["exp"] = time.Now().Add(time.Hour * 1).Unix()
		// Sign and get the complete encoded token as a string
		tokenString, err := token.SignedString([]byte(mysupersecretpassword))
		if err != nil {
			c.JSON(500, gin.H{"message": "Could not generate token"})
		}
		c.JSON(200, gin.H{"token": tokenString})
	})

	private := r.Group("/api/private")
	private.Use(jwt.Auth(mysupersecretpassword))

	/*
		Set this header in your request to get here.
		Authorization: Bearer `token`
	*/

	private.GET("/", func(c *gin.Context) {
		c.JSON(200, gin.H{"message": "Hello from private"})
	})

	r.Run("localhost:8080")
}
开发者ID:doubledutch,项目名称:dd-vote,代码行数:33,代码来源:example.go


示例4: Login

func (as *authServer) Login(ctx context.Context, request *pb.LoginRequest) (*pb.LoginResponse, error) {
	user, err := getUser(db, request.Username)
	if err != nil {
		return nil, err
	}
	err = bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(request.Password))
	if err != nil {
		return nil, grpc.Errorf(codes.PermissionDenied, "")
	}

	token := jwt.New(jwt.SigningMethodRS256)
	token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
	token.Claims["admin"] = user.IsAdmin
	token.Claims["iss"] = "auth.service"
	token.Claims["iat"] = time.Now().Unix()
	token.Claims["email"] = user.Email
	token.Claims["sub"] = user.Username

	tokenString, err := token.SignedString(as.jwtPrivatekey)
	if err != nil {
		return nil, grpc.Errorf(codes.Internal, err.Error())
	}

	return &pb.LoginResponse{tokenString}, nil
}
开发者ID:kelseyhightower,项目名称:grpc-hello-service,代码行数:25,代码来源:login.go


示例5: JwtGetToken

// generate jwt token and return to client
func JwtGetToken(c *gin.Context) {
	var login Login
	val := c.Bind(&login)
	if !val {
		c.JSON(200, gin.H{"code": 401, "msg": "Both name & password are required"})
		return
	}
	//	if login.Name == validUser.Name && login.Pass == validUser.Pass {
	token := jwt.New(jwt.SigningMethodHS256)
	// Headers
	token.Header["alg"] = "HS256"
	token.Header["typ"] = "JWT"

	// Claims
	token.Claims["name"] = validUser.Name
	token.Claims["mail"] = validUser.Mail
	token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
	tokenString, err := token.SignedString([]byte(mySigningKey))

	fmt.Println("jwt token raw: ", tokenString)

	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "Server error!"})
		return
	}
	c.JSON(200, gin.H{"code": 200, "msg": "OK", "jwt": tokenString})
	//	} else {
	//		c.JSON(200, gin.H{"code": 400, "msg": "Error username or password!"})
	//	}
}
开发者ID:tsingson,项目名称:todos-backend,代码行数:31,代码来源:jwt-token.go


示例6: login

func login(c echo.Context) error {
	username := c.FormValue("username")
	password := c.FormValue("password")

	if username == "jon" && password == "shhh!" {
		// Create token
		token := jwt.New(jwt.SigningMethodHS256)

		// Set claims
		claims := token.Claims.(jwt.MapClaims)
		claims["name"] = "Jon Snow"
		claims["admin"] = true
		claims["exp"] = time.Now().Add(time.Hour * 72).Unix()

		// Generate encoded token and send it as response.
		t, err := token.SignedString([]byte("secret"))
		if err != nil {
			return err
		}
		return c.JSON(http.StatusOK, map[string]string{
			"token": t,
		})
	}

	return echo.ErrUnauthorized
}
开发者ID:luizbafilho,项目名称:fusis,代码行数:26,代码来源:server.go


示例7: setToken

// Create JSON Web Token
func (c *Client) setToken(r *http.Request) error {

	token := jwt.New(jwt.SigningMethodHS256)

	// Set issuer
	token.Claims["iss"] = c.user

	// Set issued at time
	token.Claims["iat"] = time.Now().Unix()

	// Set expiration
	token.Claims["exp"] = time.Now().Add(time.Minute * 5).Unix()

	// Set qsh hash
	qshstring := r.Method + "&" + r.URL.Path
	hash := sha256.New()
	hash.Write([]byte(qshstring))
	token.Claims["qsh"] = hex.EncodeToString(hash.Sum(nil))

	// Sign the token
	signedtoken, err := token.SignedString([]byte(c.key))
	if err != nil {
		return err
	}

	// Save it in the header
	r.Header.Set("Authorization", "bearer "+signedtoken)

	return nil
}
开发者ID:yepengxj,项目名称:heketi,代码行数:31,代码来源:client.go


示例8: login

// Expects username & password to be passed as JSON in the POST body
// This is how Ember does it.
func (s *APIServer) login(c echo.Context) error {
	a := new(AuthInfo)

	if err := c.Bind(a); err != nil {
		return err
	}

	dbuser, err := s.DBH.GetUserByEmail(a.Username)
	if err == nil {
		//if bcrypt.CompareHashAndPassword([]byte(dbuser.Password), []byte(a.Password)) == nil {
		token := jwt.New(jwt.SigningMethodHS256)

		// Set claims
		claims := token.Claims.(jwt.MapClaims)
		claims["name"] = dbuser.Email
		claims["admin"] = false
		claims["exp"] = time.Now().Add(time.Hour * 72).Unix()

		// Generate encoded token and send it as response.
		t, err := token.SignedString([]byte("secret"))
		if err != nil {
			return err
		}
		return c.JSON(http.StatusOK, map[string]string{
			"token": t,
		})
		//}
	}

	logrus.Infof("Unknown user or bad password for: %s", a.Username)
	return c.String(http.StatusUnauthorized, "Bad username or password")
}
开发者ID:hobeone,项目名称:rss2go,代码行数:34,代码来源:auth.go


示例9: Encode

func (ja *JwtAuth) Encode(claims Claims) (t *jwt.Token, tokenString string, err error) {
	t = jwt.New(ja.signer)
	t.Claims = claims
	tokenString, err = t.SignedString(ja.signKey)
	t.Raw = tokenString
	return
}
开发者ID:ustrajunior,项目名称:minion,代码行数:7,代码来源:jwtauth.go


示例10: 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


示例11: Login

/**

	TODO:
	- Get email and password from post request
	- Find user

**/
func (a *authController) Login(c *gin.Context) {
	var userLogin models.UserLogin
	if err := c.Bind(&userLogin); err != nil {
		panic(err)
	}
	user, err := authResource.Login(userLogin.Email, userLogin.Password)
	if err != nil {
		c.Error(err)
		return
	}
	token := jwt_lib.New(jwt_lib.GetSigningMethod("HS256"))
	// Set some claims
	token.Claims["exp"] = time.Now().Add(time.Hour * 1).Unix()
	// Sign and get the complete encoded token as a string
	apiKey, err := token.SignedString([]byte(config.GetSecret()))
	if err != nil {
		c.Error(apiErrors.ThrowError(apiErrors.ServerError))
		return
	}
	// Remove password
	user.Password = ""

	c.JSON(200, gin.H{
		"user":    user,
		"api-key": apiKey,
	})
}
开发者ID:oblank,项目名称:forum,代码行数:34,代码来源:auth.go


示例12: LoginHandler

//LoginHandler Hndler for login method
func LoginHandler(context *gin.Context, database *db.Context) {
	var model models.LoginModel
	err := context.BindJSON(&model)
	if err != nil {
		log.Println(err)
		context.AbortWithError(http.StatusBadRequest, err)
		return
	}
	user := database.FindUser(model.UserID)
	storedPassword, _ := base64.URLEncoding.DecodeString(user.Password)
	salt, _ := base64.URLEncoding.DecodeString(user.Salt)
	checkPassword, _ := util.GeneratePassword([]byte(model.Password), salt)
	if bytes.Compare(storedPassword, checkPassword) == 0 {
		token := jwt_lib.New(jwt_lib.GetSigningMethod("HS256"))
		token.Claims["ID"] = user.Username
		token.Claims["exp"] = time.Now().Add(time.Hour * 24).Unix()
		tokenString, err := token.SignedString([]byte(secret))
		if err != nil {
			context.JSON(500, gin.H{"message": "Could not generate token"})
			return
		}
		context.JSON(200, gin.H{"token": tokenString})
	} else {
		context.JSON(http.StatusUnauthorized, gin.H{"status": "Login or password is incorrect"})
	}
}
开发者ID:grffn,项目名称:movier,代码行数:27,代码来源:auth.go


示例13: generateIDToken

// http://openid.net/specs/openid-connect-core-1_0.html#IDToken
func (s *Server) generateIDToken(userData interface{}, client Client, scopesString string, nonce string, accessToken string) (string, error) {
	token := jwt.New(jwt.SigningMethodRS256)
	token.Claims["iss"] = s.Config.Issuer
	token.Claims["sub"] = userData.(User).GetSub()
	token.Claims["aud"] = client.GetId()
	token.Claims["iat"] = time.Now().Unix()
	token.Claims["nonce"] = nonce
	token.Claims["exp"] = time.Now().Add(time.Duration(s.Config.IDTokenExpiration) * time.Second).Unix()
	if accessToken != "" {
		hasher := sha256.New()
		io.WriteString(hasher, accessToken)
		sum := hasher.Sum(nil)
		accessTokenHash := base64.URLEncoding.EncodeToString(sum[0 : len(sum)/2])
		token.Claims["at_hash"] = accessTokenHash
	}
	scopes := strings.Split(scopesString, " ")
	for _, scope := range scopes {
		claims := s.ClaimManager.GetClaims(scope, userData)
		for k, v := range claims {
			token.Claims[k] = v
		}
	}
	// kid
	token.Header["kid"] = s.Config.JWTKeyID
	key, _ := jwt.ParseRSAPrivateKeyFromPEM(s.Config.JWTKey)
	a, err := token.SignedString(key)
	return a, err
}
开发者ID:observadorpt,项目名称:osin,代码行数:29,代码来源:idtoken.go


示例14: WithIdentity

// WithIdentity fills the context with token
// Token is filled using input Identity object
func WithIdentity(ctx context.Context, ident account.Identity) context.Context {
	token := jwt.New(jwt.SigningMethodRS256)
	token.Claims.(jwt.MapClaims)["sub"] = ident.ID.String()
	token.Claims.(jwt.MapClaims)["uuid"] = ident.ID.String()
	token.Claims.(jwt.MapClaims)["fullName"] = ident.User.FullName
	token.Claims.(jwt.MapClaims)["imageURL"] = ident.User.ImageURL
	return goajwt.WithJWT(ctx, token)
}
开发者ID:Ritsyy,项目名称:almighty-core,代码行数:10,代码来源:login.go


示例15: createJWTToken

// create a jwt token
func createJWTToken(serviceId string, backOffice bool, expires_in int64) (string, error) {
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims["service_id"] = serviceId
	token.Claims["expires_in"] = expires_in
	token.Claims["back_office"] = backOffice
	tokenString, err := token.SignedString([]byte(SigningKey))
	return tokenString, err
}
开发者ID:ownode,项目名称:ownode,代码行数:9,代码来源:auth.go


示例16: GenerateToken

// GenerateToken - generate Token string
func GenerateToken() string {
	token := jwt.New(jwt.GetSigningMethod("RS256"))
	token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
	tokenString, err := token.SignedString(signKey)
	fatal(err)

	return tokenString
}
开发者ID:gabz75,项目名称:env-auth-go,代码行数:9,代码来源:token.go


示例17: getValidAuthHeader

// getExpiredAuthHeader returns a valid JWT bearer token
func getValidAuthHeader(t *testing.T, key interface{}) string {
	token := jwt.New(jwt.SigningMethodRS256)
	tokenStr, err := token.SignedString(key)
	if err != nil {
		t.Fatal("Could not sign the token ", err)
	}
	return fmt.Sprintf("Bearer %s", tokenStr)
}
开发者ID:Ritsyy,项目名称:almighty-core,代码行数:9,代码来源:auth_utility_test.go


示例18: GenerateToken

// GenerateToken - generates a new Json Web Token based on the incoming user id.
func (jwt *JWT) GenerateToken(userName string) (string, error) {
	token := jwtgo.New(jwtgo.SigningMethodHS512)
	// Token expires in 10hrs.
	token.Claims["exp"] = time.Now().Add(time.Hour * tokenExpires).Unix()
	token.Claims["iat"] = time.Now().Unix()
	token.Claims["sub"] = userName
	return token.SignedString([]byte(jwt.SecretAccessKey))
}
开发者ID:yrashk,项目名称:minio,代码行数:9,代码来源:signature-jwt.go


示例19: Sign

// key is the secret key for encoding token
// claims is the infomation you want to store in token, usually, a user's name or more
// for example:
// user := map[string]interface{}{"name": "yourname"}
// token, err := jwt.Sign("yourkey", user)
// In neo, middlewares are runned before any route,
// so you need set Regions, otherwise every route gonna be verified by jwt
// check it here: http://ivpusic.github.io/neo/tutorials/2015/01/22/regions.html
func Sign(key string, claims map[string]interface{}) (string, error) {
	// Create the token
	token := jwt_go.New(jwt_go.SigningMethodHS256)
	// Set claims
	token.Claims = claims
	// Sign and get the complete encoded token as a string
	return token.SignedString([]byte(key))
}
开发者ID:diankong,项目名称:neomw,代码行数:16,代码来源:jwt.go


示例20: getJwtForUser

func (authen *Authen) getJwtForUser(userid string, username string, duration int, changePassword bool) (string, error) {
	userid = strings.ToLower(userid)
	token := jwt.New(jwt.SigningMethodHS512)
	token.Claims["userid"] = userid
	token.Claims["username"] = username
	token.Claims["cp"] = changePassword
	token.Claims["exp"] = time.Now().Add(time.Second * time.Duration(duration)).Unix()
	return token.SignedString(authen.privateKey)
}
开发者ID:tianhai82,项目名称:gae_authen,代码行数:9,代码来源:auth.go



注:本文中的github.com/dgrijalva/jwt-go.New函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang jwt-go.Parse函数代码示例发布时间:2022-05-23
下一篇:
Golang jwt-go.GetSigningMethod函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap