// JWTPass retrieves the JWT signing password.
559134
func (app *App) JWTPass() string {
	pass := os.Getenv(jwtPass)
	if pass == "" {
		return "pass"
	}
	return pass
}
1330935
func UserJWT(userCB UserJWTHandler, sigCB SignatureHandler) Option {
	return func(o *Options) error {
		if userCB == nil {
			return ErrNoUserCB
		}
		if sigCB == nil {
			return ErrUserButNoSigCB
		}
		o.UserJWT = userCB
		o.SignatureCB = sigCB
		return nil
	}
}
40692
func (ar *AuthRemote) Sign(req []byte) ([]byte, error) {
	return ar.AuthSign(req, nil, ar.provider)
}
448928
func builtinJWTVerifyHS256(a ast.Value, b ast.Value) (ast.Value, error) {
	// Decode the JSON Web Token
	token, err := decodeJWT(a)
	if err != nil {
		return nil, err
	}

	// Process Secret input
	astSecret, err := builtins.StringOperand(b, 2)
	if err != nil {
		return nil, err
	}
	secret := string(astSecret)

	mac := hmac.New(sha256.New, []byte(secret))
	_, err = mac.Write([]byte(token.header + "." + token.payload))
	if err != nil {
		return nil, err
	}

	signature, err := token.decodeSignature()
	if err != nil {
		return nil, err
	}

	return ast.Boolean(hmac.Equal([]byte(signature), mac.Sum(nil))), nil
}
464810
func (soc *Socket) GetPlainPassword() (string, error) {
	s, err := soc.getString(C.ZMQ_PLAIN_PASSWORD, 1024)
	if n := len(s); n > 0 && s[n-1] == 0 {
		s = s[:n-1]
	}
	return s, err
}
778681
func hashPassword(password string) string {
	h := sha1.New()
	io.WriteString(h, password)
	return fmt.Sprintf("% x", h.Sum(nil))
}
198028
func (s *AuthServer) CheckPasswordWOToken(user string, password []byte) error {
	const errMsg = "invalid username or password"

	err := services.VerifyPassword(password)
	if err != nil {
		return trace.BadParameter(errMsg)
	}

	hash, err := s.GetPasswordHash(user)
	if err != nil && !trace.IsNotFound(err) {
		return trace.Wrap(err)
	}
	if trace.IsNotFound(err) {
		log.Debugf("Username %q not found, using fake hash to mitigate timing attacks.", user)
		hash = fakePasswordHash
	}

	if err = bcrypt.CompareHashAndPassword(hash, password); err != nil {
		log.Debugf("Password for %q does not match", user)
		return trace.BadParameter(errMsg)
	}

	return nil
}
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
}
605533
func JWTWithConfig(config JWTConfig) echo.MiddlewareFuncd {
	// Defaults
	if config.Skipper == nil {
		config.Skipper = DefaultJWTConfig.Skipper
	}
	if config.SigningKey == nil {
		panic("jwt middleware requires signing key")
	}
	if config.SigningMethod == "" {
		config.SigningMethod = DefaultJWTConfig.SigningMethod
	}
	if config.ContextKey == "" {
		config.ContextKey = DefaultJWTConfig.ContextKey
	}
	if config.Claims == nil {
		config.Claims = DefaultJWTConfig.Claims
	}
	if config.TokenLookup == "" {
		config.TokenLookup = DefaultJWTConfig.TokenLookup
	}
	config.keyFunc = func(t *jwt.Token) (interface{}, error) {
		// Check the signing method
		if t.Method.Alg() != config.SigningMethod {
			return nil, fmt.Errorf("unexpected jwt signing method=%v", t.Header["alg"])
		}
		return config.SigningKey, nil
	}

	// Initialize
	parts := strings.Split(config.TokenLookup, ":")
	extractor := jwtFromHeader(parts[1])
	switch parts[0] {
	case "query":
		extractor = jwtFromQuery(parts[1])
	case "cookie":
		extractor = jwtFromCookie(parts[1])
	}

	return func(next echo.Handler) echo.HandlerFunc {
		return func(c echo.Context) error {
			if config.Skipper(c) {
				return next.Handle(c)
			}

			auth, err := extractor(c)
			if err != nil {
				return echo.NewHTTPError(http.StatusBadRequest, err.Error())
			}
			token := new(jwt.Token)
			// Issue #647, #656
			if _, ok := config.Claims.(jwt.MapClaims); ok {
				token, err = jwt.Parse(auth, config.keyFunc)
			} else {
				claims := reflect.ValueOf(config.Claims).Interface().(jwt.Claims)
				token, err = jwt.ParseWithClaims(auth, claims, config.keyFunc)
			}
			if err == nil && token.Valid {
				// Store user information from token into context.
				c.Set(config.ContextKey, token)
				return next.Handle(c)
			}
			return echo.ErrUnauthorized
		}
	}
}
910760
func JWt(opts ...*SignOpts) fibre.MiddlewareFunc {
	return func(h fibre.HandlerFunc) fibre.HandlerFunc {
		return func(c *fibre.Context) error {

			var config *SignOpts

			switch len(opts) {
			case 0:
				return h(c)
			default:
				config = opts[0]
			}

			// This is a socket
			if c.IsSocket() {
				return h(c)
			}

			// No config has been set
			if len(config.Key) == 0 {
				return h(c)
			}

			head := c.Request().Header().Get(fibre.HeaderAuthorization)

			if head != "" && head[:6] == "Bearer" {

				token, err := jwt.Parse(head[7:], func(token *jwt.Token) (interface{}, error) {

					if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
						return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
					}

					return config.Key, nil

				})

				if err == nil && token.Valid {
					if config.Fnc != nil {
						if err := config.Fnc(c, token.Header, token.Claims.(jwt.MapClaims)); err != nil {
							return fibre.NewHTTPError(401)
						}
					}
					return h(c)
				}

			}

			return fibre.NewHTTPError(401)

		}
	}
}
384263
func DialPassword(password string) DialOption {
	return DialOption{func(do *dialOptions) {
		do.password = password
	}}
}
445505
func SHA512Pass(password string) (string, error) {
	c := sha512_crypt.New()
	return c.Generate([]byte(password), nil)
}
343234
func jwtFromHeader(header string, authScheme string) jwtExtractor {
	return func(c echo.Context) (string, error) {
		auth := c.Request().Header.Get(header)
		l := len(authScheme)
		if len(auth) > l+1 && auth[:l] == authScheme {
			return auth[l+1:], nil
		}
		return "", ErrJWTMissing
	}
}
1341599
func (secret *ServicePrincipalCertificateSecret) SignJwt(spt *ServicePrincipalToken) (string, error) {
	hasher := sha1.New()
	_, err := hasher.Write(secret.Certificate.Raw)
	if err != nil {
		return "", err
	}

	thumbprint := base64.URLEncoding.EncodeToString(hasher.Sum(nil))

	// The jti (JWT ID) claim provides a unique identifier for the JWT.
	jti := make([]byte, 20)
	_, err = rand.Read(jti)
	if err != nil {
		return "", err
	}

	token := jwt.New(jwt.SigningMethodRS256)
	token.Header["x5t"] = thumbprint
	x5c := []string{base64.StdEncoding.EncodeToString(secret.Certificate.Raw)}
	token.Header["x5c"] = x5c
	token.Claims = jwt.MapClaims{
		"aud": spt.inner.OauthConfig.TokenEndpoint.String(),
		"iss": spt.inner.ClientID,
		"sub": spt.inner.ClientID,
		"jti": base64.URLEncoding.EncodeToString(jti),
		"nbf": time.Now().Unix(),
		"exp": time.Now().Add(time.Hour * 24).Unix(),
	}

	signedString, err := token.SignedString(secret.PrivateKey)
	return signedString, err
}
1166045
func (auth *Auth) VerifyPassword(ctx context.Context, email, password string) (string, error) {
	resp, err := auth.client.VerifyPassword(&identitytoolkit.IdentitytoolkitRelyingpartyVerifyPasswordRequest{
		Email:    email,
		Password: password,
	}).Context(ctx).Do()
	if err != nil {
		return "", err
	}
	return resp.LocalId, nil
}
1327518
func (a *Authenticator) AuthenticatePassword(ctx context.Context, username, password string) (*authenticator.Response, bool, error) {
	identity, ok, err := a.getIdentity(username, password)
	if err != nil {
		return nil, false, err
	}
	if !ok {
		return nil, false, nil
	}

	return identitymapper.ResponseFor(a.mapper, identity)
}
289139
func jwtWrap(originalHandler http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		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, "", http.StatusUnauthorized)
			return
		}
		tokenClaims := token.Claims.(jwt.MapClaims)
		var url = strings.TrimPrefix(r.URL.Path, "/")
		var col = r.FormValue("col")
		// Call the API endpoint handler if authorization allows
		if tokenClaims[JWT_USER_ATTR] == JWT_USER_ADMIN {
			originalHandler(w, r)
			return
		}
		if !sliceContainsStr(tokenClaims[JWT_ENDPOINTS_ATTR], url) {
			http.Error(w, "", http.StatusUnauthorized)
			return
		} else if col != "" && !sliceContainsStr(tokenClaims[JWT_COLLECTIONS_ATTR], col) {
			http.Error(w, "", http.StatusUnauthorized)
			return
		}
		originalHandler(w, r)
	}
}