Get automatically device ID and Access Token

Hi guys,

I’m trying to develop a simple control panel for user who have no idea of how Spark Core works.
Inspired by the great web interface http://jflasher.github.io/spark-helper/ made by jflahser, I would like to make something similar but without having to ask for the Device ID or Access Token.

I don’t really know if it is possible. What I’m thinking about is that the first time you run SmartConfig on your smartphone to config your Spark Core, its ID is sent to the Spark IDE as well as the Acces Token that is generated there.

Is there any way to get automatically the device ID of a Spark Core and a valid Access Token without having to Log into the Spark IDE?

Thanks!

The short answer is yes; the Core broadcasts its device ID when it connects to the network, and you can get a valid access token through an OAuth login (though you need a login/password).

@zachary you know the details best, can you provide them here?

1 Like

After the Core successfully handshakes with the Cloud, it announces its device ID on the local subnet with a CoAP message. The UDP multicast address is 224.0.1.187 port 5683. The UDP payload is 19 bytes, the last 12 of which are the device ID.

https://github.com/spark/core-firmware/blob/master/src/spark_utilities.cpp#L459

You can get the access token by sending a POST request to https://api.spark.io/oauth/token — this will currently destroy your existing token and return a new one. I’m working on allowing multiple tokens this week. We currently only support OAuth2 password grant type. A client must be sent in HTTP Basic auth, but it does not matter what the client credentials are—just use client ID spark, password spark. Example request (ignoring TLS):

POST /oauth/token HTTP/1.1
Host: api.spark.io
Authorization: Basic c3Bhcms6c3Bhcms=
Content-Type: application/x-www-form-urlencoded

grant_type=password&username=zac@example.com&password=A3ddj3w

You can generate this in your terminal with curl like this:

curl -v -u spark:spark -d grant_type=password -d username=zac@example.com -d password=A3ddj3w https://api.spark.io/oauth/token

The response will look like this:

{
  "access_token": "620de9a6251604f85ff89a84e354db957121814d",
  "token_type": "bearer",
  "expires_in": 7776000
}

Once you have an access token, you can get a list of devices owned by that user with a GET /v1/devices request too, which is more reliable than being there to catch the UDP multicast.

2 Likes

@zachary Nice clean way of getting the access_token, and very secure since it’s generating a fresh one upon request.

Just in case anyone is looking for a way to get the access_token without changing it, try this method:
https://community.spark.io/t/cloud-api-for-access-token/1020