| 1 |
package exampleop |
| 2 |
|
| 3 |
import ( |
| 4 |
"crypto/sha256" |
| 5 |
"log" |
| 6 |
"log/slog" |
| 7 |
"net/http" |
| 8 |
"strconv" |
| 9 |
"sync/atomic" |
| 10 |
"time" |
| 11 |
|
| 12 |
"github.com/go-chi/chi/v5" |
| 13 |
"golang.org/x/text/language" |
| 14 |
|
| 15 |
"github.com/zitadel/oidc/v3/pkg/op" |
| 16 |
) |
| 17 |
|
| 18 |
const ( |
| 19 |
pathLoggedOut = "/logged-out" |
| 20 |
) |
| 21 |
|
| 22 |
type Storage interface { |
| 23 |
op.Storage |
| 24 |
authenticate |
| 25 |
deviceAuthenticate |
| 26 |
} |
| 27 |
|
| 28 |
var requestCounter atomic.Uint64 |
| 29 |
|
| 30 |
// SetupServer creates an OIDC server with Issuer=http://localhost:<port> |
| 31 |
// |
| 32 |
// Use one of the pre-made clients in storage/clients.go or register a new one. |
| 33 |
func SetupServer(issuer string, storage Storage, logger *slog.Logger, wrapServer bool, extraOptions ...op.Option) chi.Router { |
| 34 |
// the OpenID Provider requires a 32-byte key for (token) encryption |
| 35 |
// be sure to create a proper crypto random key and manage it securely! |
| 36 |
key := sha256.Sum256([]byte("test")) |
| 37 |
keyId := "key1" |
| 38 |
if logger != nil { |
| 39 |
// note that this replaces the logger for the whole process, which is |
| 40 |
// acceptable for this example, but usually not what a library should do. |
| 41 |
slog.SetDefault(logger) |
| 42 |
} |
| 43 |
|
| 44 |
router := chi.NewRouter() |
| 45 |
router.Use(requestLoggingMiddleware) |
| 46 |
|
| 47 |
// for simplicity, we provide a very small default page for users who have signed out |
| 48 |
router.HandleFunc(pathLoggedOut, func(w http.ResponseWriter, req *http.Request) { |
| 49 |
w.Write([]byte("signed out successfully")) |
| 50 |
// The example middleware logs the completed request. |
| 51 |
}) |
| 52 |
|
| 53 |
// creation of the OpenIDProvider with the just created in-memory Storage |
| 54 |
provider, err := newOP( |
| 55 |
storage, |
| 56 |
issuer, |
| 57 |
key, |
| 58 |
keyId, |
| 59 |
extraOptions..., |
| 60 |
) |
| 61 |
if err != nil { |
| 62 |
log.Fatal(err) |
| 63 |
} |
| 64 |
|
| 65 |
//the provider will only take care of the OpenID Protocol, so there must be some sort of UI for the login process |
| 66 |
//for the simplicity of the example this means a simple page with username and password field |
| 67 |
//be sure to provide an IssuerInterceptor with the IssuerFromRequest from the OP so the login can select / and pass it to the storage |
| 68 |
l := NewLogin(storage, op.AuthCallbackURL(provider), op.NewIssuerInterceptor(provider.IssuerFromRequest)) |
| 69 |
|
| 70 |
// regardless of how many pages / steps there are in the process, the UI must be registered in the router, |
| 71 |
// so we will direct all calls to /login to the login UI |
| 72 |
router.Mount("/login/", http.StripPrefix("/login", l.router)) |
| 73 |
|
| 74 |
router.Route("/device", func(r chi.Router) { |
| 75 |
registerDeviceAuth(storage, r) |
| 76 |
}) |
| 77 |
|
| 78 |
handler := http.Handler(provider) |
| 79 |
if wrapServer { |
| 80 |
handler = op.RegisterLegacyServer(op.NewLegacyServer(provider, *op.DefaultEndpoints), op.AuthorizeCallbackHandler(provider)) |
| 81 |
} |
| 82 |
|
| 83 |
// we register the http handler of the OP on the root, so that the discovery endpoint (/.well-known/openid-configuration) |
| 84 |
// is served on the correct path |
| 85 |
// |
| 86 |
// if your issuer ends with a path (e.g. http://localhost:9998/custom/path/), |
| 87 |
// then you would have to set the path prefix (/custom/path/) |
| 88 |
router.Mount("/", handler) |
| 89 |
|
| 90 |
return router |
| 91 |
} |
| 92 |
|
| 93 |
// requestLoggingMiddleware demonstrates request IDs and structured HTTP logging |
| 94 |
// without coupling the OIDC library to a particular middleware package. |
| 95 |
func requestLoggingMiddleware(next http.Handler) http.Handler { |
| 96 |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 97 |
requestID := requestCounter.Add(1) |
| 98 |
w.Header().Set("X-Request-ID", strconv.FormatUint(requestID, 10)) |
| 99 |
started := time.Now() |
| 100 |
|
| 101 |
next.ServeHTTP(w, r) |
| 102 |
|
| 103 |
slog.InfoContext(r.Context(), "http request", |
| 104 |
"request_id", requestID, |
| 105 |
"method", r.Method, |
| 106 |
"path", r.URL.Path, |
| 107 |
"duration", time.Since(started), |
| 108 |
) |
| 109 |
}) |
| 110 |
} |
| 111 |
|
| 112 |
// newOP will create an OpenID Provider for localhost on a specified port |
| 113 |
// and a predefined default logout uri |
| 114 |
// it will enable all options (see descriptions) |
| 115 |
func newOP( |
| 116 |
storage op.Storage, |
| 117 |
issuer string, |
| 118 |
key [32]byte, // encryption key |
| 119 |
keyId string, |
| 120 |
extraOptions ...op.Option, |
| 121 |
) (op.OpenIDProvider, error) { |
| 122 |
config := &op.Config{ |
| 123 |
CryptoKey: key, |
| 124 |
CryptoKeyId: keyId, |
| 125 |
|
| 126 |
// will be used if the end_session endpoint is called without a post_logout_redirect_uri |
| 127 |
DefaultLogoutRedirectURI: pathLoggedOut, |
| 128 |
|
| 129 |
// enables code_challenge_method S256 for PKCE (and therefore PKCE in general) |
| 130 |
CodeMethodS256: true, |
| 131 |
|
| 132 |
// enables additional client_id/client_secret authentication by form post (not only HTTP Basic Auth) |
| 133 |
AuthMethodPost: true, |
| 134 |
|
| 135 |
// enables additional authentication by using private_key_jwt |
| 136 |
AuthMethodPrivateKeyJWT: true, |
| 137 |
|
| 138 |
// enables refresh_token grant use |
| 139 |
GrantTypeRefreshToken: true, |
| 140 |
|
| 141 |
// enables use of the `request` Object parameter |
| 142 |
RequestObjectSupported: true, |
| 143 |
|
| 144 |
// this example has only static texts (in English), so we'll set the here accordingly |
| 145 |
SupportedUILocales: []language.Tag{language.English}, |
| 146 |
|
| 147 |
DeviceAuthorization: op.DeviceAuthorizationConfig{ |
| 148 |
Lifetime: 5 * time.Minute, |
| 149 |
PollInterval: 5 * time.Second, |
| 150 |
UserFormPath: "/device", |
| 151 |
UserCode: op.UserCodeBase20, |
| 152 |
}, |
| 153 |
} |
| 154 |
handler, err := op.NewOpenIDProvider(issuer, config, storage, |
| 155 |
append([]op.Option{ |
| 156 |
//we must explicitly allow the use of the http issuer |
| 157 |
op.WithAllowInsecure(), |
| 158 |
// as an example on how to customize an endpoint this will change the authorization_endpoint from /authorize to /auth |
| 159 |
op.WithCustomAuthEndpoint(op.NewEndpoint("auth")), |
| 160 |
}, extraOptions...)..., |
| 161 |
) |
| 162 |
if err != nil { |
| 163 |
return nil, err |
| 164 |
} |
| 165 |
return handler, nil |
| 166 |
} |