• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Golang jose.ParseJWT函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/coreos/go-oidc/jose.ParseJWT函数的典型用法代码示例。如果您正苦于以下问题:Golang ParseJWT函数的具体用法?Golang ParseJWT怎么用?Golang ParseJWT使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了ParseJWT函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: middleAuth

func middleAuth(server *Server) func(h echo.HandlerFunc) echo.HandlerFunc {
	return func(h echo.HandlerFunc) echo.HandlerFunc {
		return func(c *echo.Context) error {
			ah := c.Request().Header.Get(echo.Authorization)

			if len(ah) <= 6 || strings.ToUpper(ah[0:6]) != "BEARER" {
				return errors.New("should be a bearer token")
			}
			val := ah[7:]
			if len(val) == 0 {
				return errors.New("bearer token is empty")
			}
			jwt, err := jose.ParseJWT(val)
			if err != nil {
				return errors.New("failed to parse token")
			}
			usr, err := getUserFromJWT(jwt)
			if err != nil {
				return err
			}
			err = server.oidc.VerifyJWT(jwt, usr.ClientID)
			if err != nil {
				return err
			}
			c.Set("User", usr)
			return h(c)
		}
	}
}
开发者ID:otsimo,项目名称:distribution,代码行数:29,代码来源:http.go


示例2: getClientIDFromAuthorizedRequest

// getClientIDFromAuthorizedRequest will extract the clientID from the bearer token.
func getClientIDFromAuthorizedRequest(r *http.Request) (string, error) {
	rawToken, err := oidc.ExtractBearerToken(r)
	if err != nil {
		return "", err
	}

	jwt, err := jose.ParseJWT(rawToken)
	if err != nil {
		return "", err
	}

	claims, err := jwt.Claims()
	if err != nil {
		return "", err
	}

	sub, ok, err := claims.StringClaim("sub")
	if err != nil {
		return "", fmt.Errorf("failed to parse 'sub' claim: %v", err)
	} else if !ok || sub == "" {
		return "", errors.New("missing required 'sub' claim")
	}

	return sub, nil
}
开发者ID:jbagel2,项目名称:dex,代码行数:26,代码来源:auth_middleware.go


示例3: VerifiedIdentityFromContext

// Reads the OIDC JWT passed in the context and verifies it using the given OIDC client.
// Returns the verified identity on success, error otherwise.
func VerifiedIdentityFromContext(client *gooidc.Client, ctx context.Context) (*gooidc.Identity, error) {
	md, ok := metadata.FromContext(ctx)
	if !ok {
		return nil, errors.New("missing RPC credentials")
	}
	rawJWT, ok := md["jwt"]
	if !ok {
		return nil, errors.New("missing OIDC credentials")
	}
	if len(rawJWT) != 1 {
		return nil, errors.New("incorrect JWT data sent")
	}
	jwt, err := jose.ParseJWT(rawJWT[0])
	if err != nil {
		return nil, err
	}
	if err := client.VerifyJWT(jwt); err != nil {
		return nil, err
	}
	claims, err := jwt.Claims()
	if err != nil {
		return nil, err
	}
	return gooidc.IdentityFromClaims(claims)
}
开发者ID:polvi,项目名称:grpc-credentials,代码行数:27,代码来源:oidc.go


示例4: Refresh

func (r *idTokenRefresher) Refresh() (jose.JWT, error) {
	rt, ok := r.cfg[cfgRefreshToken]
	if !ok {
		return jose.JWT{}, errors.New("No valid id-token, and cannot refresh without refresh-token")
	}

	tokens, err := r.client.refreshToken(rt)
	if err != nil {
		return jose.JWT{}, fmt.Errorf("could not refresh token: %v", err)
	}
	jwt, err := jose.ParseJWT(tokens.IDToken)
	if err != nil {
		return jose.JWT{}, err
	}

	if tokens.RefreshToken != "" && tokens.RefreshToken != rt {
		r.cfg[cfgRefreshToken] = tokens.RefreshToken
	}
	r.cfg[cfgIDToken] = jwt.Encode()

	err = r.persister.Persist(r.cfg)
	if err != nil {
		return jose.JWT{}, fmt.Errorf("could not perist new tokens: %v", err)
	}

	return jwt, r.client.verifyJWT(jwt)
}
开发者ID:Q-Lee,项目名称:kubernetes,代码行数:27,代码来源:oidc.go


