-
-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathoauth2_token.go
50 lines (41 loc) · 1.58 KB
/
oauth2_token.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
package authorizationserver
import (
"log"
"net/http"
)
func tokenEndpoint(rw http.ResponseWriter, req *http.Request) {
// This context will be passed to all methods.
ctx := req.Context()
// Create an empty session object which will be passed to the request handlers
mySessionData := newSession("")
// This will create an access request object and iterate through the registered TokenEndpointHandlers to validate the request.
accessRequest, err := oauth2.NewAccessRequest(ctx, req, mySessionData)
// Catch any errors, e.g.:
// * unknown client
// * invalid redirect
// * ...
if err != nil {
log.Printf("Error occurred in NewAccessRequest: %+v", err)
oauth2.WriteAccessError(ctx, rw, accessRequest, err)
return
}
// If this is a client_credentials grant, grant all requested scopes
// NewAccessRequest validated that all requested scopes the client is allowed to perform
// based on configured scope matching strategy.
if accessRequest.GetGrantTypes().ExactOne("client_credentials") {
for _, scope := range accessRequest.GetRequestedScopes() {
accessRequest.GrantScope(scope)
}
}
// Next we create a response for the access request. Again, we iterate through the TokenEndpointHandlers
// and aggregate the result in response.
response, err := oauth2.NewAccessResponse(ctx, accessRequest)
if err != nil {
log.Printf("Error occurred in NewAccessResponse: %+v", err)
oauth2.WriteAccessError(ctx, rw, accessRequest, err)
return
}
// All done, send the response.
oauth2.WriteAccessResponse(ctx, rw, accessRequest, response)
// The client now has a valid access token
}