Get client access token

Prerequisites

Use a library

WARNING

We do not recommend implementing this flow manually. There are good OAuth 2.0 libraries for all common languages.

You are expected to reuse the obtained token until it expires. It can be kept in memory, and you are not required to keep a shared cache for your servers.

This is handled automatically for some libraries; Go's clientcredentialsopen in new window TokenSource function supplies an up-to date token with automatic refreshing, which is also the case for our Java library (github.com/working-group-two/wgtwo-authopen in new window).

Example

Get client credentials for subscription.read and subscription.write

export CLIENT_ID="my client ID"
export CLIENT_SECRET="my client secret"

curl -u $CLIENT_ID:$CLIENT_SECRET \
  --request POST \
  --url 'https://id.wgtwo.com/oauth2/token' \
  --header 'content-type: application/x-www-form-urlencoded' \
  --data grant_type="client_credentials" \
  --data scope="subscription.read subscription.write"
1
2
3
4
5
6
7
8
9
Install dependencies

Maven

<dependency>
  <groupId>com.wgtwo.api</groupId>
  <artifactId>auth</artifactId>
  <version>0.0.5</version>
</dependency>
import com.wgtwo.auth.WgtwoAuth

fun main() {
    val clientId = System.getenv("CLIENT_ID")
    val clientSecret = System.getenv("CLIENT_SECRET")
    val wgtwoAuth = WgtwoAuth.builder(clientId, clientSecret).build()

    val scope = "subscription.read subscription.write"
    val token = wgtwoAuth.clientCredentials.fetchToken(scope)

    println("Got access token ${token.accessToken} which expires at ${token.expiry}")
}
1
2
3
4
5
6
7
8
9
10
11
12

Example usage

package com.example.grpc

import com.wgtwo.auth.WgtwoAuth
import com.wgtwo.api.v1.sms.SmsServiceGrpc
import com.wgtwo.api.v1.sms.sendTextFromSubscriberRequest
import io.grpc.ManagedChannelBuilder

lateinit var wgtwoAuth: WgtwoAuth

fun main() {
    // Get token source (cache with automatic refresh)
    val tokenSource = wgtwoAuth.clientCredentials.newTokenSource("subscription.read subscription.write")

    val channel = ManagedChannelBuilder.forTarget("api.wgtwo.com:443").build()
    val stub = SmsServiceGrpc.newBlockingStub(channel)
        .withCallCredentials(tokenSource.callCredentials())

    val request = sendTextFromSubscriberRequest {
        fromSubscriber = "+4799000000"
        toAddress = "+4799990000"
        content = "Testing 1, 2, 3"
    }
    val response = stub.sendTextFromSubscriber(request)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package main

import (
	"context"
	"fmt"
	"golang.org/x/oauth2/clientcredentials"
	"os"
)

func main() {
	scopes := []string{"subscription.read", "subscription.write"}
	clientCredentialsConfig := &clientcredentials.Config{
		ClientID:     os.Getenv("CLIENT_ID"),
		ClientSecret: os.Getenv("CLIENT_SECRET"),
		Scopes:       scopes,
		TokenURL:     "https://id.wgtwo.com/oauth2/token",
	}
	tokenSource := clientCredentialsConfig.TokenSource(context.Background())

	token, err := tokenSource.Token()
	if err != nil {
		panic(err)
	}

	fmt.Printf("Got access token %v which expires at %v\n", token.AccessToken, token.Expiry)
}
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

Example usage

package main

import (
	"context"
	"fmt"
	wgtwoSipBreakout "github.com/working-group-two/wgtwoapis/wgtwo/sipbreakout/v1"
	"golang.org/x/oauth2"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/credentials/oauth"
)

// Token source from above
var tokenSource oauth2.TokenSource

func main() {
	conn, err := grpc.Dial(
		"api.wgtwo.com:443",
		grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
		grpc.WithPerRPCCredentials(oauth.TokenSource{TokenSource: tokenSource}),
	)

	if err != nil {
		panic(err)
	}
	defer conn.Close()

	client := wgtwoSipBreakout.NewSipBreakoutServiceClient(conn)
	request := &wgtwoSipBreakout.UpsertRegistrationRequest{
		Registration: &wgtwoSipBreakout.Registration{
			MobileOriginatingPrefix: "11",
			MobileTerminatingPrefix: "22",
			SipUri:                  "sips:example.com:8888",
			RouteType:               wgtwoSipBreakout.RouteType_ROUTE_TYPE_LOOP,
		},
	}
	response, err := client.UpsertRegistration(context.Background(), request)

	if err != nil {
		panic(err)
	}

	fmt.Printf("Got status: %v", response.StatusCode)
}
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

Resources

Reference

OAuth 2.0 Reference