示例5: ValidateJWT

// Parses and validates a JWT token, based on the client definition provided.
func ValidateJWT(idToken string, client *oidc.Client) (jose.JWT, error) {

	jwt, err := jose.ParseJWT(idToken)
	if err != nil {
		return jose.JWT{}, err
	}

	return jwt, client.VerifyJWT(jwt)
}
开发者ID:paulharter,项目名称:sync_gateway,代码行数:10,代码来源:jwt.go


示例6: AuthenticateToken

// AuthenticateToken decodes and verifies an ID Token using the OIDC client, if the verification succeeds,
// then it will extract the user info from the JWT claims.
func (a *OIDCAuthenticator) AuthenticateToken(value string) (user.Info, bool, error) {
	jwt, err := jose.ParseJWT(value)
	if err != nil {
		return nil, false, err
	}

	client, err := a.client()
	if err != nil {
		return nil, false, err
	}
	if err := client.VerifyJWT(jwt); err != nil {
		return nil, false, err
	}

	claims, err := jwt.Claims()
	if err != nil {
		return nil, false, err
	}

	claim, ok, err := claims.StringClaim(a.usernameClaim)
	if err != nil {
		return nil, false, err
	}
	if !ok {
		return nil, false, fmt.Errorf("cannot find %q in JWT claims", a.usernameClaim)
	}

	var username string
	switch a.usernameClaim {
	case "email":
		// TODO(yifan): Check 'email_verified' to make sure the email is valid.
		username = claim
	default:
		// For all other cases, use issuerURL + claim as the user name.
		username = fmt.Sprintf("%s#%s", a.issuerURL, claim)
	}

	// TODO(yifan): Add UID, also populate the issuer to upper layer.
	info := &user.DefaultInfo{Name: username}

	if a.groupsClaim != "" {
		groups, found, err := claims.StringsClaim(a.groupsClaim)
		if err != nil {
			// Groups type is present but is not an array of strings, try to decode as a string.
			group, _, err := claims.StringClaim(a.groupsClaim)
			if err != nil {
				// Custom claim is present, but isn't an array of strings or a string.
				return nil, false, fmt.Errorf("custom group claim contains invalid type: %T", claims[a.groupsClaim])
			}
			info.Groups = []string{group}
		} else if found {
			info.Groups = groups
		}
	}
	return info, true, nil
}
开发者ID:eljefedelrodeodeljefe,项目名称:kubernetes,代码行数:58,代码来源:oidc.go


示例7: parseGrpcMetadata

func (s *grpcServer) parseGrpcMetadata(ctx context.Context, mustBeAdmin bool) (*GrpcClientInfo, error) {
	info := NewClientInfo()
	md, ok := metadata.FromContext(ctx)
	if !ok {
		return nil, fmt.Errorf("missing metadata")
	}
	//GET JWT
	var auth []string
	auth, ok = md["authorization"]

	if !ok || len(auth) == 0 {
		return nil, fmt.Errorf("missing authorization header")
	}

	ah := auth[0]
	if len(ah) <= 6 || strings.ToUpper(ah[0:6]) != "BEARER" {
		return nil, errors.New("should be a bearer token")
	}
	val := ah[7:]
	if len(val) == 0 {
		return nil, errors.New("bearer token is empty")
	}
	jwt, err := jose.ParseJWT(val)
	if err != nil {
		return nil, err
	}
	info.JWT = jwt

	//APP ID
	var devices []string
	devices, ok = md["device"]
	if !ok || len(devices) == 0 {
		return nil, fmt.Errorf("missing 'device' header")
	}
	dbytes, err := base64.StdEncoding.DecodeString(devices[0])
	if err != nil {
		return nil, err
	}
	device := &apipb.DeviceInfo{}
	err = device.Unmarshal(dbytes)
	if err != nil {
		return nil, err
	}
	info.Device = device

	//AUTH TOKEN
	id, email, err := s.authToken(jwt, mustBeAdmin)
	if err != nil {
		return nil, err
	}
	info.UserID = id
	info.Email = email
	info.State = GrpcClientInfoStateUnknown
	return info, nil
}
开发者ID:otsimo,项目名称:listener,代码行数:55,代码来源:auth.go


