-
Notifications
You must be signed in to change notification settings - Fork 2
/
auth.go
99 lines (84 loc) · 2.47 KB
/
auth.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package traefik_auth_middleware
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
)
type Config struct {
IAM map[string]string
}
func CreateConfig() *Config {
return &Config{
IAM: make(map[string]string),
}
}
type Cerbere struct {
next http.Handler
name string
clientId string
iamUrl string
userQueryParamName string
passwordQueryParamName string
}
type KeycloakResponse struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
RefreshExpiresIn int `json:"refresh_expires_in"`
TokenType string `json:"token_type"`
NotBeforePolicy int `json:"not-before-policy"`
SessionState string `json:"session_state"`
Scope string `json:"scope"`
}
func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
if len(config.IAM) != 4 {
return nil, fmt.Errorf("IAM Configuration must be defined")
}
return &Cerbere{
next: next,
name: name,
clientId: config.IAM["ClientId"],
iamUrl: config.IAM["Url"],
userQueryParamName: config.IAM["UserQueryParamName"],
passwordQueryParamName: config.IAM["PasswordQueryParamName"],
}, nil
}
func (cerbereConfig *Cerbere) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
query := req.URL.Query()
username, usernamePresent := query[cerbereConfig.userQueryParamName]
apikey, apikeyPresent := query[cerbereConfig.passwordQueryParamName]
if !usernamePresent || !apikeyPresent {
http.Error(rw, "MalformedQuery", http.StatusBadRequest)
return
}
authResponse, err := http.PostForm(cerbereConfig.iamUrl,
url.Values{
"grant_type": {"password"},
"client_id": {cerbereConfig.clientId},
"username": {username[0]},
"password": {apikey[0]},
})
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
if authResponse.StatusCode != http.StatusOK {
http.Error(rw, "Forbidden", http.StatusUnauthorized)
return
}
body, err := io.ReadAll(authResponse.Body)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
var result KeycloakResponse
err = json.Unmarshal(body, &result)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", result.AccessToken))
cerbereConfig.next.ServeHTTP(rw, req)
}