1
0
mirror of https://github.com/oauth2-proxy/oauth2-proxy.git synced 2025-01-10 04:18:14 +02:00
oauth2-proxy/providers/keycloak.go

90 lines
1.9 KiB
Go
Raw Normal View History

2019-07-28 15:54:39 +02:00
package providers
import (
"context"
2019-07-28 15:54:39 +02:00
"net/http"
"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
}
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
}
func (p *KeycloakProvider) GetEmailAddress(ctx context.Context, s *sessions.SessionState) (string, error) {
2019-07-28 15:54:39 +02:00
req, err := http.NewRequestWithContext(ctx, "GET", p.ValidateURL.String(), nil)
2019-07-28 15:54:39 +02:00
req.Header.Set("Authorization", "Bearer "+s.AccessToken)
if err != nil {
logger.Printf("failed building request %s", err)
2019-07-28 15:54:39 +02:00
return "", err
}
json, err := requests.Request(req)
2019-07-28 15:54:39 +02:00
if err != nil {
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 {
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
}
}
if !found {
logger.Printf("group not found, access denied")
2019-07-28 15:54:39 +02:00
return "", nil
}
}
return json.Get("email").String()
}