示例8: idToken

func (p *oidcAuthProvider) idToken() (string, error) {
	p.mu.Lock()
	defer p.mu.Unlock()

	if idToken, ok := p.cfg[cfgIDToken]; ok && len(idToken) > 0 {
		valid, err := verifyJWTExpiry(p.now(), idToken)
		if err != nil {
			return "", err
		}
		if valid {
			// If the cached id token is still valid use it.
			return idToken, nil
		}
	}

	// Try to request a new token using the refresh token.
	rt, ok := p.cfg[cfgRefreshToken]
	if !ok || len(rt) == 0 {
		return "", errors.New("No valid id-token, and cannot refresh without refresh-token")
	}

	tokens, err := p.client.refreshToken(rt)
	if err != nil {
		return "", fmt.Errorf("could not refresh token: %v", err)
	}
	jwt, err := jose.ParseJWT(tokens.IDToken)
	if err != nil {
		return "", err
	}

	if err := p.client.verifyJWT(&jwt); err != nil {
		return "", err
	}

	// Create a new config to persist.
	newCfg := make(map[string]string)
	for key, val := range p.cfg {
		newCfg[key] = val
	}

	if tokens.RefreshToken != "" && tokens.RefreshToken != rt {
		newCfg[cfgRefreshToken] = tokens.RefreshToken
	}

	newCfg[cfgIDToken] = tokens.IDToken
	if err = p.persister.Persist(newCfg); err != nil {
		return "", fmt.Errorf("could not perist new tokens: %v", err)
	}

	// Update the in memory config to reflect the on disk one.
	p.cfg = newCfg

	return tokens.IDToken, nil
}
开发者ID:kubernetes,项目名称:kubernetes,代码行数:54,代码来源:oidc.go


示例9: ParseTokenFromRequest

func ParseTokenFromRequest(r *http.Request) (token jose.JWT, err error) {
	ah := r.Header.Get("Authorization")
	if ah == "" {
		err = errors.New("missing Authorization header")
		return
	}

	if len(ah) <= 6 || strings.ToUpper(ah[0:6]) != "BEARER" {
		err = errors.New("should be a bearer token")
		return
	}

	return jose.ParseJWT(ah[7:])
}
开发者ID:jboeuf,项目名称:go-oidc,代码行数:14,代码来源:util.go


示例10: AuthenticateTrustedJWT

// Authenticates a user based on a JWT token obtained directly from a provider (auth code flow, refresh flow).
// Verifies the token claims, but doesn't require signature verification.
// If the token is validated but the user for the username defined in the subject claim doesn't exist,
// creates the user when autoRegister=true.
func (auth *Authenticator) AuthenticateTrustedJWT(token string, provider *OIDCProvider, callbackURLFunc OIDCCallbackURLFunc) (User, jose.JWT, error) {

	// Parse JWT
	jwt, err := jose.ParseJWT(token)
	if err != nil {
		base.LogTo("OIDC+", "Error parsing JWT in AuthenticateTrustedJWT: %v", err)
		return nil, jose.JWT{}, err
	}

	// Verify claims - ensures that the token we received from the provider is valid for Sync Gateway
	if err := oidc.VerifyClaims(jwt, provider.Issuer, *provider.ClientID); err != nil {
		return nil, jose.JWT{}, err
	}
	return auth.authenticateJWT(jwt, provider)
}
开发者ID:paulharter,项目名称:sync_gateway,代码行数:19,代码来源:auth.go


