Cancel
Showing results for 
Search instead for 
Did you mean: 
Highlighted

Cannot get token using Java SDK v2.1.0 "Unable to retrieve Technical token successfully."

Experimenter
Experimenter

Hello,

 

I am trying to use the Mindsphere Java SDK (v2.1.0) and just trying to connect to the platform.

 

I first created an app by following the steps at https://developer.mindsphere.io/howto/howto-cf-running-app.html.

My app is just a simple python web server that serves static pages.

 

Then I continued with the following steps kindly explained by Siemens support, in order to create client credentials.

1) Go to Developer Cockpit you can see three tabs left top.
2) Select Authorization Management Tab.
3) Select App Credentials from left.
4) Select particular app to generate technical credential.
5) Click on issue access.
6) Note down the client id and client Secret.
7) Now you can use TokenManager API to generate the token using this above generated credentials.

I believed my client credentials are linked to my particular app, since I generated them from it. Note that this app is not bind to any service whatsoever, it's just a simple web server.

 

And finally the code that I am using to try and connect to the Mindsphere platform (I replaced the values between <…> with my real values of course).

This code is running on my desktop PC as this is the setup I want to use for the development and testing phase.

 

public static void main(String[] args) {

    RestClientConfig config = RestClientConfig.builder()
            .build();

    MindsphereCredentials credentials = MindsphereCredentials.builder()
            .clientId("<CLIENT ID>")
            .clientSecret("<CLIENT SECRET>")
            .tenant("<TENANT>")
            .build();

    AgentsClient agentsClient = AgentsClient.builder()
            .mindsphereCredentials(credentials)
            .restClientConfig(config)
            .build();

    AgentsList agentsList = null;
    try {
        agentsList = agentsClient.getAllAgents(null, 100, 0, null);
    } catch (MindsphereException e) {
        System.out.println("error: " + e.getErrorMessage());
    }

}

 

I am getting an exception with the following error: “Unable to retrieve Technical token successfully.”

I am following the guide at https://developer.mindsphere.io/resources/mindsphere-sdk-java/sdkreadme.html.

 

Is there anything I am missing? Anything wrong with the code?

Should I grant additional access rights?

 

Thanks in advance!

Nicolas

5 REPLIES 5

Re: Cannot get token using Java SDK v2.1.0 "Unable to retrieve Technical token successfully.&qu

Valued Contributor
Valued Contributor

hello @nteolane 

 

Unfortunateky SDK 2.1.0 currently does not support the use of App (Technical) credentails  to make MindSphere calls.

 

MindsphereCredentials credentials = MindsphereCredentials.builder()
            .clientId("<CLIENT ID>")
            .clientSecret("<CLIENT SECRET>")
            .tenant("<TENANT>")
            .build();

Here Client id & Client secret are Developer Service Credentials (not Token Manager Service Credentials).

 

You can use the tokenmanager-sdk release as part of SDK 2.1.1 to fetch the token and set it as usertoken.

 

MindsphereCredentials userTokencreds = MindsphereCredentials.builder()
                                        .authorization("< usertokenFromRequestHeader >")
                                        .build();

TokenManagerClient tokenManagerClient = TokenManagerClient.builder()
					  .mindsphereCredentials(userTokencreds)
					  .restClientConfig(config)
					  .build();
										
AccessTokenResponse accessTokenResponse = tokenManagerClient.getToken();

MindsphereCredentials techTokenCreds = MindsphereCredentials.builder()
                                        .authorization(accessTokenResponse.getAccessToken())
                                        .build();

Now you can use the `techTokenCreds ` object in your client to make MindSphere API calls.

 

 

However we will be adding support for App (Technical) credentials in the next version SDK 2.2 and will be available very soon.

 

Regards

Pruthula

 

Re: Cannot get token using Java SDK v2.1.0 "Unable to retrieve Technical token successfully.&am

Experimenter
Experimenter

HI,

 

