security

package
v1.0.0-b8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 6, 2024 License: MIT Imports: 26 Imported by: 1

Documentation

Index

Constants

View Source
const (
	DefaultAnonymousAccess     = false
	DefaultAuthenticatedAccess = true
)
View Source
const (
	FormRealm = "Form"

	DefaultTemplate = "<!DOCTYPE html>" +
		"<html lang=\"en\">" +
		"<head>" +
		"    <meta charset=\"UTF-8\">" +
		"    <title>{{.Title}}</title>" +
		"</head>" +
		"<body>" +
		"<h2>{{.Header}}</h2>" +
		"{{.Error}}" +
		"<form action=\"{{.Action}}\" method=\"post\">" +
		"    <label for=\"{{.UsernameField}}\">{{.UsernameLabel}}</label><br>" +
		"    <input type=\"text\" id=\"{{.UsernameField}}\" name=\"{{.UsernameField}}\"><br>" +
		"    <label for=\"{{.PasswordField}}\">{{.PasswordLabel}}</label><br>" +
		"    <input type=\"password\" id=\"{{.PasswordField}}\" name=\"{{.PasswordField}}\"><br><br>" +
		"    <input type=\"hidden\" id=\"target\" name=\"{{.TargetField}}\" value=\"{{.Target}}\"><br><br>" +
		"    <input type=\"submit\" value=\"{{.SubmitLabel}}\">" +
		"</form>" +
		"</body>" +
		"</html>"

	DefaultAction          = "/login"
	DefaultTitle           = "Login"
	DefaultHeader          = "Login"
	DefaultUsernameField   = "username"
	DefaultPasswordField   = "password"
	DefaultTargetField     = "target"
	DefaultSubmitLabel     = "Login"
	DefaultUsernameLabel   = "Username:"
	DefaultPasswordLabel   = "Password:"
	DefaultErrorExpression = "<h1>Error: {{.Error}}</h1>"
)
View Source
const (
	AuthorizationCodeUrl = "%s?response_type=code%s&client_id=%s&redirect_uri=%s&state=%s"
	ScopesQueryParameter = "&scope=%s"

	UnsupportedKeyType    = err.ErrorF("unsupported key type: %s")
	ModulusDecodingError  = err.ErrorF("error decoding key %s modulus: %v")
	ExponentDecodingError = err.ErrorF("error decoding key %s exponent: %v")
	NoJwksUriError        = err.ErrorF("unable to refresh. no jwks uri provided")
	FailedToRefreshJwks   = err.ErrorF("failed to refresh jwks: %v")
	InvalidClainsError    = err.ErrorF("invalid claims: %s")
)
View Source
const (
	SSORealm                                 = "SSO"
	DefaultAuthorizationReplyHandlerEndpoint = "/sso/authorization"
	DefaultAuthenticatedEndpoint             = "/"
)
View Source
const BasicRealm = "Basic"
View Source
const BearerRealm = "Bearer"

Variables

View Source
var Anonymous = &User{}

Anonymous is a special user that is used to represent anonymous users. An authentication provider implementation may return the Anonymous user to indicate that the request is authenticated/allowed, but the user is not known. The authorization may still deny access to anonymous users.

View Source
var DefaultClaimsMapper = func(claims *jwt.MapClaims) (*User, error) {
	if claims == nil {
		return nil, InvalidClainsError.WithValues("no claims")
	}

	user := &User{Data: claims, Active: true}
	isType := true
	if value, found := (*claims)["sub"]; !found {
		return nil, InvalidClainsError.WithValues("claims has no subject")
	} else if user.OriginId, isType = value.(string); !isType {
		return nil, InvalidClainsError.WithValues("subject is not a string")
	}
	user.Username = user.OriginId
	if value, found := (*claims)["iss"]; found {
		if user.Origin, isType = value.(string); !isType {
			return nil, InvalidClainsError.WithValues("issuer is not a string")
		}
	}
	if value, found := (*claims)["scope"]; found {
		var e error
		user.Scopes, e = translateScopes(value)
		if e != nil {
			return nil, e
		}
	}

	return user, nil
}
View Source
var UserAttributeName = "WE-SEC-USER"

