-
-
Notifications
You must be signed in to change notification settings - Fork 84
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support OpenID tokens for getting using information #122
Open
alek-sys
wants to merge
13
commits into
go-pkgz:master
Choose a base branch
from
alek-sys:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
a528a70
Add support of OpenID providers
alek-sys 242fcfc
Allow to add custom OpenID providers
alek-sys e3fd054
Refactor keys loading to retry on token request
alek-sys 89969d4
Only support OpenID for custom providers
alek-sys 7411bff
Fix typos
alek-sys 8026918
Cleanup
alek-sys e5a20c7
Only generate private key if OpenID is enabled
alek-sys ab93f7d
Fix linter issues and refactor to reduce cyclomatic complexity
alek-sys 41a0ffe
Make sure AddDevOpenIDProvider is called in auth_test.go
alek-sys 9de085f
Add auth tests
alek-sys 28a499c
Fix token validation and update README
alek-sys d6b8f26
Wrap errors when loading user info
alek-sys 3bf3b62
Tidy up
alek-sys File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,8 +2,14 @@ package provider | |
|
||
import ( | ||
"context" | ||
"crypto/rand" | ||
"crypto/rsa" | ||
"encoding/base64" | ||
"encoding/json" | ||
"fmt" | ||
"github.com/golang-jwt/jwt" | ||
"html/template" | ||
"math/big" | ||
"net/http" | ||
"strings" | ||
"sync" | ||
|
@@ -25,9 +31,10 @@ const defDevAuthPort = 8084 | |
// desired user name, this is the mode used for development. Non-interactive mode for tests only. | ||
type DevAuthServer struct { | ||
logger.L | ||
Provider Oauth2Handler | ||
Automatic bool | ||
GetEmailFn func(string) string | ||
Provider Oauth2Handler | ||
Automatic bool | ||
GetEmailFn func(string) string | ||
CustomizeIDTokenFn func(map[string]interface{}) map[string]interface{} | ||
|
||
username string // unsafe, but fine for dev | ||
httpServer *http.Server | ||
|
@@ -50,6 +57,15 @@ func (d *DevAuthServer) Run(ctx context.Context) { //nolint (gocyclo) | |
return | ||
} | ||
|
||
var privateKey *rsa.PrivateKey | ||
if d.Provider.UseOpenID { | ||
privateKey, err = rsa.GenerateKey(rand.Reader, 2048) | ||
if err != nil { | ||
d.Logf("[ERROR] failed to generate keys") | ||
return | ||
} | ||
} | ||
|
||
d.httpServer = &http.Server{ | ||
Addr: fmt.Sprintf(":%d", d.Provider.Port), | ||
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
|
@@ -74,7 +90,8 @@ func (d *DevAuthServer) Run(ctx context.Context) { //nolint (gocyclo) | |
} | ||
|
||
state := r.URL.Query().Get("state") | ||
callbackURL := fmt.Sprintf("%s?code=g0ZGZmNjVmOWI&state=%s", d.Provider.conf.RedirectURL, state) | ||
redirectURI := r.URL.Query().Get("redirect_uri") | ||
callbackURL := fmt.Sprintf("%s?code=g0ZGZmNjVmOWI&state=%s", redirectURI, state) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. isn't this change will break back compat for dev provider? |
||
d.Logf("[DEBUG] callback url=%s", callbackURL) | ||
w.Header().Add("Location", callbackURL) | ||
w.WriteHeader(http.StatusFound) | ||
|
@@ -87,13 +104,95 @@ func (d *DevAuthServer) Run(ctx context.Context) { //nolint (gocyclo) | |
"refresh_token":"IwOGYzYTlmM2YxOTQ5MGE3YmNmMDFkNTVk", | ||
"scope":"create", | ||
"state":"12345678" | ||
}` | ||
}` | ||
|
||
if d.Provider.UseOpenID { | ||
email := d.username | ||
if d.GetEmailFn != nil { | ||
email = d.GetEmailFn(d.username) | ||
} | ||
|
||
idClaims := map[string]interface{}{ | ||
// required OpenID claims | ||
"iss": "dev-auth", | ||
"sub": "%s", | ||
"aud": "client-id", | ||
"iat": time.Now().Unix(), | ||
"exp": time.Now().Add(1 * time.Hour).Unix(), | ||
|
||
// optional OpenID claims | ||
"picture": fmt.Sprintf("http://127.0.0.1:%d/avatar?user=%s", d.Provider.Port, d.username), | ||
"given_name": d.username, | ||
"email": email, | ||
} | ||
|
||
if d.CustomizeIDTokenFn != nil { | ||
idClaims = d.CustomizeIDTokenFn(idClaims) | ||
} | ||
|
||
tk := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims(idClaims)) | ||
tk.Header["kid"] = "dev-auth-key-1" | ||
|
||
signedTk, e := tk.SignedString(privateKey) | ||
if e != nil { | ||
d.Logf("[ERROR] failed to sign ID token") | ||
w.WriteHeader(http.StatusInternalServerError) | ||
return | ||
} | ||
|
||
res = fmt.Sprintf(`{ | ||
"access_token":"MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3", | ||
"id_token": "%s", | ||
"token_type":"bearer", | ||
"expires_in":3600, | ||
"refresh_token":"IwOGYzYTlmM2YxOTQ5MGE3YmNmMDFkNTVk", | ||
"scope":"create", | ||
"state":"12345678" | ||
}`, signedTk) | ||
} | ||
|
||
w.Header().Set("Content-Type", "application/json; charset=utf-8") | ||
if _, err = w.Write([]byte(res)); err != nil { | ||
w.WriteHeader(http.StatusInternalServerError) | ||
return | ||
} | ||
|
||
case strings.HasPrefix(r.URL.Path, "/jwks") && d.Provider.UseOpenID: | ||
type jwkKey struct { | ||
Kty string `json:"kty"` | ||
N string `json:"n"` | ||
E string `json:"e"` | ||
Alg string `json:"alg"` | ||
Kid string `json:"kid"` | ||
} | ||
|
||
e := big.NewInt(int64(privateKey.E)) | ||
key := jwkKey{ | ||
Kty: "RSA", | ||
Alg: "RS256", | ||
Kid: "dev-auth-key-1", | ||
N: base64.RawURLEncoding.EncodeToString(privateKey.N.Bytes()), | ||
E: base64.RawURLEncoding.EncodeToString(e.Bytes()), | ||
} | ||
|
||
jwks, er := json.Marshal(struct { | ||
Keys []jwkKey `json:"keys"` | ||
}{ | ||
Keys: []jwkKey{key}, | ||
}) | ||
if er != nil { | ||
d.Logf("[ERROR] failed to marshal jwks") | ||
w.WriteHeader(http.StatusInternalServerError) | ||
return | ||
} | ||
|
||
w.WriteHeader(http.StatusOK) | ||
wr, er := w.Write(jwks) | ||
if er != nil || wr == 0 { | ||
d.Logf("[ERROR] failed to write jwks") | ||
w.WriteHeader(http.StatusInternalServerError) | ||
} | ||
|
||
case strings.HasPrefix(r.URL.Path, "/user"): | ||
ava := fmt.Sprintf("http://127.0.0.1:%d/avatar?user=%s", d.Provider.Port, d.username) | ||
res := fmt.Sprintf(`{ | ||
|
@@ -175,13 +274,24 @@ func NewDev(p Params) Oauth2Handler { | |
}, | ||
scopes: []string{"user:email"}, | ||
infoURL: fmt.Sprintf("http://127.0.0.1:%d/user", p.Port), | ||
jwksURL: fmt.Sprintf("http://127.0.0.1:%d/jwks", p.Port), | ||
mapUser: func(data UserData, _ []byte) token.User { | ||
if p.UseOpenID { | ||
return token.User{ | ||
ID: data.Value("sub"), | ||
Name: data.Value("given_name"), | ||
Picture: data.Value("picture"), | ||
Email: data.Value("email"), | ||
} | ||
} | ||
|
||
userInfo := token.User{ | ||
ID: data.Value("id"), | ||
Name: data.Value("name"), | ||
Picture: data.Value("picture"), | ||
Email: data.Value("email"), | ||
} | ||
|
||
return userInfo | ||
}, | ||
}) | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Check warning
Code scanning / CodeQL
Open URL redirect