aboutsummaryrefslogtreecommitdiff
path: root/server
diff options
context:
space:
mode:
Diffstat (limited to 'server')
-rw-r--r--server/server.go68
1 files changed, 68 insertions, 0 deletions
diff --git a/server/server.go b/server/server.go
new file mode 100644
index 0000000..dc71c95
--- /dev/null
+++ b/server/server.go
@@ -0,0 +1,68 @@
+package server
+
+import (
+ "fmt"
+
+ "github.com/fasthttp/router"
+ "github.com/valyala/fasthttp"
+ "github.com/zitadel/oidc/pkg/client/rp"
+)
+
+func IsAuthenticate(relayPartyProvider rp.RelyingParty, next fasthttp.RequestHandler) fasthttp.RequestHandler {
+ return func(ctx *fasthttp.RequestCtx) {
+ token := string(ctx.Request.Header.Cookie("token"))
+ tokenVerifier := relayPartyProvider.IDTokenVerifier()
+ _, err := rp.VerifyIDToken(ctx, token, tokenVerifier)
+ if err != nil {
+ ctx.Redirect("/login", 307)
+ return
+ }
+ next(ctx)
+ }
+}
+
+func NewS4OServer(clientID, clientSecret, issuer, callback, rootPath string, scopes []string) (*fasthttp.Server, error) {
+ r := router.New()
+
+ relayPartyProvider, err := rp.NewRelyingPartyOIDC(issuer, clientID, clientSecret, callback, scopes)
+ if err != nil {
+ return nil, err
+ }
+
+ fs := &fasthttp.FS{
+ Root: rootPath,
+ IndexNames: []string{"index.html"},
+ GenerateIndexPages: true,
+ AcceptByteRange: true,
+ Compress: true,
+ }
+
+ r.Handle("GET", "/login", func(ctx *fasthttp.RequestCtx) {
+ url := rp.AuthURL(" ", relayPartyProvider)
+ ctx.Redirect(url, 307)
+ })
+
+ r.Handle("GET", "/callback", func(ctx *fasthttp.RequestCtx) {
+ code := string(ctx.QueryArgs().Peek("code"))
+ token, err := rp.CodeExchange(ctx, code, relayPartyProvider)
+ if err != nil {
+ ctx.WriteString(fmt.Sprintf("Error: %+v", err))
+ return
+ }
+
+ cookie := &fasthttp.Cookie{}
+ cookie.SetKey("token")
+ cookie.SetValue(token.IDToken)
+ cookie.SetExpire(token.Expiry)
+ cookie.SetHTTPOnly(true)
+ cookie.SetSameSite(fasthttp.CookieSameSiteDefaultMode)
+ ctx.Response.Header.SetCookie(cookie)
+ ctx.Redirect("/", 307)
+ })
+
+ r.Handle("GET", "/{filepath:*}", IsAuthenticate(relayPartyProvider, fs.NewRequestHandler()))
+
+ return &fasthttp.Server{
+ Handler: r.Handler,
+ }, nil
+}