Skip to content
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

Add User & Groups to Userinfo #850

Merged
merged 2 commits into from
Nov 27, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -55,6 +55,7 @@
- [#797](https://github.com/oauth2-proxy/oauth2-proxy/pull/797) Create universal Authorization behavior across providers (@NickMeves)
- [#898](https://github.com/oauth2-proxy/oauth2-proxy/pull/898) Migrate documentation to Docusaurus (@JoelSpeed)
- [#754](https://github.com/oauth2-proxy/oauth2-proxy/pull/754) Azure token refresh (@codablock)
- [#850](https://github.com/oauth2-proxy/oauth2-proxy/pull/850) Increase session fields in `/oauth2/userinfo` endpoint (@NickMeves)
- [#825](https://github.com/oauth2-proxy/oauth2-proxy/pull/825) Fix code coverage reporting on GitHub actions(@JoelSpeed)
- [#796](https://github.com/oauth2-proxy/oauth2-proxy/pull/796) Deprecate GetUserName & GetEmailAdress for EnrichSessionState (@NickMeves)
- [#705](https://github.com/oauth2-proxy/oauth2-proxy/pull/705) Add generic Header injectors for upstream request and response headers (@JoelSpeed)
10 changes: 8 additions & 2 deletions oauthproxy.go
Original file line number Diff line number Diff line change
@@ -798,13 +798,19 @@ func (p *OAuthProxy) UserInfo(rw http.ResponseWriter, req *http.Request) {
http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}

userInfo := struct {
Email string `json:"email"`
PreferredUsername string `json:"preferredUsername,omitempty"`
User string `json:"user"`
Email string `json:"email"`
Groups []string `json:"groups,omitempty"`
PreferredUsername string `json:"preferredUsername,omitempty"`
}{
User: session.User,
Email: session.Email,
Groups: session.Groups,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For our ORG Groups are part of userInfo Endpoint .. Could you pls handle the Groups claim from UserInfo endpoint?

Copy link
Contributor Author

@NickMeves NickMeves Oct 29, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The session.Groups is populated from the groups claim in the IDToken in the OIDC Provider (other Providers can populate a session.Groups how they see fit as well e.g. calling a a provider Userinfo endpoint in EnrichSessionState to get more data for the session).

Using the session to populate the userinfo endpoint is the most provider agnostic way to get data uniformly across all providers.

What were you thinking is potentially missing that you needed with this implementation? I think if you are looking for anything extra dynamic from an IdP userinfo endpoint that logic belongs in the Provider implemented in EnrichSessionState.

Copy link

@anannaya anannaya Oct 29, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I adapted this function to get the grops claims, Correct me If I am missing anything.

`
// userID cand Groups claim was not present or was empty in the ID Token
if claims.UserID == "" || len(claims.Groups) == 0 {
// BearerToken case, allow empty UserID
// ProfileURL checks below won't work since we don't have an access token
if token == nil {
claims.UserID = claims.Subject
}

	profileURL := p.ProfileURL.String()
	if profileURL == "" || token.AccessToken == "" {
		return nil, fmt.Errorf("id_token did not contain user ID claim (%q)", p.UserIDClaim)
	}

	// If the userinfo endpoint profileURL is defined, then there is a chance the userinfo
	// contents at the profileURL contains the email.
	// Make a query to the userinfo endpoint, and attempt to locate the email from there.
	respJSON, err := requests.New(profileURL).
		WithContext(ctx).
		WithHeaders(makeOIDCHeader(token.AccessToken)).
		Do().
		UnmarshalJSON()
	if err != nil {
		return nil, err
	}

	userID, err := respJSON.Get(p.UserIDClaim).String()
	if err != nil {
		return nil, fmt.Errorf("neither id_token nor userinfo endpoint contained user ID claim (%q)", p.UserIDClaim)
	}
	claims.UserID = userID

	Groups, err := respJSON.Get(p.GroupsClaim).StringArray()
	if err != nil {
		return nil, fmt.Errorf("neither id_token nor userinfo endpoint contained Groups claim (%q)", p.UserIDClaim)
	}
	claims.Groups = Groups
}

return claims, nil

}
`

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah I follow! In the profileURL where there is fallback email fetching logic if it isn't in a claim, your IdP provides access to the groups as well?

That would be a very good addition to the OIDC Provider groups support; I like it.

It is out of scope from this PR -- can you make this into its own PR so we can discuss this issue specifically and work out the best implementation?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@NickMeves Sure ..Thank you so much.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just looked it up on mine (OneLogin), it includes it too 😄

So yours doesn't include the groups claim in the IDToken (which I guess makes since you mentioned they give you errors if you ask for the groups scope). But they have that data available on the profileURL?

Which OIDC IdP is this? I'm curious about that split and how many other users might be affected by that behavior with their OIDC IdP.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In case you are feeling adventurous -- I made this Issue for a refactor I noticed this needs after looking at your sample code above: #883

PreferredUsername: session.PreferredUsername,
}

rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(http.StatusOK)
err = json.NewEncoder(rw).Encode(userInfo)
69 changes: 58 additions & 11 deletions oauthproxy_test.go
Original file line number Diff line number Diff line change
@@ -1124,20 +1124,67 @@ func NewUserInfoEndpointTest() (*ProcessCookieTest, error) {
}

func TestUserInfoEndpointAccepted(t *testing.T) {
test, err := NewUserInfoEndpointTest()
if err != nil {
t.Fatal(err)
testCases := []struct {
name string
session *sessions.SessionState
expectedResponse string
}{
{
name: "Full session",
session: &sessions.SessionState{
User: "john.doe",
Email: "john.doe@example.com",
Groups: []string{"example", "groups"},
AccessToken: "my_access_token",
},
expectedResponse: "{\"user\":\"john.doe\",\"email\":\"john.doe@example.com\",\"groups\":[\"example\",\"groups\"]}\n",
},
{
name: "Minimal session",
session: &sessions.SessionState{
User: "john.doe",
Email: "john.doe@example.com",
Groups: []string{"example", "groups"},
},
expectedResponse: "{\"user\":\"john.doe\",\"email\":\"john.doe@example.com\",\"groups\":[\"example\",\"groups\"]}\n",
},
{
name: "No groups",
session: &sessions.SessionState{
User: "john.doe",
Email: "john.doe@example.com",
AccessToken: "my_access_token",
},
expectedResponse: "{\"user\":\"john.doe\",\"email\":\"john.doe@example.com\"}\n",
},
{
name: "With Preferred Username",
session: &sessions.SessionState{
User: "john.doe",
PreferredUsername: "john",
Email: "john.doe@example.com",
Groups: []string{"example", "groups"},
AccessToken: "my_access_token",
},
expectedResponse: "{\"user\":\"john.doe\",\"email\":\"john.doe@example.com\",\"groups\":[\"example\",\"groups\"],\"preferredUsername\":\"john\"}\n",
},
}

startSession := &sessions.SessionState{
Email: "john.doe@example.com", AccessToken: "my_access_token"}
err = test.SaveSession(startSession)
assert.NoError(t, err)
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
test, err := NewUserInfoEndpointTest()
if err != nil {
t.Fatal(err)
}
err = test.SaveSession(tc.session)
assert.NoError(t, err)

test.proxy.ServeHTTP(test.rw, test.req)
assert.Equal(t, http.StatusOK, test.rw.Code)
bodyBytes, _ := ioutil.ReadAll(test.rw.Body)
assert.Equal(t, "{\"email\":\"john.doe@example.com\"}\n", string(bodyBytes))
test.proxy.ServeHTTP(test.rw, test.req)
assert.Equal(t, http.StatusOK, test.rw.Code)
bodyBytes, _ := ioutil.ReadAll(test.rw.Body)
assert.Equal(t, tc.expectedResponse, string(bodyBytes))
})
}
}

func TestUserInfoEndpointUnauthorizedOnNoCookieSetError(t *testing.T) {