-
Notifications
You must be signed in to change notification settings - Fork 480
/
oauth2_middleware.go
163 lines (140 loc) · 4.95 KB
/
oauth2_middleware.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
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package oauth2
import (
"context"
"net/http"
"net/url"
"reflect"
"strings"
"github.com/fasthttp-contrib/sessions"
"github.com/google/uuid"
"golang.org/x/oauth2"
"github.com/dapr/components-contrib/common/httputils"
mdutils "github.com/dapr/components-contrib/metadata"
"github.com/dapr/components-contrib/middleware"
"github.com/dapr/kit/logger"
kitmd "github.com/dapr/kit/metadata"
"github.com/dapr/kit/utils"
)
// Metadata is the oAuth middleware config.
type oAuth2MiddlewareMetadata struct {
ClientID string `json:"clientID" mapstructure:"clientID"`
ClientSecret string `json:"clientSecret" mapstructure:"clientSecret"`
Scopes string `json:"scopes" mapstructure:"scopes"`
AuthURL string `json:"authURL" mapstructure:"authURL"`
TokenURL string `json:"tokenURL" mapstructure:"tokenURL"`
AuthHeaderName string `json:"authHeaderName" mapstructure:"authHeaderName"`
RedirectURL string `json:"redirectURL" mapstructure:"redirectURL"`
ForceHTTPS string `json:"forceHTTPS" mapstructure:"forceHTTPS"`
}
// NewOAuth2Middleware returns a new oAuth2 middleware.
func NewOAuth2Middleware(log logger.Logger) middleware.Middleware {
m := &Middleware{logger: log}
return m
}
// Middleware is an oAuth2 authentication middleware.
type Middleware struct {
logger logger.Logger
}
const (
stateParam = "state"
savedState = "auth-state"
redirectPath = "redirect-url"
codeParam = "code"
)
// GetHandler retruns the HTTP handler provided by the middleware.
func (m *Middleware) GetHandler(ctx context.Context, metadata middleware.Metadata) (func(next http.Handler) http.Handler, error) {
meta, err := m.getNativeMetadata(metadata)
if err != nil {
return nil, err
}
forceHTTPS := utils.IsTruthy(meta.ForceHTTPS)
conf := &oauth2.Config{
ClientID: meta.ClientID,
ClientSecret: meta.ClientSecret,
Scopes: strings.Split(meta.Scopes, ","),
RedirectURL: meta.RedirectURL,
Endpoint: oauth2.Endpoint{
AuthURL: meta.AuthURL,
TokenURL: meta.TokenURL,
},
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session := sessions.Start(w, r)
if session.GetString(meta.AuthHeaderName) != "" {
r.Header.Add(meta.AuthHeaderName, session.GetString(meta.AuthHeaderName))
next.ServeHTTP(w, r)
return
}
// Redirect to the auth server
state := r.URL.Query().Get(stateParam)
if state == "" {
id, err := uuid.NewRandom()
if err != nil {
httputils.RespondWithError(w, http.StatusInternalServerError)
m.logger.Errorf("Failed to generate UUID: %v", err)
return
}
idStr := id.String()
session.Set(savedState, idStr)
session.Set(redirectPath, r.URL)
url := conf.AuthCodeURL(idStr, oauth2.AccessTypeOffline)
httputils.RespondWithRedirect(w, http.StatusFound, url)
} else {
authState := session.GetString(savedState)
redirectURL, ok := session.Get(redirectPath).(*url.URL)
if !ok {
httputils.RespondWithError(w, http.StatusInternalServerError)
m.logger.Errorf("Value saved in state key '%s' is not a *url.URL", redirectPath)
return
}
if forceHTTPS {
redirectURL.Scheme = "https"
}
if state != authState {
httputils.RespondWithErrorAndMessage(w, http.StatusBadRequest, "invalid state")
return
}
code := r.URL.Query().Get(codeParam)
if code == "" {
httputils.RespondWithErrorAndMessage(w, http.StatusBadRequest, "code not found")
return
}
token, err := conf.Exchange(r.Context(), code)
if err != nil {
httputils.RespondWithError(w, http.StatusInternalServerError)
m.logger.Error("Failed to exchange token")
return
}
authHeader := token.Type() + " " + token.AccessToken
session.Set(meta.AuthHeaderName, authHeader)
httputils.RespondWithRedirect(w, http.StatusFound, redirectURL.String())
}
})
}, nil
}
func (m *Middleware) getNativeMetadata(metadata middleware.Metadata) (*oAuth2MiddlewareMetadata, error) {
var middlewareMetadata oAuth2MiddlewareMetadata
err := kitmd.DecodeMetadata(metadata.Properties, &middlewareMetadata)
if err != nil {
return nil, err
}
return &middlewareMetadata, nil
}
func (m *Middleware) GetComponentMetadata() (metadataInfo mdutils.MetadataMap) {
metadataStruct := oAuth2MiddlewareMetadata{}
mdutils.GetMetadataInfoFromStructType(reflect.TypeOf(metadataStruct), &metadataInfo, mdutils.MiddlewareType)
return
}