Http: add pluggable authentication and token (#20066)
This commit is contained in:
parent
6f5c0b6478
commit
986772d525
6 changed files with 140 additions and 48 deletions
52
plugin/http_auth.go
Normal file
52
plugin/http_auth.go
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
package plugin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/evcc-io/evcc/plugin/auth"
|
||||
"github.com/evcc-io/evcc/util/transport"
|
||||
"github.com/jpfielding/go-http-digest/pkg/digest"
|
||||
)
|
||||
|
||||
// Auth is the authorization config
|
||||
type Auth struct {
|
||||
Type, User, Password, Token string
|
||||
|
||||
Source string
|
||||
Other map[string]any `mapstructure:",remain"`
|
||||
}
|
||||
|
||||
func (p *Auth) Transport(ctx context.Context, base http.RoundTripper) (http.RoundTripper, error) {
|
||||
switch strings.ToLower(p.Type) {
|
||||
case "digest":
|
||||
return digest.NewTransport(p.User, p.Password, base), nil
|
||||
|
||||
case "basic":
|
||||
return transport.BasicAuth(p.User, p.Password, base), nil
|
||||
|
||||
case "bearer":
|
||||
return transport.BearerAuth(p.Token, base), nil
|
||||
|
||||
default:
|
||||
if p.Source == "" {
|
||||
return nil, fmt.Errorf("unknown auth type '%s'", p.Type)
|
||||
}
|
||||
|
||||
if p.User != "" {
|
||||
p.Other["user"] = p.User
|
||||
}
|
||||
if p.Password != "" {
|
||||
p.Other["password"] = p.Password
|
||||
}
|
||||
|
||||
authorizer, err := auth.NewFromConfig(ctx, p.Source, p.Other)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return authorizer.Transport(base)
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue