forked from pace/bricks
/
oauth2.go
218 lines (171 loc) · 4.76 KB
/
oauth2.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
// Copyright © 2018 by PACE Telematics GmbH. All rights reserved.
// Created at 2018/09/03 by Mohamed Wael Khobalatte
// Package oauth2 provides a middelware that introspects the auth token on
// behalf of PACE services and populate the request context with useful information
// when the token is valid, otherwise aborts the request.
package oauth2
import (
"context"
"github.com/caarlos0/env"
opentracing "github.com/opentracing/opentracing-go"
olog "github.com/opentracing/opentracing-go/log"
"lab.jamit.de/pace/go-microservice/maintenance/log"
"net/http"
"strings"
)
type ctxkey string
var tokenKey = ctxkey("Token")
const headerPrefix = "Bearer "
// Middleware holds data necessary for Oauth processing
type Middleware struct {
URL string
ClientID string
ClientSecret string
introspectFunc introspecter
}
type token struct {
value string
userID string
clientID string
scopes []string
}
type config struct {
URL string `env:"OAUTH2_URL" envDefault:"https://cp-1-prod.pacelink.net"`
ClientID string `env:"OAUTH2_CLIENT_ID"`
ClientSecret string `env:"OAUTH2_CLIENT_SECRET"`
}
// NewMiddleware creates a new Oauth middleware
func NewMiddleware() *Middleware {
var cfg config
err := env.Parse(&cfg)
if err != nil {
log.Fatalf("Failed to parse oauth2 environment: %v", err)
}
return &Middleware{
URL: cfg.URL,
ClientID: cfg.ClientID,
ClientSecret: cfg.ClientSecret,
}
}
// Handler will parse the bearer token, introspect it, and put the token and other
// relevant information back in the context.
func (m *Middleware) Handler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Setup tracing
span, ctx := opentracing.StartSpanFromContext(r.Context(), "Oauth2")
defer span.Finish()
qualifiedToken := r.Header.Get("Authorization")
items := strings.Split(qualifiedToken, headerPrefix)
if len(items) < 2 {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
tokenValue := items[1]
var s introspectResponse
var introspectErr error
if m.introspectFunc != nil {
introspectErr = m.introspectFunc(m, tokenValue, &s)
} else {
introspectErr = introspect(m, tokenValue, &s)
}
switch introspectErr {
case errBadUpstreamResponse:
log.Req(r).Info().Msg(introspectErr.Error())
http.Error(w, introspectErr.Error(), http.StatusBadGateway)
return
case errUpstreamConnection:
log.Req(r).Info().Msg(introspectErr.Error())
http.Error(w, introspectErr.Error(), http.StatusUnauthorized)
return
case errInvalidToken:
log.Req(r).Info().Msg(introspectErr.Error())
http.Error(w, introspectErr.Error(), http.StatusUnauthorized)
return
}
t := fromIntrospectResponse(s, tokenValue)
ctx = context.WithValue(ctx, tokenKey, &t)
log.Req(r).Info().
Str("client_id", t.clientID).
Str("user_id", t.userID).
Msg("Oauth2")
span.LogFields(olog.String("client_id", t.clientID), olog.String("user_id", t.userID))
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func (m *Middleware) addIntrospectFunc(f introspecter) {
m.introspectFunc = f
}
func fromIntrospectResponse(s introspectResponse, tokenValue string) token {
t := token{
userID: s.UserID,
value: tokenValue,
clientID: s.ClientID,
}
if s.Scope != "" {
scopes := strings.Split(s.Scope, " ")
t.scopes = scopes
}
return t
}
// Request adds Authorization token to r
func Request(r *http.Request) *http.Request {
bt, ok := BearerToken(r.Context())
if !ok {
return r
}
authHeaderVal := headerPrefix + bt
r.Header.Set("Authorization", authHeaderVal)
return r
}
// BearerToken returns the bearer token stored in ctx
func BearerToken(ctx context.Context) (string, bool) {
token := tokenFromContext(ctx)
if token == nil {
return "", false
}
return token.value, true
}
// HasScope checks if scope is stored in ctx
func HasScope(ctx context.Context, scope string) bool {
token := tokenFromContext(ctx)
if token == nil {
return false
}
for _, v := range token.scopes {
if v == scope {
return true
}
}
return false
}
// UserID returns the userID stored in ctx
func UserID(ctx context.Context) (string, bool) {
token := tokenFromContext(ctx)
if token == nil {
return "", false
}
return token.userID, true
}
// Scopes returns the scopes stored in ctx
func Scopes(ctx context.Context) []string {
token := tokenFromContext(ctx)
if token == nil {
return []string{}
}
return token.scopes
}
// ClientID returns the clientID stored in ctx
func ClientID(ctx context.Context) (string, bool) {
token := tokenFromContext(ctx)
if token == nil {
return "", false
}
return token.clientID, true
}
func tokenFromContext(ctx context.Context) *token {
val := ctx.Value(tokenKey)
if val == nil {
return nil
}
return val.(*token)
}