github.com/openfga/openfga@v1.5.4-rc1/internal/authn/authn.go (about) 1 package authn 2 3 import ( 4 "context" 5 6 "github.com/MicahParks/keyfunc" 7 openfgav1 "github.com/openfga/api/proto/openfga/v1" 8 "google.golang.org/grpc/codes" 9 "google.golang.org/grpc/status" 10 ) 11 12 type ctxKey string 13 14 var ( 15 authClaimsContextKey = ctxKey("auth-claims") 16 17 ErrUnauthenticated = status.Error(codes.Code(openfgav1.AuthErrorCode_unauthenticated), "unauthenticated") 18 ErrMissingBearerToken = status.Error(codes.Code(openfgav1.AuthErrorCode_bearer_token_missing), "missing bearer token") 19 ) 20 21 type Authenticator interface { 22 // Authenticate returns a nil error and the AuthClaims info (if available) if the subject is authenticated or a 23 // non-nil error with an appropriate error cause otherwise. 24 Authenticate(requestContext context.Context) (*AuthClaims, error) 25 26 // Close Cleans up the authenticator. 27 Close() 28 } 29 30 type NoopAuthenticator struct{} 31 32 var _ Authenticator = (*NoopAuthenticator)(nil) 33 34 func (n NoopAuthenticator) Authenticate(requestContext context.Context) (*AuthClaims, error) { 35 return &AuthClaims{ 36 Subject: "", 37 Scopes: nil, 38 }, nil 39 } 40 41 func (n NoopAuthenticator) Close() {} 42 43 // AuthClaims contains claims that are included in OIDC standard claims. https://openid.net/specs/openid-connect-core-1_0.html#IDToken 44 type AuthClaims struct { 45 Subject string 46 Scopes map[string]bool 47 } 48 49 // ContextWithAuthClaims injects the provided AuthClaims into the parent context. 50 func ContextWithAuthClaims(parent context.Context, claims *AuthClaims) context.Context { 51 return context.WithValue(parent, authClaimsContextKey, claims) 52 } 53 54 // AuthClaimsFromContext extracts the AuthClaims from the provided ctx (if any). 55 func AuthClaimsFromContext(ctx context.Context) (*AuthClaims, bool) { 56 claims, ok := ctx.Value(authClaimsContextKey).(*AuthClaims) 57 if !ok { 58 return nil, false 59 } 60 61 return claims, true 62 } 63 64 // OidcConfig contains authorization server metadata. See https://datatracker.ietf.org/doc/html/rfc8414#section-2 65 type OidcConfig struct { 66 Issuer string `json:"issuer"` 67 JWKsURI string `json:"jwks_uri"` 68 } 69 70 type OIDCAuthenticator interface { 71 GetConfiguration() (*OidcConfig, error) 72 GetKeys() (*keyfunc.JWKS, error) 73 }