Documentation ¶
Overview ¶
Package oidcauth is an authentication middleware for web applications and microservices, which uses an external OpenID Connect identity provider (IdP) for user storage and authentication.
The library is configurable, except for some choices that have been pre-made on purpose:
- Supports only the authorization code flow of OAuth2, which makes it suitable for multi-page web apps. If you are creating a SPA app, the implicit flow might be a better choice for your project.
- Uses secure cookies to pass session IDs back and forth between the browser and the app. Session management is handled by gorilla/sessions, so you can use any of the many available implementations for it to choose where to store the session data (eg. CookieStore, RedisStore, DynamoStore, etc.).
- Authenticated handlers verify same origin with standard headers ('Origin' and 'Referer') and block potential CSRF requests. If neither the 'Origin' nor the 'Referer' header is present, and the request method is anything but GET or OPTIONS, the request is blocked. Additionally 'Access-Control-Allow-Origin' header is added to indicate the allowed origin. The list of allowed origins must be specified in the configuration object (usually only the domain of your own app and the domain of the IdP). Use of origin '*' is not allowed.
Can be used as authentication middleware for (see examples):
- Standard multi-page web application
- Complex web application that act as a gateway between the browser and several microservices (APIs) by passing the access token acquired during the authentication phase down to the microservices.
Tested for compatibility with:
- Keycloak 3.4.3.Final, a standalone open source identity and access management server (http://www.keycloak.org/)
Dependencies: - github.com/coreos/go-oidc - golang.org/x/oauth2 - github.com/gorilla/sessions
TODO: - Add authorization support.
Index ¶
- func VerifyOrigin(allowedOrigins []string, next http.Handler, onErr http.Handler) http.Handler
- type Authenticator
- func (a *Authenticator) AuthWithSession(next http.Handler) http.Handler
- func (a *Authenticator) Client(ctx context.Context, w http.ResponseWriter, r *http.Request) (*http.Client, error)
- func (a *Authenticator) GetAuthInfo(r *http.Request) (subject string, claims string, err error)
- func (a *Authenticator) GetClaims(r *http.Request) (map[string]interface{}, error)
- func (a *Authenticator) GetToken(r *http.Request) (*oauth2.Token, error)
- func (a *Authenticator) HandleAuthResponse() http.Handler
- func (a *Authenticator) IsAuthenticated(r *http.Request) error
- func (a *Authenticator) Logout(redirectURL string) http.Handler
- func (a *Authenticator) RedirectToLoginPage(w http.ResponseWriter, r *http.Request)
- func (a *Authenticator) SetToken(w http.ResponseWriter, r *http.Request, token *oauth2.Token) error
- func (a *Authenticator) VerifyAuthResponse() http.Handler
- type Config
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func VerifyOrigin ¶
VerifyOrigin middleware verifies the origin of requests by checking the 'Origin' and 'Referer' headers. Requests are blocked if the origin differs from the list of allowed ones provided in allowedOrigins, or if neither of those headers is present in the request.
Types ¶
type Authenticator ¶
type Authenticator struct { Config Config // contains filtered or unexported fields }
The Authenticator type provides middleware methods for authentication of http requests. A single authenticator object can be shared by concurrent goroutines.
func New ¶
func New(ctx context.Context, config *Config) (*Authenticator, error)
New creates a new Authenticator object with the given configuration options. The ctx context is used only for the initial connection to the well-known configuration endpoint of the IdP and can be set to context.Background.
func (*Authenticator) AuthWithSession ¶
func (a *Authenticator) AuthWithSession(next http.Handler) http.Handler
AuthWithSession authenticates the request. On successful authentication the request is passed down to the next http handler. The next handler can access information about the authenticated user via the GetAuthInfo, GetClaims and GetToken methods. If authentication was not successful, the browser is redirected to the login endpoint of the IdP. If the redirected request is using the GET method, the RequestURI of the current request is set as the return URL for successful login. Config.DefaultReturnURL is set for non GET requests.
func (*Authenticator) Client ¶
func (a *Authenticator) Client(ctx context.Context, w http.ResponseWriter, r *http.Request) (*http.Client, error)
Client is a wrapper to the underlying Client() method of oauth2.Config object, which returns an http.Client that automatically populates the authorization header. with the access token. If the token stored in the session has expired, uses the refresh_token to renew it automatically and stores the updated token in the session.
func (*Authenticator) GetAuthInfo ¶
GetAuthInfo retrieves the subject identifier (user id) with which the user is registered with the IdP and the claims that were returned during authentication. Subject identifer is returned as a string. Claims are returned as an opaque JSON value - as provided by the IdP. An error is returned if the user has not been authenticated yet or an error occurs while reading the session data.
func (*Authenticator) GetClaims ¶
func (a *Authenticator) GetClaims(r *http.Request) (map[string]interface{}, error)
GetClaims retrieves the claims that were sent by the IdP during authentication as a map.
func (*Authenticator) GetToken ¶
GetToken retrieves an oauth2.Token structure containing the access and refresh tokens.
func (*Authenticator) HandleAuthResponse ¶
func (a *Authenticator) HandleAuthResponse() http.Handler
HandleAuthResponse handles the authentication response sent by the IdP. Users of oidcauth should call this method as callback handler for CallbackURL.
func (*Authenticator) IsAuthenticated ¶
func (a *Authenticator) IsAuthenticated(r *http.Request) error
IsAuthenticated checks if current session is authenticated by looking at the authentication flag in the session data.
func (*Authenticator) Logout ¶
func (a *Authenticator) Logout(redirectURL string) http.Handler
Logout deletes the session data, logouts from the IdP and redirects to the URL provided.
func (*Authenticator) RedirectToLoginPage ¶
func (a *Authenticator) RedirectToLoginPage(w http.ResponseWriter, r *http.Request)
RedirectToLoginPage redirects the request to the login endpoint of the identity provider.
func (*Authenticator) SetToken ¶
func (a *Authenticator) SetToken( w http.ResponseWriter, r *http.Request, token *oauth2.Token, ) error
SetToken updates the token value stored in the session.
func (*Authenticator) VerifyAuthResponse ¶
func (a *Authenticator) VerifyAuthResponse() http.Handler
VerifyAuthResponse verifies the authentication response received from the IdP and redirects to the return URL provided on the first request.
type Config ¶
type Config struct { ClientID string ClientSecret string // IssuerURL, eg. "https://EXAMPLE.COM/auth/realms/REALM_NAME" for Keycloak. IssuerURL string // LogoutURL is the endpoint used for logging out of IdP session using GET request, // eg. "https://EXAMPLE.COM/auth/realms/REALM_NAME/protocol/openid-connect/logout" for Keycloak. LogoutURL string // CallbackURL is the absolute URL to a handler in your application, which deals with auth // responses from the IdP. // You must handle requests to that URL and pass them to the HandleAuthResponse() method. // eg. "https://localhost:5556/auth/callback". CallbackURL string // The default URL to use as return URL after successful authentication of non GET requests. DefaultReturnURL string // List of additional scopes to request from the IdP in addition to the default 'openid' scope // (eg. []string{"profile"}). Scopes []string // AllowedOrigins is a list of hosts (https://example.com) allowed as origins of the HTTP request. // Add the origin of your app and that of the IdP to the list. // Use domain names in AllowedOrigins, not IP addresses. AllowedOrigins []string // SessionStore is where session data like user ID and claims are stored. // SessionStore could be any of the available gorilla/session implementations // (eg. CookieStore with secure flag, RedisStore, DynamoStore, etc.) SessionStore sessions.Store // TokenStore holds the access/refresh tokens that are acquired during authentication. // Those tokens can be used to access other services (APIs) that are part of the application. // Keeping tokens in a separate store from session data helps to avoid reaching the usual // limit on the amount of data that can be stored in a store (eg. 4KB). // TokenStore could be any of the available gorilla/session implementations // (eg. CookieStore with secure flag, RedisStore, DynamoStore, etc.) TokenStore sessions.Store // Set StateStore to a sessions store, which will hold the oauth state value. // Monoliths and scalable applications with sticky sessions could store state in instance memory. // Scalable apps without sticky sessions can use Memcache or Redis for storage. StateStore oauth2state.StateStorer }
The Config object determines the behaviour of the Authenticator.