authproxy

package
v0.3.5 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2024 License: Apache-2.0 Imports: 13 Imported by: 0

README

authproxy

This package provides a reverse proxy and JWT validation middleware for Go applications. It's designed to work with an authentication service that sets an access_token cookie and exposes public keys for JWT verification.

Features

  • Reverse proxy for authentication endpoints: Forwards requests with the /auth prefix to a designated authentication host. This allows you to integrate your authentication flow seamlessly.
  • JWT validation: Validates the access_token cookie for all other requests. If the token is invalid or missing, it redirects the user to the authentication service's refresh endpoint.
  • Authorization header forwarding: Adds the validated access token as an Authorization header to the request, making it easy to use with downstream services.
  • gRPC support: Includes a function to forward the Authorization header from incoming gRPC requests to outgoing ones.

Installation

go get go.alis.build/iam/authproxy 

Usage

  1. Create an AuthProxy instance:
authHost := "https://iam-auth-" + os.Getenv("ALIS_RUN_HASH") + ".run.app"
authProxy := authproxy.New(authHost)
  1. Integrate with your HTTP handler:
func handler(w http.ResponseWriter, r *http.Request) {
    if authProxy.HandleAuth(w, r) {
        return // Request handled by authproxy
    }

    // Your application logic here...
}
  1. (Optional) Forward Authorization header in gRPC interceptors:
import "google.golang.org/grpc"

func unaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
    ctx, err := authProxy.ForwardAuthorizationHeader(ctx)
    if err != nil {
        return nil, err
    }
    return handler(ctx, req)
}

How it Works

  • Reverse Proxy: When a request with the /auth prefix is received, the HandleAuth function forwards it to the configured authHost. It preserves cookies and headers to maintain the authentication flow.
  • JWT Validation: For all other requests, HandleAuth checks for an access_token cookie. If present, it validates the token against the public keys fetched from the authentication service.
  • Public Key Caching: Public keys are cached in a sync.Map to reduce latency and load on the authentication service. The cache is updated if the token's kid (key ID) is not found.
  • Authorization Header: After successful validation, the access token is added as an Authorization header to the request.
  • gRPC Forwarding: The ForwardAuthorizationHeader function extracts the Authorization header from incoming gRPC metadata and adds it to the outgoing metadata.

Important Notes

  • Authentication Service: This package assumes you have a separate authentication service that handles user login, token generation, and key management.
  • Security: Ensure your authentication service is properly secured and uses HTTPS to protect sensitive information.
  • Error Handling: Implement proper error handling in your application to handle cases where the authentication service is unavailable or returns errors.
  • Customization: You can customize the cookie name and other parameters as needed.

Documentation

Index

Constants

View Source
const ForwardedHostHeader = "x-forwarded-host"

AlisForwardedHostHeader ia the header used to forward the host with the

Variables

This section is empty.

Functions

func ForwardAuthorizationHeader added in v0.0.4

func ForwardAuthorizationHeader(ctx context.Context) (context.Context, error)

ForwardAuthorizationHeader forwards the Authorization header in the incoming ctx to the outgoing ctx. Use this at the very top of your unary and streaming interceptors in the context of a gRPC server

Types

type AuthProxy

type AuthProxy struct {
	// contains filtered or unexported fields
}

func New

func New(authHost string) *AuthProxy

Creates a new AuthProxy with the given authHost. Example authHost: "https://iam-auth-123456789.europe-west1.run.app".

func (*AuthProxy) HandleAuth

func (h *AuthProxy) HandleAuth(resp http.ResponseWriter, req *http.Request) bool

Reverse proxies /auth/* requests to the authHost and validates the access_token cookie set by the authHost for all other requests. If the access token is valid, it also adds it as a header to the request.

Returns true if the request was handled, in which case you should return from the handler.

func (*AuthProxy) HandleNotFoundOrAccessDenied added in v0.1.8

func (h *AuthProxy) HandleNotFoundOrAccessDenied(resp http.ResponseWriter, req *http.Request)

Reverse proxies to /auth/denied which shows a message in the line of "Not found or you don't have access".

func (*AuthProxy) WithFixedPostAuthRedirect added in v0.1.7

func (h *AuthProxy) WithFixedPostAuthRedirect(path string)

Hardcodes the path to redirect to after authentication in stead of using the request URI.

func (*AuthProxy) WithPrivateFavicon added in v0.1.5

func (h *AuthProxy) WithPrivateFavicon()

Exclude favicon.ico from public paths, as its default behavior is to be public.

func (*AuthProxy) WithPublicPaths added in v0.1.5

func (h *AuthProxy) WithPublicPaths(paths ...string)

Exclude paths from authentication, i.e. no access token is required for these paths. You can specify exact paths or paths with a wildcard (*) at the end. favicon.ico is by default a public path.

Jump to

Keyboard shortcuts

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