Implement a Token Endpoint handler
masterA Token Endpoint handler processes incoming OAuth2 token requests. Using a fosite.OAuth2Provider, you can manage the lifecycle of an access request and response.
In the handler:
- Initialize a session (e.g.,
&oauth2.JWTSession{}for JWTs). - Call
t.oauth.NewAccessRequest(ctx, r, session)to validate the request. - If an error occurs, use
t.oauth.WriteAccessError(w, ar, err)to return the error response. - Call
t.oauth.NewAccessResponse(ctx, ar)to generate the response object. - Call
t.oauth.WriteAccessResponse(w, ar, response)to write the final HTTP response to the client.
type tokenHandler struct {
ouch oauth fosite.OAuth2Provider
}
func (t *tokenHandler) TokenHandler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
session := &oauth2.JWTSession{}
ar, err := t.oauth.NewAccessRequest(ctx, r, session)
if err != nil {
t.oauth.WriteAccessError(w, ar, err)
return
}
response, err := t.oauth.NewAccessResponse(ctx, ar)
if err != nil {
t.oauth.WriteAccessError(w, ar, err)
return
}
t.oauth.WriteAccessResponse(w, ar, response)
}