简体   繁体   中英

How to authenticate Netlify identity with Go function

In the documentation for Netlify functions they show with Node how to identify if a request is from a logged in user.

https://www.netlify.com/docs/functions/#identity-and-functions

Looking through the Go structs for the context it doesn't appear that the user data is available in Go. I must be missing something. How do I validate a user and get their info from the JWT with Go Lamda functions in Netlify?

Check out this thread: https://answers.netlify.com/t/netlify-identity-and-go-functions/17810

 type Bearer struct { Identity *Identity `json:"identity"` User *User `json:"user"` SiteUrl string `json:"site_url"` Alg string `json:"alg"` } type Identity struct { URL string `json:"url"` Token string `json:"token"` } type User struct { AppMetaData *AppMetaData `json:"app_metadata"` Email string `json:"email"` Exp int `json:"exp"` Sub string `json:"sub"` UserMetadata *UserMetadata `json:"user_metadata"` } type AppMetaData struct { Provider string `json:"provider"` } type UserMetadata struct { FullName string `json:"full_name"` } func AuthMiddleware(h *Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { lc, ok := lambdacontext.FromContext(r.Context()) if !ok { err := errors.New("server error") h.logger.Errorf("error retrieving context %+v", r.Context()) http.Error(w, err.Error(), http.StatusInternalServerError) return } bearer := lc.ClientContext.Custom["netlify"] raw, err := base64.StdEncoding.DecodeString(bearer) if err != nil { h.logger.Error(err) http.Error(w, err.Error(), http.StatusInternalServerError) return } data := Bearer{} err = json.Unmarshal(raw, &data) if err != nil { h.logger.Error(err) http.Error(w, err.Error(), http.StatusInternalServerError) return } if data.User == nil { err := errors.New("forbidden") h.logger.Errorf("Unauthenticated request bearer: %+v", bearer) http.Error(w, err.Error(), http.StatusForbidden) return } h.ServeHTTP(w, r) }) }

There is also a blog: https://matthewkrump.com/2020-07-13-netlify-go-functions/ for more details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM