auth

package module
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Sep 15, 2021 License: Apache-2.0 Imports: 9 Imported by: 2

README

auth

codecov GoDoc

ackage auth provides painless OAuth2 authentication for http handlers.

After creating an Auth object, the RedirectHandler should be mounted to answer the cfg.OAuth2.RedirectURL http calls and the Authenticate method can be used to enforce authentication on http handlers. The User function can be used to get the logged in user in an authenticated http handler.

See simple usage example in ./example/main.go.

a, err := auth.New(ctx, auth.Config{ ... })
if err != nil { /* Handle error */ }

mux := http.NewServeMux()
mux.Handle("/", a.Authenticate(handler))  // Authenticate a given handler on '/'.
mux.Handle("/auth", a.RedirectHandler())  // Handle OAuth2 redirect.
log.Fatal(http.ListenAndServe(":8080", mux)) // Serve.

Authentication

Authentication is done by wrapping an http.Handler that requires only signed in users with the Authenticate middleware method.

Authorization

Authorization is allowing only specific users to access an http.Handler. For example, allowing only john@gmail.com, or anyone that signed in using their @example.com. This can be done by inspecting the username using the auth.User(ctx) method, inside the authenticated http.Handler. For example, given a function authorized that checks if the signed-in user is authorized:

func handler(w http.ResponseWriter, r *http.Request) {
	creds := auth.User(r.Context())
	if !authorized(creds) {
		// Handle unauthorized users.
		http.Error(w, "User not allowed", http.StatusForbidden)
		return
	}
	// Handle authorized users.
}

// authorized is an example function that checks if a user is authorized.
func authorized(creds *auth.Creds) bool { return creds.Email == "john@gmail.com" }

Features

  • Automatic redirects to OAuth2 flow (login screen) from authorized handlers when user is not authenticated.

  • Redirect handler automatic redirects to the path that requested to the authentication. Such that if user visited /foo and was sent to the OAuth2 login. After successfull login it will return to /foo.

  • Auth2 id_token is automatically stored in a Cookie. This allows users not to go through the authentication phase on every authenticated page, or on different sessions.

Sub Packages

  • example: The example program shows how to use the auth package.

Readme created from Go doc with goreadme

Documentation

Overview

ackage auth provides painless OAuth2 authentication for http handlers.

After creating an Auth object, the `RedirectHandler` should be mounted to answer the cfg.OAuth2.RedirectURL http calls and the `Authenticate` method can be used to enforce authentication on http handlers. The `User` function can be used to get the logged in user in an authenticated http handler.

See simple usage example in ./example/main.go.

a, err := auth.New(ctx, auth.Config{ ... })
if err != nil { /* Handle error */ }

mux := http.NewServeMux()
mux.Handle("/", a.Authenticate(handler))  // Authenticate a given handler on '/'.
mux.Handle("/auth", a.RedirectHandler())  // Handle OAuth2 redirect.
log.Fatal(http.ListenAndServe(":8080", mux)) // Serve.

Authentication

Authentication is done by wrapping an `http.Handler` that requires only signed in users with the `Authenticate` middleware method.

Authorization

Authorization is allowing only specific users to access an `http.Handler`. For example, allowing only john@gmail.com, or anyone that signed in using their @example.com. This can be done by inspecting the username using the `auth.User(ctx)` method, inside the authenticated `http.Handler`. For example, given a function `authorized` that checks if the signed-in user is authorized:

func handler(w http.ResponseWriter, r *http.Request) {
	creds := auth.User(r.Context())
	if !authorized(creds) {
		// Handle unauthorized users.
		http.Error(w, "User not allowed", http.StatusForbidden)
		return
	}
	// Handle authorized users.
}

// authorized is an example function that checks if a user is authorized.
func authorized(creds *auth.Creds) bool { return creds.Email == "john@gmail.com" }

Features

- [x] Automatic redirects to OAuth2 flow (login screen) from authorized handlers when user is not authenticated.

- [x] Redirect handler automatic redirects to the path that requested to the authentication. Such that if user visited /foo and was sent to the OAuth2 login. After successfull login it will return to /foo.

- [x] Auth2 id_token is automatically stored in a Cookie. This allows users not to go through the authentication phase on every authenticated page, or on different sessions.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Auth

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

Auth is an authentication handler.

func New

func New(ctx context.Context, cfg Config) (*Auth, error)

New returns an authentication handler.

func (*Auth) Authenticate

func (a *Auth) Authenticate(handler http.Handler) http.Handler

Authenticate wraps a handler and enforces only authenticated users.

func (*Auth) LogoutHandler added in v0.1.1

func (a *Auth) LogoutHandler(redirectPath string) http.Handler

LogoutHandler can be mounted on an http endpoint for logging out. It will redirect to the given path after user is navigating to the logout path.

func (*Auth) RedirectHandler

func (a *Auth) RedirectHandler() http.Handler

RedirectHandler should be mounted on the cfg.OAuth2.RedirectURL path.

type Config

type Config struct {
	// Config Oauth2 client credentials.
	//
	// If scope is not set, the defaultScopes are used. The scope should not be set for standard
	// usage.
	// If Endpoint is not set, google.Endpoint is used. It should not be set for standard usage.
	//
	// OAuth2 Providers
	//
	// For Google OAuth2 authentication, the client credentials can be generated using Google cloud
	// console at: https://console.cloud.google.com/apis/credentials.
	oauth2.Config

	// Disable authentication.
	Disable bool

	Log    func(string, ...interface{}) `json:"-"`
	Client *http.Client                 `json:"-"`

	// Unsecure uses unsecured cookies (Required for http scheme).
	Unsecure bool
}

Config is the Google configuration for the authentication.

type Creds

type Creds struct {
	// Email of user. Can be used to identify the user.
	Email string
	// Name of user. User may change the name, therefore this field should not be used for
	// authentication.
	Name string
}

Creds is the credentials of the logged in user.

func User

func User(ctx context.Context) *Creds

User returns the credentials of the logged in user. It returns nil in case that there is no user information (This can happen when the http handler is not authenticated). It should be used inside an `http.Handler` that was authenticated using `Auth.Authenticate(handler)` and receive the request context, as follows:

	func handler(w http.ResponseWriter, r *http.Request) {
		creds := auth.User(r.Context())
 	if !authorized(creds) {
			// Handle unauthorized users.
			http.Error(w, "User not allowed", http.StatusForbidden)
			return
		}
		// Handle authorized users.
 }

Directories

Path Synopsis
The example program shows how to use the auth package.
The example program shows how to use the auth package.

Jump to

Keyboard shortcuts

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