本文整理汇总了Golang中github.com/coreos/go-oidc/jose.ParseJWT函数的典型用法代码示例。如果您正苦于以下问题:Golang ParseJWT函数的具体用法?Golang ParseJWT怎么用?Golang ParseJWT使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ParseJWT函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
}
}
}
示例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
}
示例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)
}
示例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)
}
示例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)
}
示例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
}
示例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
}
示例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
}
示例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:])
}
示例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)
}
示例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
}
示例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)
}
示例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)
}
示例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)
}
示例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)
}
}