示例11: validateJWT

func (tkr *Tracker) validateJWT(jwtStr, infohash string) error {
	jwkSet := tkr.jwkSet
	if time.Now().After(jwkSet.validUntil) {
		return fmt.Errorf("Failed verify JWT due to stale JWK Set")
	}

	jwt, err := jose.ParseJWT(jwtStr)
	if err != nil {
		return err
	}

	validated, err := validateJWTSignature(&jwt, &jwkSet)
	if err != nil {
		return err
	} else if !validated {
		return errors.New("Failed to verify JWT with all available verifiers")
	}

	claims, err := jwt.Claims()
	if err != nil {
		return err
	}

	if claimedIssuer, ok, err := claims.StringClaim("iss"); claimedIssuer != jwkSet.Issuer || err != nil || !ok {
		return errors.New("Failed to validate JWT issuer claim")
	}

	if claimedAudience, ok, err := claims.StringClaim("aud"); claimedAudience != tkr.Config.JWTAudience || err != nil || !ok {
		return errors.New("Failed to validate JWT audience claim")
	}

	claimedInfohash, ok, err := claims.StringClaim("infohash")
	if err != nil || !ok {
		return errors.New("Failed to validate JWT infohash claim")
	}

	unescapedInfohash, err := url.QueryUnescape(claimedInfohash)
	if err != nil {
		return errors.New("Failed to unescape JWT infohash claim")
	}

	if unescapedInfohash != infohash {
		return errors.New("Failed to match infohash claim with requested infohash")
	}

	return nil
}
开发者ID:jzelinskie,项目名称:chihaya,代码行数:47,代码来源:jwt.go


示例12: RefreshToken

// RefreshToken uses a refresh token to exchange for a new OIDC JWT ID Token.
func (c *Client) RefreshToken(refreshToken string) (jose.JWT, error) {
	oac, err := c.OAuthClient()
	if err != nil {
		return jose.JWT{}, err
	}

	t, err := oac.RequestToken(oauth2.GrantTypeRefreshToken, refreshToken)
	if err != nil {
		return jose.JWT{}, err
	}

	jwt, err := jose.ParseJWT(t.IDToken)
	if err != nil {
		return jose.JWT{}, err
	}

	return jwt, c.VerifyJWT(jwt)
}
开发者ID:ryanj,项目名称:dex,代码行数:19,代码来源:client.go


示例13: ExchangeAuthCode

// Exchange an OAuth2 auth code for an OIDC JWT
func (c *Client) ExchangeAuthCode(code string) (jose.JWT, error) {
	oac, err := c.OAuthClient()
	if err != nil {
		return jose.JWT{}, err
	}

	t, err := oac.Exchange(code)
	if err != nil {
		return jose.JWT{}, err
	}

	jwt, err := jose.ParseJWT(t.IDToken)
	if err != nil {
		return jose.JWT{}, err
	}

	return jwt, c.VerifyJWT(jwt)
}
开发者ID:sym3tri,项目名称:go-oidc,代码行数:19,代码来源:client.go


示例14: ServeHTTP

func (l *TokenValidator) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	log.Info("validating")
	rawToken, err := oidc.ExtractBearerToken(r)
	if err != nil {
		log.Error("token.go: failed to get jwt from header")
		writeError(rw, http.StatusUnauthorized, "missing or invalid token")
		return
	}

	jwt, err := jose.ParseJWT(rawToken)
	if err != nil {
		log.Error("token.go: failed to parse jwt")
		writeError(rw, http.StatusUnauthorized, "missing or invalid token")
		return
	}

	err = l.accounts.Oidc.VerifyJWT(jwt)
	if err != nil {
		log.Errorf("token.go: Failed to verify signature: %v", err)
		writeError(rw, http.StatusUnauthorized, "invalid token")
	}

	claims, err := jwt.Claims()
	if err != nil {
		log.Error("token.go: failed to get claims", err)
		writeError(rw, http.StatusUnauthorized, "missing or invalid token")
		return
	}

	sub, ok, err := claims.StringClaim("sub")
	if err != nil {
		log.Errorf("token.go: failed to parse 'sub' claim: %v", err)
		writeError(rw, http.StatusUnauthorized, "missing or invalid token")
		return
	}
	if !ok || sub == "" {
		log.Error("token.go: missing required 'sub' claim")
		writeError(rw, http.StatusUnauthorized, "missing or invalid token")
		return
	}
	fmt.Println("token.go: verified token for", sub)
	r.Header.Set("sub", sub)
	next(rw, r)
}
开发者ID:otsimo,项目名称:accounts,代码行数:44,代码来源:token.go


