-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcallback.go
98 lines (85 loc) · 2.54 KB
/
callback.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
package xoauthlite
import (
"context"
"fmt"
"html/template"
"log"
"net/http"
"github.com/ninja-software/xoauthlite/oidc"
)
// renderAndLogError prints the error message to the browser, then shut down the web server gracefully
func renderAndLogError(w http.ResponseWriter, cancelFunc context.CancelFunc, errorMessage string) {
_, streamErr := fmt.Fprintf(w, errorMessage)
if streamErr != nil {
log.Printf("Failed to write to stream %v\n", streamErr)
}
echo(errorMessage)
cancelFunc()
}
// handleOidcCallback waits for the OIDC server to redirect to our listening web server
// It exchanges the `code` for a token set. If successful, the token is shown on webpage
// and the web server is shut down gracefully
func handleOidcCallback(
w http.ResponseWriter,
r *http.Request,
clientName string,
clientID string,
clientSecret string,
redirectURI string,
wellKnownConfig oidc.WellKnownConfiguration,
state string,
codeVerifier string,
cancel context.CancelFunc,
) {
var authorisationResponse, err = oidc.ValidateAuthorisationResponse(r.URL, state)
if err != nil {
renderAndLogError(w, cancel, fmt.Sprintf("%v", err))
return
}
viewModel, err := VerifyCode(clientID, clientSecret, redirectURI, wellKnownConfig, codeVerifier, authorisationResponse.Code)
if err != nil {
renderAndLogError(w, cancel, fmt.Sprintf("%v", err))
return
}
// show webpage
t := template.New("credentials")
_, parseErr := t.Parse(TokenResultView())
if parseErr != nil {
renderAndLogError(w, cancel, fmt.Sprintf("%v", parseErr))
return
}
tplErr := t.Execute(w, viewModel)
if tplErr != nil {
renderAndLogError(w, cancel, fmt.Sprintf("%v", tplErr))
return
}
cancel()
}
// VerifyCode exchange `code` and turn into token
func VerifyCode(
clientID string,
clientSecret string,
redirectURI string,
wellKnownConfig oidc.WellKnownConfiguration,
codeVerifier string,
code string,
) (*TokenResultViewModel, error) {
// echo("Received OIDC response")
var result, codeExchangeErr = oidc.ExchangeCodeForToken(wellKnownConfig.TokenEndpoint, code, clientID, clientSecret, codeVerifier, redirectURI)
if codeExchangeErr != nil {
return nil, codeExchangeErr
}
// echo("Validating token")
var claims, validateErr = oidc.ValidateToken(result.IdentityToken, wellKnownConfig)
if validateErr != nil {
return nil, validateErr
}
var viewModel = &TokenResultViewModel{
AccessToken: result.AccessToken,
RefreshToken: result.RefreshToken,
IDToken: result.IdentityToken,
Claims: claims,
Authority: wellKnownConfig.Issuer,
}
return viewModel, nil
}