// Token returns a signed JWT containing the claims provided
330400
func Token(
	claims *Claims,
	signature *Signature,
	options *Options,
) (string, error) {

	mapclaims := jwt.MapClaims{
		"sub":   claims.Subject,
		"iss":   claims.Issuer,
		"email": claims.Email,
		"name":  claims.Name,
		"roles": claims.Roles,
		"iat":   time.Now().Add(-options.IATSubtract).Unix(),
		"exp":   options.Expiration,
	}
	if claims.Groups != nil {
		mapclaims["groups"] = claims.Groups
	}
	token := jwt.NewWithClaims(signature.Type, mapclaims)
	signedtoken, err := token.SignedString(signature.Key)
	if err != nil {
		return "", err
	}

	return signedtoken, nil
}
1131287
func (a *AltTokenSource) Token() (*oauth2.Token, error) {
	a.throttle.Accept()
	getTokenCounter.Inc()
	t, err := a.token()
	if err != nil {
		getTokenFailCounter.Inc()
	}
	return t, err
}
1079077
func ValidateJWT(token string, publicKey []byte) (*jwt.StandardClaims, error) {
	claims := &jwt.StandardClaims{}
	_, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodECDSA); !ok {
			return nil, fmt.Errorf("Unexpected JWT signing method: %v", token.Header["alg"])
		}
		key, err := jwt.ParseECPublicKeyFromPEM(publicKey)
		if err != nil {
			return nil, err
		}
		return key, nil
	})
	if err != nil {
		return nil, fmt.Errorf("Unable to verify JWT: %s", err.Error())
	}
	return claims, nil
}
598391
func Token(file string, cfg *oauth.Config) (*oauth.Transport, error) {
	if !filepath.IsAbs(file) {
		file = filepath.Join(os.Getenv("HOME"), file)
	}
	cfg1 := *cfg
	cfg = &cfg1
	cfg.TokenCache = oauth.CacheFile(file)
	tok, err := cfg.TokenCache.Token()
	if err == nil {
		return &oauth.Transport{Config: cfg, Token: tok}, nil
	}

	// Start HTTP server on localhost.
	l, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		var err1 error
		if l, err1 = net.Listen("tcp6", "[::1]:0"); err1 != nil {
			return nil, fmt.Errorf("oauthprompt.Token: starting HTTP server: %v", err)
		}
	}

	type done struct {
		err  error
		code string
	}
	ch := make(chan done, 100)

	randState, err := randomID()
	if err != nil {
		return nil, err
	}

	cfg.RedirectURL = "http://" + l.Addr().String() + "/done"
	authURL := cfg1.AuthCodeURL(randState)

	handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		if req.URL.Path == "/auth" {
			http.Redirect(w, req, authURL, 301)
			return
		}
		if req.URL.Path != "/done" {
			http.Error(w, "", 404)
			return
		}
		if req.FormValue("state") != randState {
			ch <- done{err: fmt.Errorf("oauthprompt.Token: incorrect response")}
			http.Error(w, "", 500)
			return
		}
		if code := req.FormValue("code"); code != "" {
			ch <- done{code: code}
			w.Write([]byte(success))
			return
		}
		http.Error(w, "", 500)
	})

	srv := &http.Server{Handler: handler}
	go srv.Serve(l)
	if err := openURL("http://" + l.Addr().String() + "/auth"); err != nil {
		l.Close()
		return nil, err
	}
	d := <-ch
	l.Close()

	if d.err != nil {
		return nil, err
	}

	tr := &oauth.Transport{Config: &cfg1}
	_, err = tr.Exchange(d.code)
	if err != nil {
		return nil, err
	}
	return tr, nil
}
1289537
func Token(r *http.Request) string {
	if val, err := contextGet(r, tokenKey); err == nil {
		if maskedToken, ok := val.(string); ok {
			return maskedToken
		}
	}

	return ""
}
603895
func (s *tokenServiceImpl) RegisterToken(ctx context.Context, identityID uuid.UUID, tokenString string, tokenType string,
	privileges []tokenrepo.TokenPrivilege) (*tokenrepo.Token, error) {

	// Parse the claims from the provided token string
	tokenClaims, err := s.tokenManager.ParseToken(ctx, tokenString)
	if err != nil {
		log.Error(ctx, map[string]interface{}{"error": err}, "invalid token string could not be parsed")
		return nil, errors.NewBadParameterErrorFromString("tokenString", tokenString,
			"invalid token string could not be parsed")
	}

	// Extract the id from the refresh token
	tokenID, err := uuid.FromString(tokenClaims.Id)
	if err != nil {
		log.Error(ctx, map[string]interface{}{"error": err}, "could not extract token ID from token string")
		return nil, errors.NewBadParameterErrorFromString("tokenString", tokenString,
			"could not extract token ID from token string")
	}

	expiryTime := time.Unix(tokenClaims.ExpiresAt, 0)

	tkn := &tokenrepo.Token{
		TokenID:    tokenID,
		IdentityID: identityID,
		Status:     0,
		TokenType:  tokenType,
		ExpiryTime: expiryTime,
	}

	// Persist the token record to the database
	err = s.ExecuteInTransaction(func() error {
		err = s.Repositories().TokenRepository().Create(ctx, tkn)
		if err != nil {
			return err
		}

		// If the access token is an RPT, register its permissions also
		if privileges != nil && len(privileges) > 0 {
			// Assign privileges to the token record, and persist them to the database
			for _, tokenPriv := range privileges {
				tokenPriv.TokenID = tokenID
				err = s.Repositories().TokenRepository().CreatePrivilege(ctx, &tokenPriv)
				if err != nil {
					return err
				}
			}
		}

		return nil
	})

	if err != nil {
		return nil, errors.NewInternalError(ctx, err)
	}

	return tkn, nil
}
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)
	}
}
907611
func (j *JwtAuthenticator) AuthenticateToken(ctx context.Context, rawtoken string) (*Claims, error) {

	// Parse token
	token, err := jwt.Parse(rawtoken, func(token *jwt.Token) (interface{}, error) {

		// Verify Method
		if strings.HasPrefix(token.Method.Alg(), "RS") {
			// RS256, RS384, or RS512
			return j.rsaKey, nil
		} else if strings.HasPrefix(token.Method.Alg(), "ES") {
			// ES256, ES384, or ES512
			return j.ecdsKey, nil
		} else if strings.HasPrefix(token.Method.Alg(), "HS") {
			// HS256, HS384, or HS512
			return j.sharedSecretKey, nil
		}
		return nil, fmt.Errorf("Unknown token algorithm: %s", token.Method.Alg())
	})
	if err != nil {
		return nil, err
	}

	if !token.Valid {
		return nil, fmt.Errorf("Token failed validation")
	}

	// Get claims
	claims, ok := token.Claims.(jwt.MapClaims)
	if claims == nil || !ok {
		return nil, fmt.Errorf("No claims found in token")
	}

	// Check for required claims
	for _, requiredClaim := range requiredClaims {
		if _, ok := claims[requiredClaim]; !ok {
			// Claim missing
			return nil, fmt.Errorf("Required claim %v missing from token", requiredClaim)
		}
	}

	// Token now has been verified.
	// Claims holds all the authorization information.
	// Here we need to first decode it then unmarshal it from JSON
	parts := strings.Split(token.Raw, ".")
	claimBytes, err := jwt.DecodeSegment(parts[1])
	if err != nil {
		return nil, fmt.Errorf("Failed to decode claims: %v", err)
	}
	var sdkClaims Claims
	err = json.Unmarshal(claimBytes, &sdkClaims)
	if err != nil {
		return nil, fmt.Errorf("Unable to get sdkclaims: %v", err)
	}

	if err := validateUsername(j.usernameClaim, &sdkClaims); err != nil {
		return nil, err
	}

	return &sdkClaims, nil
}
504491
func GetJWTToken(proj *v1alpha1.AppProject, roleName string, issuedAt int64) (*v1alpha1.JWTToken, int, error) {
	role, _, err := GetRoleByName(proj, roleName)
	if err != nil {
		return nil, -1, err
	}
	for i, token := range role.JWTTokens {
		if issuedAt == token.IssuedAt {
			return &token, i, nil
		}
	}
	return nil, -1, fmt.Errorf("JWT token for role '%s' issued at '%d' does not exist in project '%s'", role.Name, issuedAt, proj.Name)
}
535402
func (f JWTSigner) Sign(request *http.Request) error {
	request.Header.Set("Authorization", "Bearer "+f.Token)
	return nil
}
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)

		}
	}
}
911713
func (t TokenUnsealer) Token() (string, error) {
	r, err := vault.Request{goreq.Request{
		Uri:             vault.Path("/v1/auth/token/lookup-self", ""),
		MaxRedirects:    10,
		RedirectHeaders: true,
	}.WithHeader("X-Vault-Token", t.AuthToken)}.Do()
	if err == nil {
		defer r.Body.Close()
		switch r.StatusCode {
		case 200:
			return t.AuthToken, nil
		default:
			var e vault.Error
			e.Code = r.StatusCode
			if err := r.Body.FromJsonTo(&e); err == nil {
				return "", e
			} else {
				e.Errors = []string{"communication error."}
				return "", e
			}
		}
	} else {
		return "", err
	}
}
113500
func getClaimJWT(client *http.Client, url, accessToken string) (string, error) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// TODO: Allow passing request body with configurable information.
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return "", fmt.Errorf("while calling %v: %v", url, err)
	}
	if accessToken != "" {
		req.Header.Set("Authorization", fmt.Sprintf("Bearer %v", accessToken))
	}
	req = req.WithContext(ctx)
	response, err := client.Do(req)
	if err != nil {
		return "", err
	}
	// Report non-OK status code as an error.
	if response.StatusCode < http.StatusOK || response.StatusCode > http.StatusIMUsed {
		return "", fmt.Errorf("error while getting distributed claim JWT: %v", response.Status)
	}
	defer response.Body.Close()
	responseBytes, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return "", fmt.Errorf("could not decode distributed claim response")
	}
	return string(responseBytes), nil
}
225580
func TokenIssuer(rawtoken string) (string, error) {
	claims, err := TokenClaims(rawtoken)
	if err != nil {
		return "", err
	}

	// Return issuer
	if len(claims.Issuer) != 0 {
		return claims.Issuer, nil
	} else {
		return "", fmt.Errorf("Issuer was not specified in the token")
	}
}
1033255
func (spt *ServicePrincipalToken) Token() Token {
	spt.refreshLock.RLock()
	defer spt.refreshLock.RUnlock()
	return spt.inner.Token
}
744141
func Token(w http.ResponseWriter, r *http.Request, sess *sessions.Session) string {
	// Generate the map if it doesn't exist
	if _, ok := sess.Values[TokenName]; !ok {
		sess.Values[TokenName] = make(StringMap)
	}

	path := r.URL.Path

	if SingleToken {
		path = "/"
	}

	sessMap := sess.Values[TokenName].(StringMap)
	if _, ok := sessMap[path]; !ok {

		if len(sessMap) >= MaxTokens {
			for i, _ := range sessMap {
				delete(sessMap, i)
			}
		}

		sessMap[path] = generate(TokenLength)
		sess.Save(r, w)
	}

	return sessMap[path]
}
913583
func (c *tokenSource) Token() (*oauth2.Token, error) {
	return retrieveToken(c.ctx, c.conf, url.Values{
		"grant_type": {"client_credentials"},
		"scope":      internal.CondVal(strings.Join(c.conf.Scopes, " ")),
	})
}