示例15: handleCallbackFunc

func handleCallbackFunc(c *oidc.Client, claims *jose.Claims, refresh *string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		code := r.URL.Query().Get("code")
		if code == "" {
			phttp.WriteError(w, http.StatusBadRequest, "code query param must be set")
			return
		}

		oac, err := c.OAuthClient()
		if err != nil {
			phttp.WriteError(w, http.StatusInternalServerError, fmt.Sprintf("unable to create oauth client: %v", err))
			return
		}

		t, err := oac.RequestToken(oauth2.GrantTypeAuthCode, code)
		if err != nil {
			phttp.WriteError(w, http.StatusBadRequest, fmt.Sprintf("unable to verify auth code with issuer: %v", err))
			return
		}

		// Get id token and claims.
		tok, err := jose.ParseJWT(t.IDToken)
		if err != nil {
			phttp.WriteError(w, http.StatusBadRequest, fmt.Sprintf("unable to parse id_token: %v", err))
			return
		}

		if err := c.VerifyJWT(tok); err != nil {
			phttp.WriteError(w, http.StatusBadRequest, fmt.Sprintf("unable to verify the JWT: %v", err))
			return
		}

		if *claims, err = tok.Claims(); err != nil {
			phttp.WriteError(w, http.StatusBadRequest, fmt.Sprintf("unable to construct claims: %v", err))
			return
		}

		// Get refresh token.
		*refresh = t.RefreshToken

		w.WriteHeader(http.StatusOK)
	}
}
开发者ID:Tecsisa,项目名称:dex,代码行数:43,代码来源:oidc_test.go


示例16: parseAndVerifyTokenClaims

// Returns TokenClaims if and only if
// - the given token string is an appropriately formatted JWT
// - the JWT contains nonempty "aud" and "sub" claims
// - the JWT can be verified for the client associated with the "aud" claim
//   using the given keys
func parseAndVerifyTokenClaims(token string, issuer url.URL, keys []key.PublicKey) (TokenClaims, error) {
	jwt, err := jose.ParseJWT(token)
	if err != nil {
		return TokenClaims{}, err
	}

	claims, err := jwt.Claims()
	if err != nil {
		return TokenClaims{}, err
	}

	clientID, ok, err := claims.StringClaim("aud")
	if err != nil {
		return TokenClaims{}, err
	}
	if !ok || clientID == "" {
		return TokenClaims{}, errors.New("no aud(client ID) claim")
	}

	sub, ok, err := claims.StringClaim("sub")
	if err != nil {
		return TokenClaims{}, err
	}
	if !ok || sub == "" {
		return TokenClaims{}, errors.New("no sub claim")
	}

	noop := func() error { return nil }

	keysFunc := func() []key.PublicKey {
		return keys
	}

	verifier := oidc.NewJWTVerifier(issuer.String(), clientID, noop, keysFunc)
	if err := verifier.Verify(jwt); err != nil {
		return TokenClaims{}, err
	}

	timeClaimsToInt(claims)

	return TokenClaims{claims}, nil
}
开发者ID:Tecsisa,项目名称:dex,代码行数:47,代码来源:user.go


示例17: handleCallbackFunc

