Identifying the invoking Device from the custom C8y Microservice using Authorization Data

What product/components do you use and which version/fix level?

Cumulocity IoT 10.10

Are you using a free trial or a product with a customer license?

Customer License

What are trying to achieve? Please describe in detail.

We want to identify the invoking device from Microserivce using the Authorization data. Is it possible to identify which device’s agent has called a certian end point of the microserice and then fetch the device data from the c8y inventory API. Also, the device is using a JWT token to authenticate itself. We also wanted to know if its possible to check what kind of authentication was used to invoke the endpoint to differentiate between a device and a postman client(which uses BASIC auth).

Hi Balpreet,

The request headers that were sent by the client are forwarded to the microservice.
So in case of e.g. basic auth, you should have an Authorization header as part of the request received by the microservice, which starts with Basic . The base64 encoded token right after that contains the clients credentials.

In case of the JWT token, the Authorization header would start with Bearer and the base64 encoded token right after it should contain some details regarding the user.

In case you don’t want to parse the Authorization header, you could also just perform a request to the currentUser endpoint using the authorization header of the incoming request.

2 Likes

Hi Balpreet,
as Tristan mentioned one way is to parse the Authorization header - or use the currentUser endpoint as suggested which might give you more information you need.

You can get the header by adding this as parameter to your method (in your “@RestController” class)
@RequestHeader(HttpHeaders.AUTHORIZATION) final String authorizationHeader

In case it is Basic authentication you could parse it like this, in this case it would extract the device-username.

private String getDeviceUser(final String authorizationHeader) {
		final byte[] decoded = Base64.getDecoder().decode(authorizationHeader.replace("Basic ", ""));
		final String authDetails = new String(decoded, StandardCharsets.UTF_8).trim();
		final Pattern p = Pattern.compile("[^\\/]+(?=\\:)"); //
		final Matcher m = p.matcher(authDetails);
		if (m.find()) {
			return m.group();
		} else {
			return null;
		}
	}
2 Likes

Thanks Kai and Tristan. Your suggestion really helped.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.