2019-07-28 15:54:39 +02:00
|
|
|
package providers
|
|
|
|
|
|
|
|
import (
|
2020-05-05 17:53:33 +02:00
|
|
|
"context"
|
2019-07-28 15:54:39 +02:00
|
|
|
"net/url"
|
|
|
|
|
2020-03-29 15:54:36 +02:00
|
|
|
"github.com/oauth2-proxy/oauth2-proxy/pkg/apis/sessions"
|
|
|
|
"github.com/oauth2-proxy/oauth2-proxy/pkg/logger"
|
|
|
|
"github.com/oauth2-proxy/oauth2-proxy/pkg/requests"
|
2019-07-28 15:54:39 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
type KeycloakProvider struct {
|
|
|
|
*ProviderData
|
|
|
|
Group string
|
|
|
|
}
|
|
|
|
|
2020-05-05 17:53:33 +02:00
|
|
|
var _ Provider = (*KeycloakProvider)(nil)
|
|
|
|
|
2019-07-28 15:54:39 +02:00
|
|
|
func NewKeycloakProvider(p *ProviderData) *KeycloakProvider {
|
|
|
|
p.ProviderName = "Keycloak"
|
|
|
|
if p.LoginURL == nil || p.LoginURL.String() == "" {
|
|
|
|
p.LoginURL = &url.URL{
|
|
|
|
Scheme: "https",
|
|
|
|
Host: "keycloak.org",
|
|
|
|
Path: "/oauth/authorize",
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if p.RedeemURL == nil || p.RedeemURL.String() == "" {
|
|
|
|
p.RedeemURL = &url.URL{
|
|
|
|
Scheme: "https",
|
|
|
|
Host: "keycloak.org",
|
|
|
|
Path: "/oauth/token",
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if p.ValidateURL == nil || p.ValidateURL.String() == "" {
|
|
|
|
p.ValidateURL = &url.URL{
|
|
|
|
Scheme: "https",
|
|
|
|
Host: "keycloak.org",
|
|
|
|
Path: "/api/v3/user",
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if p.Scope == "" {
|
|
|
|
p.Scope = "api"
|
|
|
|
}
|
|
|
|
return &KeycloakProvider{ProviderData: p}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *KeycloakProvider) SetGroup(group string) {
|
|
|
|
p.Group = group
|
|
|
|
}
|
|
|
|
|
2020-05-05 17:53:33 +02:00
|
|
|
func (p *KeycloakProvider) GetEmailAddress(ctx context.Context, s *sessions.SessionState) (string, error) {
|
2020-07-03 20:27:25 +02:00
|
|
|
json, err := requests.New(p.ValidateURL.String()).
|
|
|
|
WithContext(ctx).
|
|
|
|
SetHeader("Authorization", "Bearer "+s.AccessToken).
|
2020-07-06 18:42:26 +02:00
|
|
|
Do().
|
2020-07-03 20:27:25 +02:00
|
|
|
UnmarshalJSON()
|
2019-07-28 15:54:39 +02:00
|
|
|
if err != nil {
|
2019-07-28 16:46:16 +02:00
|
|
|
logger.Printf("failed making request %s", err)
|
2019-07-28 15:54:39 +02:00
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
if p.Group != "" {
|
|
|
|
var groups, err = json.Get("groups").Array()
|
|
|
|
if err != nil {
|
2019-07-28 16:46:16 +02:00
|
|
|
logger.Printf("groups not found %s", err)
|
2019-07-28 15:54:39 +02:00
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
var found = false
|
|
|
|
for i := range groups {
|
|
|
|
if groups[i].(string) == p.Group {
|
|
|
|
found = true
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-14 10:36:44 +02:00
|
|
|
if !found {
|
2019-07-28 16:46:16 +02:00
|
|
|
logger.Printf("group not found, access denied")
|
2019-07-28 15:54:39 +02:00
|
|
|
return "", nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return json.Get("email").String()
|
|
|
|
}
|