Functions

This section is empty.

Types

type AuthenticatedSecurityFilterBuilder

type AuthenticatedSecurityFilterBuilder interface {
	Path(paths ...string) AuthenticatedAuthorizationBuilder
	OnAuthentication(triggers ...func(*User, we.RequestScope)) AuthenticatedSecurityFilterBuilder
	Build() we.Filter
}

type AuthenticationProvider

type AuthenticationProvider interface {
	// Authenticate Tries to authenticate the incoming request. Each provider should extract from the incoming request
	// the information required to authenticate it. If none of the required attributes are present in the request, then the
	// provider should return a nil user and no error. If the request does have authentication credentials, and they
	// cannot be validated, then it should return an error. Successful authentication returns a user object and no error.
	Authenticate(headers http.Header, scope we.RequestScope) (*User, error)
	// Realm returns the provider authentication realm. Each provider should authenticate users for a distinct realm
	// within the same application. This realm is used to identify the authentication provider when checking if the user
	// is still value
	Realm() string
	// IsValid checks if the provided user is still authenticated
	IsValid(user *User) bool
	// Challenge returns the authentication challenge to be sent to the client with WWW-Authenticate header. It should not
	// contain the realm, which is added by the filter. An empty challenge means that the provider does not produce
	// WWW-Authenticate response headers
	Challenge() string
	// Endpoints are specific endpoints the authorization provider reports as being handled by the filter also, regardless
	// if they fall under any specific path they are authenticating. Typically they will only report endpoints used
	// in SSO or login form authenticators
	Endpoints() []string
}

AuthenticationProvider is an interface for authentication provider implementations. Authentication providers can be addedto a security filter to provider users that will be added to the request scope.

type Authorization

type Authorization interface {
	IsAuthorized(*User, we.RequestScope) bool
}

func All

func All(authorizations ...Authorization) Authorization

func Either

func Either(authorizations ...Authorization) Authorization

type AuthorizationCodeProvider

type AuthorizationCodeProvider interface {
	AuthorizationUrl(replyHandlerUrl, state string) string
	State(*http.Request) (state string, accessCode string)
	ValidateAuthorizationCode(code, replyHandlerUrl string) (*User, error)
}

type AuthorizationFunc

type AuthorizationFunc func(*User, we.RequestScope) bool

func (AuthorizationFunc) IsAuthorized

func (f AuthorizationFunc) IsAuthorized(user *User, scope we.RequestScope) bool

type BasicAuthenticationProviderBuilder

type BasicAuthenticationProviderBuilder interface {
	Realm(string) BasicAuthenticationProviderBuilder
	CredentialsProvider(CredentialsProvider) BasicAuthenticationProviderBuilder
	Build() AuthenticationProvider
}

func BasicAuthenticationProvider

func BasicAuthenticationProvider(users ...User) BasicAuthenticationProviderBuilder

type BearerAndSsoProvider

type BearerAndSsoProvider interface {
	TokenIntrospector
	AuthorizationCodeProvider
	TokenIntrospector() TokenIntrospector
	AuthorizationCodeProvider() AuthorizationCodeProvider
}

type ClaimsMapper

type ClaimsMapper func(claims *jwt.MapClaims) (*User, error)

type CredentialsProvider

type CredentialsProvider interface {
	Authenticate(username, password string) (*User, error)
	Get(username string) *User
}

func DefaultCredentialsProvider

func DefaultCredentialsProvider(users ...User) CredentialsProvider

type CredentialsSource

type CredentialsSource interface {
	CredentialsProvider
	Add(User) *User
	Delete(string) *User
}

