Categorygithub.com/wtsi-hgi/go-authserver
modulepackage
1.3.0
Repository: https://github.com/wtsi-hgi/go-authserver.git
Documentation: pkg.go.dev

# README

go-authserver

A library to easily create an authenticated web server in Go

Supports arbitrary username&password type authentication using your own callback to veryify the password, and also Okta auth via both a CLI and a web interface.

The server is gin-based, and you add routes to the server using Router() or AuthRouter(), then Start() it (it will gracefully stop on SIGINT and SIGTERM):

import gas "github.com/wtsi-hgi/go-authserver"

logger := syslog.new(syslog.LOG_INFO, "tag")

server := gas.New(logger)

server.Router().GET(gas.EndPointREST+"/myendpoint", myGinHandlerFunc)

server.EnableAuth("cert.pem", "key.pem", func(username, password string) (bool, string) {
    return true, "" // allows all login attempts; do proper password checking instead!
})

server.AuthRouter().GET("/mysecuredendpoint", myGinHandlerFuncForSecureStuff)

err := server.Start("localhost:8080", "cert.pem", "key.pem")

With the server running, a client can login with a username and password:

import gas "github.com/wtsi-hgi/go-authserver"

jwt, err := gas.Login("localhost:8080", "cert.pem", "username", "password")

restyRequest := gas.NewAuthenticatedClientRequest("localhost:8080", "cert.pem", jwt)

response, err := restyRequest.Get(gas.EndPointAuth+"/mysecuredendpoint")

Okta

For okta auth, you will need an Okta app configured like:

  • Sign-in method: OIDC
  • App type: Web application
  • Name: [your app name]
  • Grant type: Authorization code
  • Sign-in redirect URIs: https://[your domain:port]/callback, https://[your domain:port]/callback-cli
  • Sign-out redirect URIs: https://[your domain:port]/
  • Assignments: allow everyone access

Then for the server, after calling EnableAuth(), also say:

server.AddOIDCRoutes(oktaURL, oktaOAuthIssuer, oktaOAuthClientID, oktaOAuthClientSecret)

Then a command-line client can log in using Okta after getting a code by visiting https://localhost:8080/login-cli :

jwt, err := gas.LoginWithOKTA("localhost:8080", "cert.pem", code)

A web-based client can log in by visiting https://localhost:8080/login . After logging in they will be redirected to your default route.

# Functions

CreateTestCert creates a self-signed cert and key in a temp dir and returns their paths.
GenerateAndStoreTokenForSelfClient calls GenerateToken() and returns the token, but also stores it in the given file, readable only by the current user.
GenerateToken creates a cryptographically secure pseudorandom URL-safe base64 encoded string 43 bytes long.
GetStoredToken reads the token from the given file but only returns it if it's got some length.
GetUser returns the current user's username and uid.
IncludeAbortErrorsInBody is a gin.HandlerFunc that can be Use()d with gin routers from Router() and AuthRouter() that ensures that the errors we accumulate in AbortWithError() calls get written to the returned body.
Login is a client call to a Server listening at the domain:port url given to the request that checks the given password is valid for the given username, and returns a JWT if so.
LoginWithOKTA sends a request to the server containing the token as a cookie, so it will be able to return the JWT for the user.
New creates a Server which can serve a REST API and website.
NewAuthenticatedClientRequest is like NewClientRequest, but sets the given JWT in the authorization header.
NewClientCLI returns a ClientCLI that will get and store JWTs from and to a file with the given basename in the user's XDG_STATE_HOME or HOME directory, initially retrieving the JWT from the server at url using cert.
NewClientRequest creates a resty Request that will trust the certificate at the given path.
NewStringLogger returns a new StringLogger.
QueryREST does a test GET of the given REST endpoint (start it with /), with extra appended (start it with ?).
RefreshJWT is like Login(), but refreshes a JWT previously returned by Login() if it's still valid.
StartTestServer starts the given server using the given cert and key paths and returns the address and a func you should defer to stop the server.
TokenDir is the directory where the server will store a token file when using GenerateAndStoreTokenForSelfClient(), and ClientCLI will store JWTs.
TokenMatches compares two tokens and tells you if they match.
UserNameToUID converts user name to UID.

# Constants

No description provided by the author
No description provided by the author
No description provided by the author
EndPointAuth is the name of the router group that endpoints requiring JWT authorisation should belong to.
EndpointAuthCallback is the endpoint where the OIDC provider will send the user back to after login.
No description provided by the author
EndpointCLIAuthCode is the endpoint the user can get an auth code from to copy paste into the terminal for a CLI session.
EndPointJWT is the endpoint for creating or refreshing a JWT.
EndpointOIDCCLILogin will be handled by redirecting the user to Okta, to get an auth code back to copy paste.
EndpointOIDCLogin will be handled by redirecting the user to Okta.
EndPointREST is the base location for all REST endpoints.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Structs

ClientCLI can be used by a CLI client to log in to a go-authserver Server.
JWTPermissionsError is used to distinguish this type of error - where the already stored JWT token doesn't have private permissions.
OktaUser is used to json.Unmarshal Okta user claims.
Server is used to start a web server that provides a REST API for authenticating, and a router you can add website pages to.
StdPasswordHandler is the default password handler using stdout and stdin.
StringLogger is a thread-safe logger that logs to a string.
User is what we store in our JWTs.

# Interfaces

PasswordHandler can ask for and return a password read from a reader.
StartStop is an interface that Server satisfies.

# Type aliases

AuthCallback is a function that returns true if the given password is valid for the given username.
No description provided by the author
StopCallback is a function that you can give SetStopCallback() to have this function called when the Server is Stop()ped.