github.com/miguelangel-nubla/oauth2commander@v0.3.7/oauth2server/oauth2server.go (about) 1 package oauth2server 2 3 import ( 4 "context" 5 "encoding/gob" 6 "log" 7 "net/http" 8 "time" 9 10 "github.com/coreos/go-oidc/v3/oidc" 11 "github.com/grokify/go-pkce" 12 "golang.org/x/oauth2" 13 14 "github.com/alexedwards/scs/v2" 15 ) 16 17 type idTokenClaims struct { 18 Iss string `json:"iss"` 19 Sub string `json:"sub"` 20 Aud string `json:"aud"` 21 Exp int64 `json:"exp"` 22 Nbf int64 `json:"nbf"` 23 Iat int64 `json:"iat"` 24 Nonce string `json:"nonce"` 25 Azp string `json:"azp"` 26 Name string `json:"name"` 27 PreferredUsername string `json:"preferred_username"` 28 Scopes []string `json:"scopes"` 29 Groups []string `json:"groups"` 30 } 31 32 type authData struct { 33 OAuth2Token oauth2.Token 34 IDTokenClaims idTokenClaims 35 } 36 37 type oauthFlowData struct { 38 State string 39 Nonce string 40 Redirect string 41 } 42 43 type Oauth2Commander struct { 44 ctx context.Context 45 config oauth2.Config 46 verifier *oidc.IDTokenVerifier 47 codeVerifier string 48 sessionManager *scs.SessionManager 49 sessionKey string 50 oauthKey string 51 csrfKey string 52 } 53 54 func init() { 55 gob.Register(authData{}) 56 gob.Register(oauthFlowData{}) 57 } 58 59 func NewOauth2Commander(clientID, clientSecret, oidcIssuer, callbackURL string) *Oauth2Commander { 60 ctx := context.Background() 61 62 provider, err := oidc.NewProvider(ctx, oidcIssuer) 63 if err != nil { 64 log.Fatal(err) 65 } 66 67 oidcConfig := &oidc.Config{ClientID: clientID} 68 verifier := provider.Verifier(oidcConfig) 69 70 codeVerifier, err := pkce.NewCodeVerifier(96) 71 if err != nil { 72 log.Fatal(err) 73 } 74 75 sessionManager := scs.New() 76 sessionManager.Lifetime = 24 * time.Hour 77 sessionManager.Cookie.Persist = true 78 sessionManager.Cookie.SameSite = http.SameSiteStrictMode 79 sessionManager.Cookie.Secure = true 80 81 return &Oauth2Commander{ 82 ctx: ctx, 83 verifier: verifier, 84 codeVerifier: codeVerifier, 85 config: oauth2.Config{ 86 ClientID: clientID, 87 ClientSecret: clientSecret, 88 Endpoint: provider.Endpoint(), 89 RedirectURL: callbackURL, 90 Scopes: []string{oidc.ScopeOpenID, "profile", "groups"}, 91 }, 92 sessionManager: sessionManager, 93 sessionKey: "authData", 94 oauthKey: "oauthFlowData", 95 } 96 } 97 98 func (app *Oauth2Commander) Oauth2Callback(w http.ResponseWriter, r *http.Request) { 99 oauthFlowDataValue := app.sessionManager.Get(r.Context(), app.oauthKey) 100 if oauthFlowDataValue == nil { 101 handleError(w, "oauth flow session data not found", http.StatusBadRequest) 102 return 103 } 104 105 oauthFlowData, ok := oauthFlowDataValue.(oauthFlowData) 106 if !ok { 107 handleError(w, "oauth flow session data invalid", http.StatusInternalServerError) 108 return 109 } 110 111 if r.URL.Query().Get("state") != oauthFlowData.State { 112 handleError(w, "oauth flow state did not match", http.StatusBadRequest) 113 return 114 } 115 116 oauth2Token, err := app.config.Exchange( 117 app.ctx, 118 r.URL.Query().Get("code"), 119 oauth2.SetAuthURLParam(pkce.ParamCodeVerifier, app.codeVerifier), 120 ) 121 if err != nil { 122 handleError(w, "Failed to exchange token: "+err.Error(), http.StatusInternalServerError) 123 return 124 } 125 126 idToken, err := app.verifier.Verify(app.ctx, oauth2Token.Extra("id_token").(string)) 127 if err != nil { 128 handleError(w, "Failed to verify ID Token: "+err.Error(), http.StatusInternalServerError) 129 return 130 } 131 132 if idToken.Nonce != oauthFlowData.Nonce { 133 handleError(w, "nonce did not match", http.StatusBadRequest) 134 return 135 } 136 137 app.sessionManager.Remove(r.Context(), app.oauthKey) 138 139 var claims idTokenClaims 140 if err := idToken.Claims(&claims); err != nil { 141 handleError(w, err.Error(), http.StatusInternalServerError) 142 return 143 } 144 145 authData := authData{ 146 OAuth2Token: *oauth2Token, 147 IDTokenClaims: claims, 148 } 149 150 app.setAuth(r, &authData) 151 http.Redirect(w, r, oauthFlowData.Redirect, http.StatusFound) 152 }