func InMemoryCredentialsProvider

func InMemoryCredentialsProvider(credentials ...User) CredentialsSource

type JwKey

type JwKey struct {
	Id        string   `json:"kid"`
	Type      string   `json:"kty"`
	Algorithm string   `json:"alg"`
	Use       string   `json:"use"`
	Modulus   string   `json:"n"`
	Exponent  string   `json:"e"`
	X5TS256   string   `json:"x5t#S256,omitempty"`
	X5T       string   `json:"x5t,omitempty"`
	X5C       []string `json:"x5c,omitempty"`
}

JwKey represents a json web key for RSA keys (at the moment only RSA keys are supported)

type JwKeys

type JwKeys struct {
	Keys []JwKey `json:"keys"`
}

type LoginForm

type LoginForm interface {
	Generate(error string, target string) string
	Configuration() *LoginFormConfiguration
}

func CustomLoginForm

func CustomLoginForm(configuration LoginFormConfiguration, customTemplate string) LoginForm

func DefaultLoginForm

func DefaultLoginForm(configuration LoginFormConfiguration) LoginForm

type LoginFormConfiguration

type LoginFormConfiguration struct {
	Action        string
	UsernameLabel string
	PasswordLabel string
	SubmitLabel   string
	UsernameField string
	PasswordField string
	TargetField   string
	Target        string
	Title         string
	Header        string
	Error         string
}

type OpenIdConfiguration

type OpenIdConfiguration struct {
	Issuer                                     string   `json:"issuer"`
	AuthorizationEndpoint                      string   `json:"authorization_endpoint"`
	TokenEndpoint                              string   `json:"token_endpoint"`
	TokenEndpointAuthMethodsSupported          []string `json:"token_endpoint_auth_methods_supported"`
	TokenEndpointAuthSigningAlgValuesSupported []string `json:"token_endpoint_auth_signing_alg_values_supported"`
	UserinfoEndpoint                           string   `json:"userinfo_endpoint"`
	JwksUri                                    string   `json:"jwks_uri"`
	EndSessionEndpoint                         string   `json:"end_session_endpoint"`
	ScopesSupported                            []string `json:"scopes_supported"`
	ResponseTypesSupported                     []string `json:"response_types_supported"`
	SubjectTypesSupported                      []string `json:"subject_types_supported"`
	IdTokenSigningAlgValuesSupported           []string `json:"id_token_signing_alg_values_supported"`
	IdTokenEncryptionAlgValuesSupported        []string `json:"id_token_encryption_alg_values_supported"`
	ClaimTypesSupported                        []string `json:"claim_types_supported"`
	ClaimsSupported                            []string `json:"claims_supported"`
	ClaimsParameterSupported                   bool     `json:"claims_parameter_supported"`
	ServiceDocumentation                       string   `json:"service_documentation"`
	UiLocalesSupported                         []string `json:"ui_locales_supported"`
	CodeChallengeMethodsSupported              []string `json:"code_challenge_methods_supported"`
}

type OpenIdIdentityProviderBuilder

type OpenIdIdentityProviderBuilder interface {
	OpenIdConfigurationEndpoint(path string) OpenIdIdentityProviderBuilder
	IntrospectionEndpoint(path string) OpenIdIdentityProviderBuilder
	UserEnrichment(function UserEnrichmentFunction) OpenIdIdentityProviderBuilder
	TokenEndpoint(path string) OpenIdIdentityProviderBuilder
	JwksEndpoint(path string) OpenIdIdentityProviderBuilder
	Jwks(jwks []JwKey) OpenIdIdentityProviderBuilder
	JwtValidationFallback(fallbackToIntrospection bool) OpenIdIdentityProviderBuilder
	ClaimsMapper(mapper ClaimsMapper) OpenIdIdentityProviderBuilder
	Scope(scope ...string) OpenIdIdentityProviderBuilder
	Client(client, secret string) OpenIdIdentityProviderBuilder
	Tls(config *tls.Config) OpenIdIdentityProviderBuilder
	Build() BearerAndSsoProvider
}

