Exemplo n.º 1
0
Arquivo: jwt.go Projeto: thanzen/hydra
// Verify a token and output the claims.
func (j *JWT) VerifyToken(tokenData []byte) (*jwt.Token, error) {
	// trim possible whitespace from token
	tokenData = regexp.MustCompile(`\s*$`).ReplaceAll(tokenData, []byte{})

	// Parse the token.  Load the key from command line option
	token, err := jwt.Parse(string(tokenData), 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 jwt.ParseRSAPublicKeyFromPEM(j.publicKey)
	})
	if err != nil {
		return nil, errors.Errorf("Couldn't parse token: %v", err)
	} else if !token.Valid {
		return nil, errors.Errorf("Token is invalid")
	}

	claims := ClaimsCarrier(token.Claims)
	if claims.AssertExpired() {
		token.Valid = false
		return token, errors.Errorf("Token expired: %v", claims.GetExpiresAt())
	}
	if claims.AssertNotYetValid() {
		token.Valid = false
		return token, errors.Errorf("Token is not valid yet: %v", claims.GetNotBefore())
	}
	return token, nil
}
Exemplo n.º 2
0
func PoliciesFromContext(ctx context.Context) ([]policy.Policy, error) {
	args, ok := ctx.Value(authKey).(*authorization)
	if !ok {
		return nil, errors.Errorf("Could not assert array type for %s", ctx.Value(authKey))
	}

	symbols := make([]policy.Policy, len(args.policies))
	for i, arg := range args.policies {
		symbols[i], ok = arg.(*policy.DefaultPolicy)
		if !ok {
			return nil, errors.Errorf("Could not assert policy type for %s", ctx.Value(authKey))
		}
	}

	return symbols, nil
}
Exemplo n.º 3
0
func SubjectFromContext(ctx context.Context) (string, error) {
	args, ok := ctx.Value(authKey).(*authorization)
	if !ok {
		return "", errors.Errorf("Could not assert type for %v", ctx.Value(authKey))
	}
	return args.claims.GetSubject(), nil
}
Exemplo n.º 4
0
func TokenFromContext(ctx context.Context) (*jwt.Token, error) {
	args, ok := ctx.Value(authKey).(*authorization)
	if !ok {
		return nil, errors.Errorf("Could not assert type for %v", ctx.Value(authKey))
	}
	return args.token, nil
}
Exemplo n.º 5
0
func (r *defaultRegistry) Find(id string) (Provider, error) {
	id = strings.ToLower(id)
	p, ok := r.providers[id]
	if !ok {
		return nil, errors.Errorf("Provider %s not found", id)
	}
	return p, nil
}
Exemplo n.º 6
0
Arquivo: jwt.go Projeto: thanzen/hydra
// Helper func: Read certificate from specified file
func LoadCertificate(path string) ([]byte, error) {
	if path == "" {
		return nil, errors.Errorf("No path specified")
	}

	var rdr io.Reader
	if f, err := os.Open(path); err == nil {
		rdr = f
		defer f.Close()
	} else {
		return nil, err
	}
	return ioutil.ReadAll(rdr)
}
Exemplo n.º 7
0
Arquivo: jwt.go Projeto: thanzen/hydra
func (j *JWT) GenerateAccessToken(data *osin.AccessData, generateRefresh bool) (accessToken string, refreshToken string, err error) {
	claims, ok := data.UserData.(ClaimsCarrier)
	if !ok {
		return "", "", errors.Errorf("Could not assert claims to ClaimsCarrier: %v", claims)
	}

	claims["exp"] = data.ExpireAt()
	if accessToken, err = j.SignToken(claims, map[string]interface{}{}); err != nil {
		return "", "", err
	} else if !generateRefresh {
		return
	}

	if refreshToken, err = j.SignToken(claims, map[string]interface{}{}); err != nil {
		return "", "", err
	}
	return
}
Exemplo n.º 8
0
func (h *Handler) authenticate(w http.ResponseWriter, r *http.Request, email, password string) (account.Account, error) {
	acc, err := h.Accounts.Authenticate(email, password)
	if err != nil {
		http.Error(w, "Could not authenticate.", http.StatusUnauthorized)
		return nil, err
	}

	policies, err := h.Policies.FindPoliciesForSubject(acc.GetID())
	if err != nil {
		http.Error(w, fmt.Sprintf("Could not fetch policies: %s", err.Error()), http.StatusInternalServerError)
		return nil, err
	}

	if granted, err := h.Guard.IsGranted("/oauth2/authorize", "authorize", acc.GetID(), policies, middleware.Env(r).Ctx()); !granted {
		err = errors.Errorf(`Subject "%s" is not allowed to authorize.`, acc.GetID())
		http.Error(w, err.Error(), http.StatusUnauthorized)
		return nil, err
	} else if err != nil {
		http.Error(w, fmt.Sprintf(`Authorization failed for Subject "%s": %s`, acc.GetID(), err.Error()), http.StatusInternalServerError)
		return nil, err
	}

	return acc, nil
}
Exemplo n.º 9
0
func (d *dropbox) Exchange(code string) (Session, error) {
	conf := *d.conf
	ctx := context.Background()
	token, err := conf.Exchange(ctx, code)
	if err != nil {
		return nil, err
	}

	if !token.Valid() {
		return nil, errors.Errorf("Token is not valid: %v", token)
	}

	c := conf.Client(ctx, token)
	rawurl := fmt.Sprintf("%s/%s?%s", d.api, "users/get_current_account", nil)
	response, err := c.Get(rawurl)
	if err != nil {
		return nil, err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return nil, err
	}

	var acc Account
	if err = json.Unmarshal(body, &acc); err != nil {
		return nil, err
	}

	return &DefaultSession{
		RemoteSubject: acc.ID,
		Extra:         acc,
		Token:         token,
	}, nil
}