func handleCallbackFunc(c *oidc.Client) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		code := r.URL.Query().Get("code")
		if code == "" {
			phttp.WriteError(w, http.StatusBadRequest, "code query param must be set")
			return
		}

		tokens, err := exchangeAuthCode(c, code)
		if err != nil {
			phttp.WriteError(w, http.StatusBadRequest,
				fmt.Sprintf("unable to verify auth code with issuer: %v", err))
			return
		}

		tok, err := jose.ParseJWT(tokens.IDToken)
		if err != nil {
			phttp.WriteError(w, http.StatusBadRequest,
				fmt.Sprintf("unable to parse JWT: %v", err))
			return
		}

		claims, err := tok.Claims()
		if err != nil {
			phttp.WriteError(w, http.StatusBadRequest,
				fmt.Sprintf("unable to construct claims: %v", err))
			return
		}

		s := fmt.Sprintf(`
<html>
  <body>
    <p> Token: %v</p>
    <p> Claims: %v </p>
        <a href="/resend?jwt=%s">Resend Verification Email</a>
    <p> Refresh Token: %v </p>
  </body>
</html>`, tok.Encode(), claims, tok.Encode(), tokens.RefreshToken)
		w.Write([]byte(s))
	}
}
开发者ID:GamerockSA,项目名称:dex,代码行数:41,代码来源:main.go


示例18: ClientCredsToken

func (c *Client) ClientCredsToken(scope []string) (jose.JWT, error) {
	if !c.providerConfig.SupportsGrantType(oauth2.GrantTypeClientCreds) {
		return jose.JWT{}, fmt.Errorf("%v grant type is not supported", oauth2.GrantTypeClientCreds)
	}

	oac, err := c.OAuthClient()
	if err != nil {
		return jose.JWT{}, err
	}

	t, err := oac.ClientCredsToken(scope)
	if err != nil {
		return jose.JWT{}, err
	}

	jwt, err := jose.ParseJWT(t.IDToken)
	if err != nil {
		return jose.JWT{}, err
	}

	return jwt, c.VerifyJWT(jwt)
}
开发者ID:sym3tri,项目名称:go-oidc,代码行数:22,代码来源:client.go


示例19: verifyJWTExpiry

func verifyJWTExpiry(now time.Time, s string) (valid bool, err error) {
	jwt, err := jose.ParseJWT(s)
	if err != nil {
		return false, fmt.Errorf("invalid %q", cfgIDToken)
	}
	claims, err := jwt.Claims()
	if err != nil {
		return false, err
	}

	exp, ok, err := claims.TimeClaim("exp")
	switch {
	case err != nil:
		return false, fmt.Errorf("failed to parse 'exp' claim: %v", err)
	case !ok:
		return false, errors.New("missing required 'exp' claim")
	case exp.After(now.Add(expiryDelta)):
		return true, nil
	}

	return false, nil
}
开发者ID:kubernetes,项目名称:kubernetes,代码行数:22,代码来源:oidc.go


示例20: getJWTToken

func getJWTToken(ctx context.Context) (jose.JWT, error) {
	md, ok := metadata.FromContext(ctx)
	if !ok {
		return jose.JWT{}, fmt.Errorf("missing metadata")
	}
	var auth []string
	auth, ok = md["Authorization"]
	if !ok || len(auth) == 0 {
		return jose.JWT{}, fmt.Errorf("missing authorization header")
	}
	if len(auth) > 1 {
		return jose.JWT{}, fmt.Errorf("too many authorization header")
	}
	ah := auth[0]
	if len(ah) <= 6 || strings.ToUpper(ah[0:6]) != "BEARER" {
		return jose.JWT{}, errors.New("should be a bearer token")
	}
	val := ah[7:]
	if len(val) == 0 {
		return jose.JWT{}, errors.New("bearer token is empty")
	}
	return jose.ParseJWT(val)
}
开发者ID:otsimo,项目名称:accounts,代码行数:23,代码来源:grpc.go



注:本文中的github.com/coreos/go-oidc/jose.ParseJWT函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang jose.Claims类代码示例发布时间:2022-05-23
下一篇:
Golang jose.NewSignedJWT函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap