Created
April 11, 2019 03:35
-
-
Save atotto/4195a759e8e06bfecd7dffe552d5e1aa to your computer and use it in GitHub Desktop.
Firebase SignInWithCustomToken
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "bytes" | |
| "encoding/json" | |
| "fmt" | |
| "io/ioutil" | |
| "log" | |
| "net/http" | |
| "os" | |
| ) | |
| const ( | |
| verifyCustomTokenURL = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyCustomToken?key=%s" | |
| ) | |
| var ( | |
| apiKey = os.Getenv("FIREBASE_WEB_API_KEY") // see https://console.firebase.google.comproject/<project_id>/settings/general/ | |
| ) | |
| // see https://github.com/firebase/firebase-admin-go/blob/1d2a52c3c8195451b5ad2e0a173906bd6eb9529d/integration/auth/auth_test.go#L199 | |
| func SignInWithCustomToken(token string) (string, error) { | |
| req, err := json.Marshal(map[string]interface{}{ | |
| "token": token, | |
| "returnSecureToken": true, | |
| }) | |
| if err != nil { | |
| return "", err | |
| } | |
| resp, err := postRequest(fmt.Sprintf(verifyCustomTokenURL, apiKey), req) | |
| if err != nil { | |
| return "", err | |
| } | |
| var respBody struct { | |
| IDToken string `json:"idToken"` | |
| } | |
| if err := json.Unmarshal(resp, &respBody); err != nil { | |
| return "", err | |
| } | |
| return respBody.IDToken, err | |
| } | |
| func postRequest(url string, req []byte) ([]byte, error) { | |
| resp, err := http.Post(url, "application/json", bytes.NewBuffer(req)) | |
| if err != nil { | |
| return nil, err | |
| } | |
| defer resp.Body.Close() | |
| if resp.StatusCode != http.StatusOK { | |
| return nil, fmt.Errorf("unexpected http status code: %d", resp.StatusCode) | |
| } | |
| return ioutil.ReadAll(resp.Body) | |
| } | |
| func main() { | |
| token, err := SignInWithCustomToken("eyJxxx") | |
| if err != nil { | |
| log.Fatal(err) | |
| } | |
| fmt.Printf("%s\n", token) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment