From 6734c4408ffb67841115ca17d14d879043a3343e Mon Sep 17 00:00:00 2001 From: Gabriel Arakaki Giovanini Date: Sat, 10 Dec 2022 23:36:39 +0100 Subject: feat: Initial set up for static single sign on This is a simple project to have a static site behind single sign on. --- server/server.go | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 server/server.go (limited to 'server/server.go') 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 +} -- cgit v1.2.3