Esempio n. 1
2
// NewToken creates new JWT token for the gien username. It embedds the given
// public key as kontrolKey and signs the token with the private one.
func NewToken(username, private, public string) *jwt.Token {
	tknID := uuid.NewV4()

	hostname, err := os.Hostname()
	if err != nil {
		panic(err)
	}

	if username == "" {
		username = "******"
	}

	if testuser := os.Getenv("TESTKEY_USERNAME"); testuser != "" {
		username = testuser
	}

	claims := &kitekey.KiteClaims{
		StandardClaims: jwt.StandardClaims{
			Issuer:   "testuser",
			Subject:  username,
			Audience: hostname,
			IssuedAt: time.Now().UTC().Unix(),
			Id:       tknID.String(),
		},
		KontrolKey: public,
		KontrolURL: "http://localhost:4000/kite",
	}

	token := jwt.NewWithClaims(jwt.GetSigningMethod("RS256"), claims)

	rsaPrivate, err := jwt.ParseRSAPrivateKeyFromPEM([]byte(private))
	if err != nil {
		panic(err)
	}

	token.Raw, err = token.SignedString(rsaPrivate)
	if err != nil {
		panic(err)
	}

	// verify the token
	_, err = jwt.ParseWithClaims(token.Raw, claims, func(*jwt.Token) (interface{}, error) {
		return jwt.ParseRSAPublicKeyFromPEM([]byte(public))
	})

	if err != nil {
		panic(err)
	}

	token.Valid = true
	return token

}
Esempio n. 2
0
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
}
Esempio n. 3
0
File: auth.go Progetto: oblank/forum
/**

	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,
	})
}
Esempio n. 4
0
// New creates a JwtAuth authenticator instance that provides middleware handlers
// and encoding/decoding functions for JWT signing.
func New(alg string, signKey []byte, verifyKey []byte) *JwtAuth {
	return &JwtAuth{
		signKey:   signKey,
		verifyKey: verifyKey,
		signer:    jwt.GetSigningMethod(alg),
	}
}
Esempio n. 5
0
File: auth.go Progetto: grffn/movier
//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"})
	}
}
Esempio n. 6
0
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")
}
Esempio n. 7
0
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"] = "admin@tiedot"
	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()
	}
}
Esempio n. 8
0
// 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
}
Esempio n. 9
0
// NewWithParser is the same as New, except it supports custom parser settings
// introduced in ver. 2.4.0 of jwt-go
func NewWithParser(alg string, parser *jwt.Parser, signKey []byte, verifyKey []byte) *JwtAuth {
	return &JwtAuth{
		signKey:   signKey,
		verifyKey: verifyKey,
		signer:    jwt.GetSigningMethod(alg),
		parser:    parser,
	}
}
Esempio n. 10
0
func NewToken() tokenData {
	t := tokenData{}
	t.payload = make(map[string]interface{})

	// initialize every token with ecryption algorithm and expiration time
	t.encrytpionAlg = jwt.GetSigningMethod("RS256")
	t.expirationTimeToAdd = expTime
	return t
}
Esempio n. 11
0
func CreateTokenWithPayload(payload map[string]interface{}, privateKey interface{}) string {
	token := jwt.New(jwt.GetSigningMethod("RS256"))
	token.Claims = payload
	signed, err := token.SignedString(privateKey)
	if err != nil {
		log.Fatal("Failed to parse private key.", err)
	}
	return signed
}
Esempio n. 12
0
func handleLogin(w http.ResponseWriter, r *http.Request) {
	token := jwt.New(jwt.GetSigningMethod("RS256"))
	token.Claims["ID"] = "This is my super fake ID"
	token.Claims["exp"] = time.Now().Unix() + 30
	tokenString, _ := token.SignedString(privateKey)

	w.WriteHeader(http.StatusOK)
	fmt.Fprintf(w, `{"token": %s}`, tokenString)
}
Esempio n. 13
0
func CreateToken(hostUuid string, privateKey interface{}) string {
	token := jwt.New(jwt.GetSigningMethod("RS256"))
	token.Claims["hostUuid"] = hostUuid
	signed, err := token.SignedString(privateKey)
	if err != nil {
		log.Fatal("Failed to parse private key.", err)
	}
	return signed
}
Esempio n. 14
0
func (m *defaultSessionManager) createToken(userID int64) (string, error) {
	token := jwt.New(jwt.GetSigningMethod("RS256"))
	token.Claims["uid"] = strconv.FormatInt(userID, 10)
	token.Claims["exp"] = time.Now().Add(time.Minute * expiry).Unix()
	tokenString, err := token.SignedString(m.signKey)
	if err != nil {
		return tokenString, errgo.Mask(err)
	}
	return tokenString, nil
}
Esempio n. 15
0
func EncodeJwt(secret Secret, claims map[string]interface{}) (EncodedJwt, error) {
	if secret == "" {
		return "", nil
	}

	t := jwt.New(jwt.GetSigningMethod("HS256"))
	t.Claims = claims
	encoded, e := t.SignedString(secret)
	return EncodedJwt(encoded), e
}
Esempio n. 16
0
func EncodeJwt(secret Secret, claims *jwt.StandardClaims) (EncodedJwt, error) {
	if secret == "" {
		return "", nil
	}

	t := jwt.New(jwt.GetSigningMethod("HS256"))
	t.Claims = claims
	encoded, e := t.SignedString(secret)
	return EncodedJwt(encoded), e
}
Esempio n. 17
0
// createJWTToken generates the JWT token to be added to Request Headers
func createJWTToken(userID string) (string, error) {
	// Create the token
	token := jwt_lib.New(jwt_lib.GetSigningMethod("HS256"))
	// Set some claims
	token.Claims["ID"] = userID
	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(config.TokenSecret))
	return tokenString, err
}
Esempio n. 18
0
func makeRandomUserToken() (username string, tokenString string) {
	token := jwt.New(jwt.GetSigningMethod("HS256"))
	username, err := randutil.AlphaStringRange(5, 10)
	errPanic(err, "Cannot random string, wtf?")
	token.Claims["username"] = username
	token.Claims["secret"] = time.Now().Add(time.Hour * 72).Unix()
	tokenString, err = token.SignedString([]byte(mySigningKey))
	errPanic(err, "Cannot sign string, wtf?")
	return
}
Esempio n. 19
0
func (rp *relyingParty) generateAssertion() (string, error) {
	now := time.Now().Unix()
	token := jwt.New(jwt.GetSigningMethod("RS256"))
	token.Claims["iss"] = rp.cfg.ServiceAccountEmail
	token.Claims["scope"] = "https://www.googleapis.com/auth/identitytoolkit"
	token.Claims["aud"] = tokenEndpointURL
	token.Claims["lat"] = now
	token.Claims["exp"] = now + 3600
	return token.SignedString(rp.cfg.priKey)
}
Esempio n. 20
0
func PostTokenResource(c *gin.Context) {
	db := c.MustGet("db").(gorm.DB)
	config := c.MustGet("config").(models.Configuration)

	var user models.User

	c.Bind(&user)

	if (user.Username == "") || (user.Password == "") {
		response := make(map[string]string)
		response["error"] = "Incomplete submission."
		c.JSON(400, response)
	} else {
		var queryUser models.User

		db.Where("username = ?", user.Username).First(&queryUser)

		if queryUser.Username == "" {
			response := make(map[string]string)
			response["error"] = "Resource not found."
			c.JSON(404, response)
		} else {
			err := bcrypt.CompareHashAndPassword([]byte(queryUser.Password), []byte(user.Password))

			if err != nil {
				response := make(map[string]string)
				response["error"] = "Invalid credentials."
				c.JSON(401, response)
			} else {
				key, err := ioutil.ReadFile(config.Keys.Private)

				if err != nil {
					log.Fatal(err)
				}

				token := jwt.New(jwt.GetSigningMethod("RS256"))

				token.Claims["id"] = queryUser.Id

				expires := time.Now().Add(time.Hour * 72).UTC()

				token.Claims["life"] = expires.Format(time.RFC3339)

				tokenString, err := token.SignedString(key)

				response := make(map[string]string)
				response["token"] = tokenString
				response["expires"] = expires.String()

				c.JSON(200, response)
			}
		}
	}
}
Esempio n. 21
0
func GetToken(sp string) string {
	token := jwt.New(jwt.GetSigningMethod("HS256"))
	token.Claims["ID"] = "mujiburTest"
	token.Claims["exp"] = time.Now().Add(time.Hour * 1).Unix()
	ts, err := token.SignedString([]byte(sp))
	if err != nil {
		log.Printf("Error to get signed string: %v\n", err)
		return ""
	}
	return ts
}
Esempio n. 22
0
func createToken(w http.ResponseWriter, userID string) (string, error) {
	token := jwt.New(jwt.GetSigningMethod("RS256"))
	token.Claims["uid"] = userID
	token.Claims["exp"] = time.Now().Add(time.Minute * expiry).Unix()
	tokenString, err := token.SignedString(signKey)
	if err != nil {
		return "", err
	}
	w.Header().Set(tokenHeader, tokenString)
	return tokenString, nil
}
Esempio n. 23
0
// Verify user identity and hand out a JWT.
func getJWT(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	addCommonJwtRespHeaders(w, r)
	// Verify identity
	user := r.FormValue(JWT_USER_ATTR)
	if user == "" {
		http.Error(w, "Please pass JWT 'user' parameter", http.StatusBadRequest)
		return
	}
	jwtCol := HttpDB.Use(JWT_COL_NAME)
	if jwtCol == nil {
		http.Error(w, "Server is missing JWT identity collection, please restart the server.", http.StatusInternalServerError)
		return
	}
	userQuery := map[string]interface{}{
		"eq": user,
		"in": []interface{}{JWT_USER_ATTR}}
	userQueryResult := make(map[int]struct{})
	if err := db.EvalQuery(userQuery, jwtCol, &userQueryResult); err != nil {
		tdlog.CritNoRepeat("Query failed in JWT identity collection : %v", err)
		http.Error(w, "Query failed in JWT identity collection", http.StatusInternalServerError)
		return
	}
	// Verify password
	pass := r.FormValue(JWT_PASS_ATTR)
	for recID := range userQueryResult {
		rec, err := jwtCol.Read(recID)
		if err != nil {
			break
		}
		if rec[JWT_PASS_ATTR] != pass {
			tdlog.CritNoRepeat("JWT: identitify verification failed from request sent by %s", r.RemoteAddr)
			break
		}
		// Successful password match
		token := jwt.New(jwt.GetSigningMethod("RS256"))
		token.Claims = jwt.MapClaims{
			JWT_USER_ATTR:        rec[JWT_USER_ATTR],
			JWT_COLLECTIONS_ATTR: rec[JWT_COLLECTIONS_ATTR],
			JWT_ENDPOINTS_ATTR:   rec[JWT_ENDPOINTS_ATTR],
			JWT_EXPIRY:           time.Now().Add(time.Hour * 72).Unix(),
		}
		var tokenString string
		var e error
		if tokenString, e = token.SignedString(privateKey); e != nil {
			panic(e)
		}
		w.Header().Set("Authorization", "Bearer "+tokenString)
		w.WriteHeader(http.StatusOK)
		return
	}
	// ... password mismatch
	http.Error(w, "Invalid password", http.StatusUnauthorized)
}
Esempio n. 24
0
File: jwt.go Progetto: ngaut/beego
// CreateToken return the token
func CreateToken() map[string]string {
	log := logs.NewLogger(10000)
	log.SetLogger("console", "")

	token := goJwt.New(goJwt.GetSigningMethod("RS256")) // Create a Token that will be signed with RSA 256.
	token.Claims["ID"] = "This is my super fake ID"
	token.Claims["exp"] = time.Now().Unix() + 36000
	// The claims object allows you to store information in the actual token.
	tokenString, _ := token.SignedString(RSAKeys.PrivateKey)
	// tokenString Contains the actual token you should share with your client.
	return map[string]string{"token": tokenString}
}
Esempio n. 25
0
/*
Token path
*/
func Token(secretPassword string, claims map[string]interface{}) (string, error) {

	// Create the token
	token := jwt_lib.New(jwt_lib.GetSigningMethod("HS256"))

	// Set some claims
	token.Claims = claims
	token.Claims["exp"] = time.Now().Add(expirationTime()).Unix()

	// Sign and get the complete encoded token as a string
	return token.SignedString([]byte(secretPassword))
}
func GenerateToken(userTel string) (string, error) {
	token := jwt.New(jwt.GetSigningMethod("HS256"))
	token.Claims["exp"] = time.Now().Add(time.Hour * time.Duration(600)).Unix()
	token.Claims["iat"] = time.Now().Unix()
	token.Claims["sub"] = userTel
	tokenString, err := token.SignedString([]byte(secretKey))
	if err != nil {
		panic(err)
		return "", err
	}
	return tokenString, nil
}
Esempio n. 27
0
func generateToken(emailPrefix string) string {
	token := jwt.New(jwt.GetSigningMethod("HS256"))
	token.Claims["email"] = fmt.Sprintf("*****@*****.**", emailPrefix)
	token.Claims["exp"] = time.Now().Add(time.Minute * 100).Unix()
	token.Claims["groups"] = []string{"sre", "mcdev", "users"}

	tokenString, err := token.SignedString([]byte(secretKey))
	if err != nil {
		panic(err)
	}
	return tokenString
}
Esempio n. 28
0
// generateToken returns a JWT token string. Please see the URL for details:
// http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-13#section-4.1
func (k *Kontrol) generateToken(aud, username, issuer string, kp *KeyPair) (string, error) {
	uniqKey := aud + username + issuer + kp.ID

	k.tokenCacheMu.Lock()
	defer k.tokenCacheMu.Unlock()

	signed, ok := k.tokenCache[uniqKey]
	if ok {
		return signed, nil
	}

	rsaPrivate, err := jwt.ParseRSAPrivateKeyFromPEM([]byte(kp.Private))
	if err != nil {
		return "", err
	}

	now := time.Now().UTC()

	claims := &kitekey.KiteClaims{
		StandardClaims: jwt.StandardClaims{
			Issuer:    issuer,
			Subject:   username,
			Audience:  aud,
			ExpiresAt: now.Add(k.tokenTTL()).Add(k.tokenLeeway()).UTC().Unix(),
			IssuedAt:  now.Add(-k.tokenLeeway()).UTC().Unix(),
			Id:        uuid.NewV4().String(),
		},
	}

	if !k.TokenNoNBF {
		claims.NotBefore = now.Add(-k.tokenLeeway()).Unix()
	}

	signed, err = jwt.NewWithClaims(jwt.GetSigningMethod("RS256"), claims).SignedString(rsaPrivate)
	if err != nil {
		return "", errors.New("Server error: Cannot generate a token")
	}

	// cache our token
	k.tokenCache[uniqKey] = signed

	// cache invalidation, because we cache the token in tokenCache we need to
	// invalidate it expiration time. This was handled usually within JWT, but
	// now we have to do it manually for our own cache.
	time.AfterFunc(TokenTTL-TokenLeeway, func() {
		k.tokenCacheMu.Lock()
		defer k.tokenCacheMu.Unlock()

		delete(k.tokenCache, uniqKey)
	})

	return signed, nil
}
Esempio n. 29
0
func Auth(res http.ResponseWriter, req *http.Request) {
	token := jwt.New(jwt.GetSigningMethod("RS256"))

	token.Claims["ID"] = "This is my super fake ID"
	token.Claims["exp"] = time.Now().Unix() + 36000

	tokenString, _ := token.SignedString(privateKey)

	rt, _ := json.Marshal(Result{http.StatusOK, "Successful", tokenString})
	res.Header().Set("Content-Type", "application/json")
	res.WriteHeader(http.StatusOK)
	res.Write(rt)
}
Esempio n. 30
0
func (s *service) generateToken(user BaseUser) string {
	//This signing method must be the one that we validate below by calling `if _, ok := token.Method.(*jwt.SigningMethod`
	token := jwt.New(jwt.GetSigningMethod("RS256"))
	token.Claims["exp"] = time.Now().Add(time.Hour * time.Duration(s.jwtExpirationDeltaHours)).Unix()
	token.Claims["iat"] = time.Now().Unix()
	token.Claims["sub"] = user.UUID()
	tokenString, err := token.SignedString(s.privateKeyBytes)
	if err != nil {
		s.Logger.Error("Cannot generate JWT token: %s", err.Error())
		panic(s.ErrorsService.CreateClientError(http.StatusBadRequest, "[1442894957] Token error"))
	}
	return tokenString
}