// It returns the JWT token or an error.
182582
func (s *server) createToken(idt *lib.Identity) (string, error) {

	token := jwt.New(jwt.GetSigningMethod(s.p.signMethod))
	token.Claims["pid"] = idt.Pid
	token.Claims["idp"] = idt.Idp
	token.Claims["display_name"] = idt.DisplayName
	token.Claims["email"] = idt.Email
	token.Claims["iss"] = "localhost"
	token.Claims["exp"] = time.Now().Add(time.Second * 3600).UnixNano()

	tokenStr, err := token.SignedString([]byte(s.p.sharedSecret))
	if err != nil {
		return "", err
	}

	return tokenStr, nil
}
1306841
func parseVaultTokenFromJWT(token string) *string {
	if strings.Count(token, ".") != 2 {
		return nil
	}

	parsedJWT, err := squarejwt.ParseSigned(token)
	if err != nil {
		return nil
	}

	var claims squarejwt.Claims
	if err = parsedJWT.UnsafeClaimsWithoutVerification(&claims); err != nil {
		return nil
	}

	return &claims.ID
}
767496
func decodeJWT(jwt string) (map[string]interface{}, error) {
	jwtParts := strings.Split(jwt, ".")
	if len(jwtParts) != 3 {
		return nil, fmt.Errorf("invalid JSON Web Token: expected 3 parts, got %d", len(jwtParts))
	}

	// Re-pad, if needed
	encodedPayload := jwtParts[1]
	if l := len(encodedPayload) % 4; l != 0 {
		encodedPayload += strings.Repeat("=", 4-l)
	}

	// Decode base64url
	decodedPayload, err := base64.URLEncoding.DecodeString(encodedPayload)
	if err != nil {
		return nil, fmt.Errorf("error decoding payload: %v", err)
	}

	// Parse JSON
	return getJSON(decodedPayload)
}
526430
func (mw *GinJWTMiddleware) TokenGenerator(data interface{}) (string, time.Time, error) {
	token := jwt.New(jwt.GetSigningMethod(mw.SigningAlgorithm))
	claims := token.Claims.(jwt.MapClaims)

	if mw.PayloadFunc != nil {
		for key, value := range mw.PayloadFunc(data) {
			claims[key] = value
		}
	}

	expire := mw.TimeFunc().UTC().Add(mw.Timeout)
	claims["exp"] = expire.Unix()
	claims["orig_iat"] = mw.TimeFunc().Unix()
	tokenString, err := mw.signedString(token)
	if err != nil {
		return "", time.Time{}, err
	}

	return tokenString, expire, nil
}
720003
func isRequestJWT(r *http.Request) bool {
	return strings.HasPrefix(r.Header.Get("Authorization"), jwtAlgorithm)
}
587511
func (t *TokenRenewer) parse(tokenString string) error {
	claims := &kitekey.KiteClaims{}

	_, err := jwt.ParseWithClaims(tokenString, claims, t.localKite.RSAKey)
	if err != nil {
		valErr, ok := err.(*jwt.ValidationError)
		if !ok {
			return err
		}

		// do noy return for ValidationErrorSignatureValid. This is because we
		// might asked for a kite who's public Key is different what we have.
		// We still should be able to send them requests.
		if (valErr.Errors & jwt.ValidationErrorSignatureInvalid) == 0 {
			return fmt.Errorf("Cannot parse token: %s", err)
		}
	}

	t.validUntil = time.Unix(claims.ExpiresAt, 0).UTC()
	return nil
}
683422
func jwtFromQuery(param string) jwtExtractor {
	return func(c echo.Context) (string, error) {
		token := c.QueryParam(param)
		if token == "" {
			return "", ErrJWTMissing
		}
		return token, nil
	}
}
359819
func (c *JWTClaims) ToMap() map[string]interface{} {
	var ret = Copy(c.Extra)

	ret["jti"] = c.JTI
	if c.JTI == "" {
		ret["jti"] = uuid.New()
	}

	ret["sub"] = c.Subject
	ret["iss"] = c.Issuer
	ret["aud"] = c.Audience

	if !c.IssuedAt.IsZero() {
		ret["iat"] = float64(c.IssuedAt.Unix()) // jwt-go does not support int64 as datatype
	}

	if !c.NotBefore.IsZero() {
		ret["nbf"] = float64(c.NotBefore.Unix()) // jwt-go does not support int64 as datatype
	}

	ret["exp"] = float64(c.ExpiresAt.Unix()) // jwt-go does not support int64 as datatype

	if c.Scope != nil {
		ret["scp"] = c.Scope
	}

	return ret
}
297447
func jwtFromCookie(name string) jwtExtractor {
	return func(c echo.Context) (string, error) {
		token := c.GetCookie(name)
		if len(token) == 0 {
			return "", errors.New("empty jwt in cookie")
		}
		return token, nil
	}
}
1285111
func checkJWT(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	addCommonJwtRespHeaders(w, r)
	// Look for JWT in both headers and request value "access_token".
	token, err := request.ParseFromRequest(r, TokenExtractor{}, func(token *jwt.Token) (interface{}, error) {
		// Token was signed with RSA method when it was initially granted
		if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		return publicKey, nil
	})
	if err != nil || !token.Valid {
		http.Error(w, fmt.Sprintf("{\"error\": \"%s %s\"}", "JWT not valid,", err), http.StatusUnauthorized)
	} else {
		w.WriteHeader(http.StatusOK)
	}
}
413474
func (a *authenticator) getTokenStringFromRequest(req *http.Request) (result string, errCode int, err error) {
	// Try to read header, validate it if exists.
	authHeader := req.Header.Get(AuthHeaderKey)
	if authHeader != "" {
		bearerToken := strings.Split(authHeader, " ")
		if len(bearerToken) != 2 {
			return "", http.StatusUnauthorized, fmt.Errorf("401 Unauthorized: invalid authorization token")
		}
		// Parse token header constant
		if bearerToken[0] != "Bearer" {
			return "", http.StatusUnauthorized, fmt.Errorf("401 Unauthorized: invalid authorization header")
		}
		return bearerToken[1], 0, nil
	}
	a.log.Debugf("Authentication header not found (err: %v)", err)

	// Otherwise read cookie
	cookie, err := req.Cookie(cookieName)
	if err == nil && cookie != nil {
		return cookie.Value, 0, nil
	}
	a.log.Debugf("Authentication cookie not found (err: %v)", err)

	return "", http.StatusUnauthorized, fmt.Errorf("401 Unauthorized: authorization required")
}
578335
func (this *serviceImpl) get_token_from_header_query_param(req *http.Request) (*Token, error) {
	if this.settings.VerifyKeyFromHttpRequest == nil {
		return nil, ErrNoVerifyKey
	}
	t, err := jwt.ParseFromRequest(req, func(*jwt.Token) (interface{}, error) {
		return this.settings.VerifyKeyFromHttpRequest(req), nil
	})
	if err != nil {
		return nil, err
	}
	return this.check_token(t)
}
463258
func (f *jwtFilter) getKey(token *jwt.Token) (interface{}, error) {
	return f.publicKey, nil
}
17133
func decodeJWT(jwt string) (map[string]interface{}, error) {
	jwtParts := strings.Split(jwt, ".")
	if len(jwtParts) != 3 {
		return nil, errors.New("jws: invalid token received, not all parts available")
	}

	// Re-pad, if needed
	encodedPayload := jwtParts[1]
	if l := len(encodedPayload) % 4; l != 0 {
		encodedPayload += strings.Repeat("=", 4-l)
	}

	decodedPayload, err := base64.StdEncoding.DecodeString(encodedPayload)
	if err != nil {
		return nil, err
	}

	return unMarshal(decodedPayload)
}
958955
func (k *JSONWebKeySet) VerifyJWT(jwt string) (body []byte, err error) {
	chunks := strings.Split(jwt, ".")
	if len(chunks) != 3 {
		return nil, fmt.Errorf("bad JWT - expected 3 components separated by '.'")
	}

	// Check the header, grab the corresponding public key.
	var hdr struct {
		Alg string `json:"alg"`
		Kid string `json:"kid"`
	}
	if err := unmarshalB64JSON(chunks[0], &hdr); err != nil {
		return nil, fmt.Errorf("bad JWT header - %s", err)
	}
	if hdr.Alg != "RS256" {
		return nil, fmt.Errorf("bad JWT - only RS256 alg is supported, not %q", hdr.Alg)
	}
	if hdr.Kid == "" {
		return nil, fmt.Errorf("bad JWT - missing the signing key ID in the header")
	}
	pub, ok := k.keys[hdr.Kid]
	if !ok {
		return nil, fmt.Errorf("can't verify JWT - unknown signing key %q", hdr.Kid)
	}

	// Decode the signature.
	sig, err := base64.RawURLEncoding.DecodeString(chunks[2])
	if err != nil {
		return nil, fmt.Errorf("bad JWT - can't base64 decode the signature - %s", err)
	}

	// Check the signature. The signed string is "b64(header).b64(body)".
	hasher := sha256.New()
	hasher.Write([]byte(chunks[0]))
	hasher.Write([]byte{'.'})
	hasher.Write([]byte(chunks[1]))
	if err := rsa.VerifyPKCS1v15(&pub, crypto.SHA256, hasher.Sum(nil), sig); err != nil {
		return nil, fmt.Errorf("bad JWT - bad signature")
	}

	// Decode the body. There should be no errors here generally, the encoded body
	// is signed and the signature was already verified.
	body, err = base64.RawURLEncoding.DecodeString(chunks[1])
	if err != nil {
		return nil, fmt.Errorf("bad JWT - can't base64 decode the body - %s", err)
	}
	return body, nil
}
469748
func (e *Extractor) Extract(token *jwt.Token) (interface{}, error) {
	e.Token = token

	if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
		return nil, errors.New("invalid signing method")
	}

	claims, ok := token.Claims.(*KiteClaims)
	if !ok {
		return nil, fmt.Errorf("no kontrol key found")
	}

	e.Claims = claims

	return jwt.ParseRSAPublicKeyFromPEM([]byte(claims.KontrolKey))
}
1316287
func (a *authenticator) getTokenFor(credentials *credentials) (string, int, error) {
	name, errCode, err := a.validateCredentials(credentials)
	if err != nil {
		return "", errCode, err
	}
	claims := jwt.StandardClaims{
		Audience:  name,
		ExpiresAt: a.expTime.Nanoseconds(),
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString([]byte(signature))
	if err != nil {
		return "", http.StatusInternalServerError, fmt.Errorf("500 internal server error: failed to sign token: %v", err)
	}
	a.userDb.SetLoginTime(name)
	a.log.Debugf("user %s was logged in", name)

	return tokenString, 0, nil
}