I am very new to Mindsphere. I have a requirement to send some telemetry data into Mindsphere asset using Java SDK V2. While I was tying a sample application with codes given in official documentation I also encountered a token issue.

 

@psrinivas : Could you please mention where I can find / how to generate this "usertokenFromRequestHeader" token for above proposed solution ?

 

I am using following dependencies.

 

<artifactId>mindsphere-sdk-java-core</artifactId>
<version>2.1.1</version>
<artifactId>tokenmanager-sdk</artifactId>
<version>3.0</version>

 

 

Re: Cannot get token using Java SDK v2.1.0 "Unable to retrieve Technical token successfully.&am

Valued Contributor
Valued Contributor

@Buddhi 

When an application is uploaded in Developer Cockpit, a token is passed as part of the Request (@RequestHeader(value = "Authorization"). You can pass this token in the MindSphereCredentials.

Re: Cannot get token using Java SDK v2.1.0 "Unable to retrieve Technical token successfully.&am

Valued Contributor
Valued Contributor

https://developer.mindsphere.io/concepts/concept-authentication.html

 

The above link can provide you with more information.

Re: Cannot get token using Java SDK v2.1.0 "Unable to retrieve Technical token successfully.&qu

Experimenter
Experimenter

Hello,

 

I had the same issues during the implementation for the Token Management Service within my Java backend application. During the development phase of an application it is very unhandy to fetch a user token in order to be able to receive an application acces_token. Therefore I created a workaround for my java application so that I am able to receive an application access_token without a usertoken. Because it seems that there are more developers which are struggling during the implementation, I want to share my solution with you.

In the following, you can find all methods which are required to authenticate an assetClient with an application access_token:

public static AssetsClient createAssetClient()
{
    logger.info("create Assets Client with Token Service");

    return createAssetClient(authenticateWithTokenService());
}

 

 

public static MindsphereCredentials authenticateViaTokenmanagementService()
{
    ResponseEntity<TechnicalToken> responseEntity = createRestTemplate();
    String accessToken = responseEntity.getBody().getAccessToken();
    accessToken = "Bearer " + accessToken;

    MindsphereCredentials credentials = MindsphereCredentials.builder().authorization(accessToken).build();

    return credentials;
}

 

 

 

private static ResponseEntity<TechnicalToken> createRestTemplate()
{
    String url = "https://gateway.eu1.mindsphere.io/api/technicaltokenmanager/v3/oauth/token";

    RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());

    String body = "{\"appName\": \"<APPNAME>\",\"appVersion\": \"<APPVERSION>\",\"hostTenant\": \"<HOSTTENANT>\",\"userTenant\": \"<USERTENANT>\"}";

    MultiValueMap<String, String> requestHeaders = new LinkedMultiValueMap<String, String>();

	// setHeadersForAuth() reads the X_Space_auth_key from a .txt file
	// It is also possible to set this header as local variable during development
	// example how the X_Space_auth_key looks like: "X_Space_auth_key": "Basic bmJn..."
	//information regarding this header can be found here: https://developer.mindsphere.io/apis/exchange-tokenmanager/api-tokenmanager-samples.html
	
    MultiValueMap<String, String> credentialMap = setHeadersForAuth();

    requestHeaders.add("X-SPACE-AUTH-KEY", credentialMap.getFirst("X_Space_auth_key"));
    requestHeaders.add("Content-Type", "application/json");

    HttpEntity<?> httpEntity = new HttpEntity<Object>(body, requestHeaders);

    return restTemplate.exchange(url, HttpMethod.POST, httpEntity, TechnicalToken.class);
}

 

 

 

private static ClientHttpRequestFactory getClientHttpRequestFactory()
{
    HttpHost proxy = new HttpHost(proxyHost, proxyPort);

    RequestConfig config = RequestConfig.custom().setProxy(proxy).setConnectTimeout(connectionTimeoutInSeconds).build();

    CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
    return new HttpComponentsClientHttpRequestFactory(client);
}

 

I hope that this workaround will help you be developing your application for Mindsphere.

Best Regards