func OpenIdIdentityProvider

func OpenIdIdentityProvider(openIdUrl string) OpenIdIdentityProviderBuilder

type Origin

type Origin string

func (Origin) IsAuthorized

func (o Origin) IsAuthorized(user *User, _ we.RequestScope) bool

type Realm

type Realm string

func (Realm) IsAuthorized

func (r Realm) IsAuthorized(user *User, _ we.RequestScope) bool

type SSOAuthenticationProviderBuilder

type SSOAuthenticationProviderBuilder interface {
	RedirectToRequestedUrl(redirect bool) SSOAuthenticationProviderBuilder
	Address(string) SSOAuthenticationProviderBuilder
	DynamicAddress(dynamic bool) SSOAuthenticationProviderBuilder
	DefaultAuthenticatedEndpoint(string) SSOAuthenticationProviderBuilder
	Realm(string) SSOAuthenticationProviderBuilder
	AuthorizationCodeProvider(AuthorizationCodeProvider) SSOAuthenticationProviderBuilder
	AuthorizationReplyHandler(string) SSOAuthenticationProviderBuilder
	Build() AuthenticationProvider
}

func SSOAuthenticationProvider

func SSOAuthenticationProvider() SSOAuthenticationProviderBuilder

type Scope

type Scope string

func (Scope) IsAuthorized

func (s Scope) IsAuthorized(user *User, _ we.RequestScope) bool

type TokenData

type TokenData struct {
	Raw           string
	Claims        *jwt.MapClaims
	Introspection *TokenIntrospection
}

type TokenIntrospection

type TokenIntrospection struct {
	Raw        []byte         `json:"-"`
	RawMap     map[string]any `json:"-"`
	Active     bool           `json:"active"`
	Scope      any            `json:"scope"`
	Scopes     []string       `json:"-"`
	ClientId   string         `json:"client_id"`
	Username   string         `json:"username"`
	Type       string         `json:"token_type"`
	Expiration int64          `json:"exp"`
	Issued     int64          `json:"iat"`
	Starting   int64          `json:"nbf"`
	Subject    string         `json:"sub"`
	Audience   any            `json:"aud"`
	Audiences  []string       `json:"-"`
	Issuer     string         `json:"iss"`
	TokenId    string         `json:"jti"`
}

type TokenIntrospector

type TokenIntrospector interface {
	Introspect(token string) (*User, error)
}

TokenIntrospector allows introspecting a bearer token and return a user for it. If there are no means to translate the token to a user, an error must be returned.

type TokenResponse

type TokenResponse struct {
	AccessToken  string `json:"access_token"`
	TokenType    string `json:"token_type"`
	ExpiresIn    int    `json:"expires_in"`
	RefreshToken string `json:"refresh_token"`
}

type UnauthenticatedSecurityFilterBuilder

type UnauthenticatedSecurityFilterBuilder interface {
	Authentication(...AuthenticationProvider) AuthenticatedSecurityFilterBuilder
	OnAuthentication(triggers ...func(*User, we.RequestScope)) UnauthenticatedSecurityFilterBuilder
	Path(paths ...string) UnauthenticatedAuthorizationBuilder
	Build() we.Filter
}

func Filter

func Filter(restricted bool) UnauthenticatedSecurityFilterBuilder

type User

type User struct {
	Realm    string   `json:"realm"`
	Password string   `json:"-"`
	Username string   `json:"username"`
	Scopes   []string `json:"scopes"`
	Origin   string   `json:"origin"`
	OriginId string   `json:"originId"`
	Active   bool     `json:"active"`
	Data     any
}

func GetUser

func GetUser(scope we.RequestScope) *User

type UserEnrichmentFunction

type UserEnrichmentFunction func(*User) (*User, error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL