// decodeJWT decodes a JSON Web Token into a simple map
// http://openid.net/specs/draft-jones-json-web-token-07.html
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)
}
464965
func (g *CookieGenerator) DecodeToken(encrypted []byte) (*Cookie, error) {
	// if the client didn't send any Cookie, DecodeToken will be called with a nil-slice
	if len(encrypted) == 0 {
		return nil, nil
	}

	data, err := g.cookieProtector.DecodeToken(encrypted)
	if err != nil {
		return nil, err
	}
	t := &token{}
	rest, err := asn1.Unmarshal(data, t)
	if err != nil {
		return nil, err
	}
	if len(rest) != 0 {
		return nil, fmt.Errorf("rest when unpacking token: %d", len(rest))
	}
	cookie := &Cookie{
		RemoteAddr: decodeRemoteAddr(t.RemoteAddr),
		SentTime:   time.Unix(t.Timestamp, 0),
	}
	if len(t.OriginalDestConnectionID) > 0 {
		cookie.OriginalDestConnectionID = protocol.ConnectionID(t.OriginalDestConnectionID)
	}
	return cookie, nil
}
1172513
func JSON2Dot(r io.Reader) ([]byte, error) {
	g, err := decodeGraph(r)
	if err != nil {
		return nil, err
	}

	return g.Dot(nil), nil
}
321453
func (j *RS256JWTStrategy) Decode(ctx context.Context, token string) (*jwt.Token, error) {
	// Parse the token.
	parsedToken, err := jwt.Parse(token, func(t *jwt.Token) (interface{}, error) {
		if _, ok := t.Method.(*jwt.SigningMethodRSA); !ok {
			return nil, errors.Errorf("Unexpected signing method: %v", t.Header["alg"])
		}
		return &j.PrivateKey.PublicKey, nil
	})

	if err != nil {
		return parsedToken, errors.WithStack(err)
	} else if !parsedToken.Valid {
		return parsedToken, errors.WithStack(fosite.ErrInactiveToken)
	}

	return parsedToken, err
}
863638
func (e Response) JSON(decoder interface{}) (*interface{}, error) {
	defer e.Res.Body.Close()
	resp := &decoder
	err := json.NewDecoder(e.Res.Body).Decode(resp)
	return resp, err
}
909538
func (service *Service) JWTHandler(w http.ResponseWriter, r *http.Request) {

	err := r.ParseForm()
	if err != nil {
		log.Debug("Error parsing form: ", err)
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	requestedScopeParameter := r.FormValue("scope")
	audiences := strings.TrimSpace(r.FormValue("aud"))

	//First check if the user uses an existing jwt to authenticate and authorize itself
	idToken, err := oauth2.GetValidJWT(r, &service.jwtSigningKey.PublicKey)
	if err != nil {
		log.Warning(err)
		http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
		return
	}
	var tokenString string
	if idToken != nil {
		tokenString, err = service.createNewJWTFromParent(r, idToken, requestedScopeParameter, audiences)
	} else {
		//If no jwt was supplied, check if an old school access_token was used
		accessToken := r.Header.Get("Authorization")

		//Get the actual token out of the header (accept 'token ABCD' as well as just 'ABCD' and ignore some possible whitespace)
		accessToken = strings.TrimSpace(strings.TrimPrefix(accessToken, "token"))
		if accessToken == "" {
			http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
			return
		}

		oauthMgr := NewManager(r)
		var at *AccessToken
		at, err = oauthMgr.GetAccessToken(accessToken)
		if err != nil {
			log.Error(err)
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			return
		}
		if at == nil || at.IsExpired() {
			http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
			return
		}

		validity := parseValidity(r)

		tokenString, err = service.convertAccessTokenToJWT(r, at, requestedScopeParameter, audiences, validity)
	}
	if err == errUnauthorized {
		http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
		return
	}
	if err != nil {
		log.Error(err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-type", "application/jwt")
	w.Write([]byte(tokenString))
}
811640
func (c *Component) BuildJWT() (string, error) {
	if c.privateKey == nil {
		return "", nil
	}
	if c.Identity == nil {
		return "", nil
	}
	privPEM, err := security.PrivatePEM(c.privateKey)
	if err != nil {
		return "", err
	}
	return security.BuildJWT(c.Identity.ID, 20*time.Second, privPEM)
}
1230043
func (t Token) JwtID() string {
	if v, ok := t.Get(JwtIDKey); ok {
		return v.(string)
	}
	return ""
}
839664
func NewJWT(claims Claims, method crypto.SigningMethod) jwt.JWT {
	j, ok := New(claims, method).(*jws)
	if !ok {
		panic("jws.NewJWT: runtime panic: New(...).(*jws) != true")
	}
	j.sb[0].protected.Set("typ", "JWT")
	j.isJWT = true
	return j
}
1169604
func (b *BearerJWT) Token(username string) (string, error) {
	if b.Now == nil {
		b.Now = time.Now
	}
	return JWT(username, b.SharedSecret, b.Now)
}
412270
func decodeToken(encoded string) *oauth2.Token {
	t := new(oauth2.Token)
	f := strings.Fields(encoded)
	if len(f) > 0 {
		t.AccessToken = f[0]
	}
	if len(f) > 1 {
		t.RefreshToken = f[1]
	}
	if len(f) > 2 && f[2] != "0" {
		sec, err := strconv.ParseInt(f[2], 10, 64)
		if err == nil {
			t.Expiry = time.Unix(sec, 0)
		}
	}
	return t
}
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
}
597624
func parseToken(token string) (*tokenPayload, error) {
	parts := strings.Split(token, ".")

	length := len(parts)

	if length != 3 {
		return nil, fmt.Errorf("Expected JWT token to contain a header, a payload, and a signature.  Only received %d parts", length)
	}

	partToDecode := parts[1]

	// fmt.Printf("Decoding base64 value of %s\n", partToDecode)

	decodedPayload, err := base64.RawURLEncoding.DecodeString(partToDecode)

	if err != nil {
		return nil, fmt.Errorf("Unable to decode payload.  Decode error: %s", err)
	}

	// fmt.Printf("Decoded payload is %s\n", decodedPayload)

	var tokenPayload tokenPayload

	err = json.Unmarshal([]byte(decodedPayload), &tokenPayload)

	if err != nil {
		return nil, err
	}

	tokenPayload.EncodedToken = token

	return &tokenPayload, nil
}
126745
func NewJWT(secret string, jwksurl string) *JWT {
	return &JWT{
		Secret:  secret,
		Jwksurl: jwksurl,
		Now:     DefaultNowTime,
	}
}
1013850
func (d *decoder) decode() error {
	// The loop invariant is that the top of each d.vs stack
	// is where we try to unmarshal the next JSON value we see.
	for len(d.vs) > 0 {
		tok, err := d.tokenizer.Token()
		if err == io.EOF {
			return errors.New("unexpected end of JSON input")
		} else if err != nil {
			return err
		}

		switch {

		// Are we inside an object and seeing next key (rather than end of object)?
		case d.state() == '{' && tok != json.Delim('}'):
			key, ok := tok.(string)
			if !ok {
				return errors.New("unexpected non-key in JSON input")
			}
			someFieldExist := false
			for i := range d.vs {
				v := d.vs[i][len(d.vs[i])-1]
				if v.Kind() == reflect.Ptr {
					v = v.Elem()
				}
				var f reflect.Value
				if v.Kind() == reflect.Struct {
					f = fieldByGraphQLName(v, key)
					if f.IsValid() {
						someFieldExist = true
					}
				}
				d.vs[i] = append(d.vs[i], f)
			}
			if !someFieldExist {
				return fmt.Errorf("struct field for %q doesn't exist in any of %v places to unmarshal", key, len(d.vs))
			}

			// We've just consumed the current token, which was the key.
			// Read the next token, which should be the value, and let the rest of code process it.
			tok, err = d.tokenizer.Token()
			if err == io.EOF {
				return errors.New("unexpected end of JSON input")
			} else if err != nil {
				return err
			}

		// Are we inside an array and seeing next value (rather than end of array)?
		case d.state() == '[' && tok != json.Delim(']'):
			someSliceExist := false
			for i := range d.vs {
				v := d.vs[i][len(d.vs[i])-1]
				if v.Kind() == reflect.Ptr {
					v = v.Elem()
				}
				var f reflect.Value
				if v.Kind() == reflect.Slice {
					v.Set(reflect.Append(v, reflect.Zero(v.Type().Elem()))) // v = append(v, T).
					f = v.Index(v.Len() - 1)
					someSliceExist = true
				}
				d.vs[i] = append(d.vs[i], f)
			}
			if !someSliceExist {
				return fmt.Errorf("slice doesn't exist in any of %v places to unmarshal", len(d.vs))
			}
		}

		switch tok := tok.(type) {
		case string, json.Number, bool, nil:
			// Value.

			for i := range d.vs {
				v := d.vs[i][len(d.vs[i])-1]
				if !v.IsValid() {
					continue
				}
				err := unmarshalValue(tok, v)
				if err != nil {
					return err
				}
			}
			d.popAllVs()

		case json.Delim:
			switch tok {
			case '{':
				// Start of object.

				d.pushState(tok)

				frontier := make([]reflect.Value, len(d.vs)) // Places to look for GraphQL fragments/embedded structs.
				for i := range d.vs {
					v := d.vs[i][len(d.vs[i])-1]
					frontier[i] = v
					// TODO: Do this recursively or not? Add a test case if needed.
					if v.Kind() == reflect.Ptr && v.IsNil() {
						v.Set(reflect.New(v.Type().Elem())) // v = new(T).
					}
				}
				// Find GraphQL fragments/embedded structs recursively, adding to frontier
				// as new ones are discovered and exploring them further.
				for len(frontier) > 0 {
					v := frontier[0]
					frontier = frontier[1:]
					if v.Kind() == reflect.Ptr {
						v = v.Elem()
					}
					if v.Kind() != reflect.Struct {
						continue
					}
					for i := 0; i < v.NumField(); i++ {
						if isGraphQLFragment(v.Type().Field(i)) || v.Type().Field(i).Anonymous {
							// Add GraphQL fragment or embedded struct.
							d.vs = append(d.vs, []reflect.Value{v.Field(i)})
							frontier = append(frontier, v.Field(i))
						}
					}
				}
			case '[':
				// Start of array.

				d.pushState(tok)

				for i := range d.vs {
					v := d.vs[i][len(d.vs[i])-1]
					// TODO: Confirm this is needed, write a test case.
					//if v.Kind() == reflect.Ptr && v.IsNil() {
					//	v.Set(reflect.New(v.Type().Elem())) // v = new(T).
					//}

					// Reset slice to empty (in case it had non-zero initial value).
					if v.Kind() == reflect.Ptr {
						v = v.Elem()
					}
					if v.Kind() != reflect.Slice {
						continue
					}
					v.Set(reflect.MakeSlice(v.Type(), 0, 0)) // v = make(T, 0, 0).
				}
			case '}', ']':
				// End of object or array.
				d.popAllVs()
				d.popState()
			default:
				return errors.New("unexpected delimiter in JSON input")
			}
		default:
			return errors.New("unexpected token in JSON input")
		}
	}
	return nil
}
1115404
func (ts TokensService) Decode(token string) (Token, error) {
	segments := strings.Split(token, ".")
	if len(segments) != 3 {
		return Token{}, InvalidTokenError{fmt.Errorf("invalid number of segments in token (%d/3)", len(segments))}
	}

	claims, err := jwt.DecodeSegment(segments[1])
	if err != nil {
		return Token{}, InvalidTokenError{fmt.Errorf("claims cannot be decoded: %s", err)}
	}

	t := Token{}
	err = json.Unmarshal(claims, &t)
	if err != nil {
		return Token{}, InvalidTokenError{fmt.Errorf("token cannot be parsed: %s", err)}
	}

	return t, nil
}
720003
func isRequestJWT(r *http.Request) bool {
	return strings.HasPrefix(r.Header.Get("Authorization"), jwtAlgorithm)
}