FCM HTTP v1: how to get access token using Go?

Viewed 2391

In order to send Firebase Cloud Messaging with Go, we need to place the access token in the HTTP request header.

On Firebase documentation, there are examples on how to retrieve the access token using Node.JS, Python and Java:

https://firebase.google.com/docs/cloud-messaging/auth-server

can anyone show the get the access token using Go?

There seems to be many Go packages about Firebase/Google authentication. It's very confusing to understand which ones should be used:

  • firebase.google.com/go
  • firebase.google.com/go/auth
  • github.com/firebase/firebase-admin-go
  • google.golang.org/api/option
  • golang.org/x/oauth2
  • golang.org/x/oauth2/google
  • github.com/google/google-api-go-client
3 Answers

FCM httpv1 use JSON file for it credentials.

Download it first, then move it to your project. download JSON credentials in your firebase

second, do :

go get "golang.org/x/oauth2/google"

then use this method to get token

const firebaseScope = "https://www.googleapis.com/auth/firebase.messaging"

type tokenProvider struct {
    tokenSource oauth2.TokenSource
}

// newTokenProvider function to get token for fcm-send
func newTokenProvider(credentialsLocation string) (*tokenProvider, error) {
    jsonKey, err := ioutil.ReadFile(credentialsLocation)
    if err != nil {
        return nil, errors.New("fcm: failed to read credentials file at: " + credentialsLocation)
    }
    cfg, err := google.JWTConfigFromJSON(jsonKey, firebaseScope)
    if err != nil {
        return nil, errors.New("fcm: failed to get JWT config for the firebase.messaging scope")
    }
    ts := cfg.TokenSource(context.Background())
    return &tokenProvider{
        tokenSource: ts,
    }, nil
}

func (src *tokenProvider) token() (string, error) {
    token, err := src.tokenSource.Token()
    if err != nil {
        return "", errors.New("fcm: failed to generate Bearer token")
    }
    return token.AccessToken, nil
}

Then call it in your FCM-Send method :

tp, err := newTokenProvider("yourJSONFileLocation")
if err != nil {
    return nil, err
}
token, err := tp.token()
if err != nil {
    return nil, err
}

last, add it to header :

r.Header.Add("Authorization", "Bearer "+token)

Done.

i am put header Authorization by used volly

  @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headerMap = new HashMap<String, String>();
                headerMap.put("Content-Type", "application/json");
                headerMap.put("Authorization", "Bearer " + key);
                Log.v(TAG,"getHeaders "+headerMap);

                return headerMap;
            }

but send Authorization=Bearer Add..

how change to current Authorization:Bearer

Related