grafana/pkg/services/authn/clients/basic.go
Karl Persson 2324597d8d
AuthN: Perform login with authn.Service (#61466)
* AuthN: Create password client wrapper and use that on in basic auth
client

* AuthN: fix basic auth client test

* AuthN: Add tests for form authentication

* API: Inject authn service

* Login: If authnService feature flag is enabled use authn login

* Login: Handle token creation errors
2023-01-17 09:11:45 +01:00

59 lines
1.3 KiB
Go

package clients
import (
"context"
"strings"
"github.com/grafana/grafana/pkg/services/authn"
"github.com/grafana/grafana/pkg/util"
"github.com/grafana/grafana/pkg/util/errutil"
)
var (
errDecodingBasicAuthHeader = errutil.NewBase(errutil.StatusBadRequest, "basic-auth.invalid-header", errutil.WithPublicMessage("Invalid Basic Auth Header"))
)
var _ authn.Client = new(Basic)
func ProvideBasic(client authn.PasswordClient) *Basic {
return &Basic{client}
}
type Basic struct {
client authn.PasswordClient
}
func (c *Basic) Authenticate(ctx context.Context, r *authn.Request) (*authn.Identity, error) {
username, password, err := util.DecodeBasicAuthHeader(getBasicAuthHeaderFromRequest(r))
if err != nil {
return nil, errDecodingBasicAuthHeader.Errorf("failed to decode basic auth header: %w", err)
}
return c.client.AuthenticatePassword(ctx, r, username, password)
}
func (c *Basic) Test(ctx context.Context, r *authn.Request) bool {
return looksLikeBasicAuthRequest(r)
}
func looksLikeBasicAuthRequest(r *authn.Request) bool {
return getBasicAuthHeaderFromRequest(r) != ""
}
func getBasicAuthHeaderFromRequest(r *authn.Request) string {
if r.HTTPRequest == nil {
return ""
}
header := r.HTTPRequest.Header.Get(authorizationHeaderName)
if header == "" {
return ""
}
if !strings.HasPrefix(header, basicPrefix) {
return ""
}
return header
}