本文整理汇总了Golang中github.com/dgrijalva/jwt-go.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了New函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
}
示例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)
}
示例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")
}
示例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
}
示例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!"})
// }
}
示例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
}
示例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
}
示例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")
}
示例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
}
示例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()
}
}
示例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,
})
}
示例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"})
}
}
示例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
}
示例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)
}
示例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
}