Example #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

}
Example #2
1
File: Mint.go Project: e-gov/fox
// GetToken wraps the incoming username into a TokenStruct, serializes the result to json
// and generates a Fernet token based on the resulting string
func GetToken(username string) string {
	// If the configuration has changed, re-load the keys
	if confVersion != util.GetConfig().Version {
		loadMintKey()
	}

	claims := jwt.StandardClaims{
		Issuer:    "FoxAuthn",
		Subject:   username,
		IssuedAt:  time.Now().Unix(),
		ExpiresAt: time.Now().Add(time.Duration(util.GetConfig().Authn.TokenTTL) * time.Second).Unix(),
	}

	log.WithFields(log.Fields{
		"claims": claims,
	}).Debug("Going to sign with these claims")

	token := jwt.NewWithClaims(jwt.SigningMethodRS384, claims)
	ss, err := token.SignedString(GetKey())
	if err != nil {
		log.WithFields(log.Fields{
			"path": mint.From,
		}).Panic("Failed to create signed token: ", err)
	}
	return ss
}
Example #3
0
// MakeToken will create a JWT token
func MakeToken() (newtoken string, err error) {

	// the current timestamp
	now := time.Now()

	claims := TokenClaims{
		jwt.StandardClaims{
			Issuer:    jwtIssuer,
			IssuedAt:  now.Unix(),
			NotBefore: now.Unix(),
			ExpiresAt: now.Add(time.Hour * 24 * jwtExpireDays).Unix(),
		},
	}

	// Create the token
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

	// set our header info
	token.Header[jwtHeaderKeyID] = 1

	secret, err := GetSecret()
	if err != nil {
		return
	}

	return token.SignedString(secret)

}
Example #4
0
func (t *AccessToken) JWT() (string, error) {
	now := time.Now().UTC()

	stdClaims := &jwt.StandardClaims{
		Id:        fmt.Sprintf("%s-%d", t.apiKey, now.Unix()),
		ExpiresAt: now.Add(t.ttl).Unix(),
		Issuer:    t.apiKey,
		IssuedAt:  now.Unix(),
		Subject:   t.accountSid,
	}
	if !t.NotBefore.IsZero() {
		stdClaims.NotBefore = t.NotBefore.UTC().Unix()
	}

	t.mu.Lock()
	defer t.mu.Unlock()
	claims := myCustomClaims{
		Grants:         t.grants,
		StandardClaims: stdClaims,
	}

	jwtToken := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	jwtToken.Header["cty"] = jwtContentType
	return jwtToken.SignedString(t.apiSecret)
}
Example #5
0
// Create JSON Web Token
func (c *Client) setToken(r *http.Request) error {

	// Create qsh hash
	qshstring := r.Method + "&" + r.URL.Path
	hash := sha256.New()
	hash.Write([]byte(qshstring))

	// Create Token
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		// Set issuer
		"iss": c.user,

		// Set issued at time
		"iat": time.Now().Unix(),

		// Set expiration
		"exp": time.Now().Add(time.Minute * 5).Unix(),

		// Set qsh
		"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
}
Example #6
0
func login(c echo.Context) error {
	username := c.FormValue("username")
	password := c.FormValue("password")

	if username == "jon" && password == "shhh!" {

		// Set custom claims
		claims := &jwtCustomClaims{
			"Jon Snow",
			true,
			jwt.StandardClaims{
				ExpiresAt: time.Now().Add(time.Hour * 72).Unix(),
			},
		}

		// Create token with claims
		token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

		// 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
}
Example #7
0
func genToken() (string, error) {
	tok := jwt.NewWithClaims(jwt.SigningMethodHS256, &jwt.StandardClaims{
		ExpiresAt: time.Now().Add(time.Hour * 72).Unix(),
		IssuedAt:  time.Now().Unix(),
		Subject:   "admin",
	})

	return tok.SignedString(signingKey)
}
Example #8
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
}
Example #9
0
// Create, sign, and output a token.  This is a great, simple example of
// how to use this library to create and sign a token.
func signToken() error {
	// get the token data from command line arguments
	tokData, err := loadData(*flagSign)
	if err != nil {
		return fmt.Errorf("Couldn't read token: %v", err)
	} else if *flagDebug {
		fmt.Fprintf(os.Stderr, "Token: %v bytes", len(tokData))
	}

	// parse the JSON of the claims
	var claims jwt.MapClaims
	if err := json.Unmarshal(tokData, &claims); err != nil {
		return fmt.Errorf("Couldn't parse claims JSON: %v", err)
	}

	// get the key
	var key interface{}
	key, err = loadData(*flagKey)
	if err != nil {
		return fmt.Errorf("Couldn't read key: %v", err)
	}

	// get the signing alg
	alg := jwt.GetSigningMethod(*flagAlg)
	if alg == nil {
		return fmt.Errorf("Couldn't find signing method: %v", *flagAlg)
	}

	// create a new token
	token := jwt.NewWithClaims(alg, claims)

	if isEs() {
		if k, ok := key.([]byte); !ok {
			return fmt.Errorf("Couldn't convert key data to key")
		} else {
			key, err = jwt.ParseECPrivateKeyFromPEM(k)
			if err != nil {
				return err
			}
		}
	}

	if out, err := token.SignedString(key); err == nil {
		fmt.Println(out)
	} else {
		return fmt.Errorf("Error signing token: %v", err)
	}

	return nil
}
Example #10
0
// Generate the twilio capability token. Deliver this token to your
// JS/iOS/Android Twilio client.
func (c *Capability) GenerateToken(ttl time.Duration) (string, error) {
	c.doBuildIncomingScope()
	c.doBuildOutgoingScope()
	now := time.Now().UTC()
	cc := &customClaim{
		Scope: strings.Join(c.capabilities, " "),
		StandardClaims: &jwt.StandardClaims{
			ExpiresAt: now.Add(ttl).Unix(),
			Issuer:    c.accountSid,
			IssuedAt:  now.Unix(),
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, cc)
	return token.SignedString([]byte(c.authToken))
}
Example #11
0
// signToken produces a JWT token signed with HS256. (HMAC-SHA256)
func (c *Casper) signToken(params map[string]string) (string, error) {
	t := time.Now().Unix()
	claims := jwt.MapClaims{
		"iat": t,
	}
	for k, v := range params {
		claims[k] = v
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	jwtString, err := token.SignedString([]byte(c.APISecret))
	if err != nil {
		return "", err
	}
	return jwtString, nil
}
Example #12
0
// GenerateToken - generates a new Json Web Token based on the incoming access key.
func (jwt *JWT) GenerateToken(accessKey string) (string, error) {
	// Trim spaces.
	accessKey = strings.TrimSpace(accessKey)

	if !isValidAccessKey(accessKey) {
		return "", errInvalidAccessKeyLength
	}

	tUTCNow := time.Now().UTC()
	token := jwtgo.NewWithClaims(jwtgo.SigningMethodHS512, jwtgo.MapClaims{
		// Token expires in 10hrs.
		"exp": tUTCNow.Add(jwt.expiry).Unix(),
		"iat": tUTCNow.Unix(),
		"sub": accessKey,
	})
	return token.SignedString([]byte(jwt.SecretAccessKey))
}
Example #13
0
// NewSigner will return a signer that can be used to sign tokens for a given
// set of claims.
func NewSigner(privateKeyBase64Str string) (Signer, error) {
	privateKey, err := DecodePrivateKey(privateKeyBase64Str)
	if err != nil {
		return nil, err
	}

	// This is the signer function that provides the support for signing tokens.
	f := func(claims map[string]interface{}) (string, error) {

		// Create the new JWT token with the ES384 signing method.
		token := jwt.NewWithClaims(jwt.SigningMethodES384, jwt.MapClaims(claims))

		// Actually sign the token.
		return token.SignedString(privateKey)
	}

	return f, nil
}
Example #14
0
func (k *Kontrol) registerUser(username, publicKey, privateKey string) (kiteKey string, err error) {
	claims := &kitekey.KiteClaims{
		StandardClaims: jwt.StandardClaims{
			Issuer:   k.Kite.Kite().Username,
			Subject:  username,
			IssuedAt: time.Now().Add(-k.tokenLeeway()).UTC().Unix(),
			Id:       uuid.NewV4().String(),
		},
		KontrolURL: k.Kite.Config.KontrolURL,
		KontrolKey: strings.TrimSpace(publicKey),
	}

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

	k.Kite.Log.Info("Registered machine on user: %s", username)

	return jwt.NewWithClaims(jwt.GetSigningMethod("RS256"), claims).SignedString(rsaPrivate)
}
Example #15
0
// MakeToken will create a JWT token
func MakeToken(secret string, uid uint) (newtoken string, err error) {

	// error if theres no secret set
	if secret == "" {
		err = e.ErrNoSecret
		return
	}

	// a token should never be created for these users
	if uid == 0 || uid == 1 {
		err = e.ErrUserNotValid
		return
	}

	// the current timestamp
	now := time.Now()

	claims := TokenClaims{
		uid,
		jwt.StandardClaims{
			Issuer:    jwtIssuer,
			IssuedAt:  now.Unix(),
			NotBefore: now.Unix(),
			ExpiresAt: now.Add(time.Hour * 24 * jwtExpireDays).Unix(),
		},
	}

	// Create the token
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

	// set our header info
	token.Header[jwtHeaderKeyID] = 1

	return token.SignedString([]byte(secret))

}
		issuer, err := cmd.Flags().GetString("issuer")
		if err != nil {
			ctx.WithError(err).Fatal("Could not read issuer ID")
		}

		var claims claims.ComponentClaims
		claims.Subject = args[1]
		claims.Type = args[0]
		claims.Issuer = issuer
		claims.IssuedAt = time.Now().Unix()
		claims.NotBefore = time.Now().Unix()
		if ttl > 0 {
			claims.ExpiresAt = time.Now().Add(time.Duration(ttl) * time.Hour * 24).Unix()
		}
		tokenBuilder := jwt.NewWithClaims(jwt.SigningMethodES256, claims)
		token, err := tokenBuilder.SignedString(privKey)
		if err != nil {
			ctx.WithError(err).Fatal("Could not sign JWT")
		}

		ctx.WithField("ID", args[0]).Info("Generated token")
		fmt.Println()
		fmt.Println(token)
		fmt.Println()
	},
}

func init() {
	discoveryCmd.AddCommand(discoveryAuthorizeCmd)
	discoveryAuthorizeCmd.Flags().Int("valid", 0, "The number of days the token is valid")