/
grantcallback.go
94 lines (77 loc) · 2.18 KB
/
grantcallback.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
package auth
import (
"net/http"
log "github.com/sirupsen/logrus"
"github.com/zalando/skipper/filters"
"golang.org/x/oauth2"
)
// GrantCallbackName is the filter name
// Deprecated, use filters.GrantCallbackName instead
const GrantCallbackName = filters.GrantCallbackName
type grantCallbackSpec struct {
config OAuthConfig
}
type grantCallbackFilter struct {
config OAuthConfig
}
func (*grantCallbackSpec) Name() string { return filters.GrantCallbackName }
func (s *grantCallbackSpec) CreateFilter([]interface{}) (filters.Filter, error) {
return &grantCallbackFilter{
config: s.config,
}, nil
}
func (f *grantCallbackFilter) exchangeAccessToken(code string, redirectURI string) (*oauth2.Token, error) {
ctx := providerContext(f.config)
params := f.config.GetAuthURLParameters(redirectURI)
return f.config.GetConfig().Exchange(ctx, code, params...)
}
func (f *grantCallbackFilter) loginCallback(ctx filters.FilterContext) {
req := ctx.Request()
q := req.URL.Query()
code := q.Get("code")
if code == "" {
badRequest(ctx)
return
}
queryState := q.Get("state")
if queryState == "" {
badRequest(ctx)
return
}
state, err := f.config.flowState.extractState(queryState)
if err != nil {
if err == errExpiredAuthState {
// The login flow state expired. Instead of just returning an
// error, restart the login process with the original request
// URL.
loginRedirectWithOverride(ctx, f.config, state.RequestURL)
} else {
serverError(ctx)
}
return
}
redirectURI, _ := f.config.RedirectURLs(req)
token, err := f.exchangeAccessToken(code, redirectURI)
if err != nil {
log.Errorf("Failed to exchange access token: %v.", err)
serverError(ctx)
return
}
c, err := createCookie(f.config, req.Host, token)
if err != nil {
log.Errorf("Failed to create OAuth grant cookie: %v.", err)
serverError(ctx)
return
}
ctx.Serve(&http.Response{
StatusCode: http.StatusTemporaryRedirect,
Header: http.Header{
"Location": []string{state.RequestURL},
"Set-Cookie": []string{c.String()},
},
})
}
func (f *grantCallbackFilter) Request(ctx filters.FilterContext) {
f.loginCallback(ctx)
}
func (f *grantCallbackFilter) Response(ctx filters.FilterContext) {}