Skip to content

Authentication & Authorization

This section describes the most important aspects of authentication and authorization within MindSphere. It gets you up and running quickly when working with MindSphere APIs. After referring to this introduction, you will be able to do the following:

  • Call MindSphere APIs from Cloud Foundry applications.
  • Call MindSphere APIs from frontend applications (e.g. AJAX call from JavaScript).
  • Secure your application by an application specific scope.

Introduction

All MindSphere Endpoints are secured and can only be reached after a successful authentication. You will then be provided with a token that can be obtained by different ways as described in the following sections. The token will contain information about what you are allowed to do, e.g. what APIs you are allowed to use.

Get a Token to call MindSphere APIs from your Application

Running Applications in MindSphere

Your application requires a valid token for calling MindSphere APIs. If a logged in user accesses your application, either via the Launchpad or by directly calling the application URL, a token (bearer token) is passed as a header in the request to your application.

MindSphere offers two ways of calling MindSphere APIs from applications:

  • Calling APIs from the backend (e.g. Cloud Foundry) by using gateway.{region}.{mindsphere_domain}/api/...
  • Calling APIs from frontend relatively like {web_app_host}/api/...

Calling APIs from Backend

Calls from the backend to MindSphere APIs must send an authorization header with every request. Extract the header information from the request to your backend and reuse the authorization header in your requests to MindSphere APIs.

Java

The following Java Code Snippet prints out all available headers and returns the token.

1
2
3
4
5
6
7
8
private String extractToken(HttpServletRequest request) {
  Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
      String header = headerNames.nextElement();
      LOGGER.info("header " + header +  " " + request.getHeader(header));
    }
    return request.getHeader("authorization");
}

Logging of Tokens

Production code must not output any logs of secrets like tokens!

Add this token as authorization header when sending requests to the MindSphere APIs listed in the Important Urls section.

Node.js

The following Node.js Snippet uses expressjs and superagent to access an API - line 7 contains placeholders for the region and MindSphere domain.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
var request = require("superagent");
...

app.get('my-route', function (req, res) {
  authHeader = req.get("authorization");
  request
  .get('https://gateway.{region}.{mindsphere-domain}/api/identitymanagement/v3/Users?attributes=meta,name,userName,active')
  .set('Authorization', authHeader)
  .set('Accept', 'application/json')
  .then(function(data) {
      res.json({
        resources: data.body.resources
      });
  }).catch(err => {
      console.error(err.message, err.status);
      res.status(err.status).json({ message: 'Failed to fetch users.'});
  });
});

...

Calling APIs from Frontend

When calling APIs from the frontend, the authorization header is not required. Reuse the sessionid that is set as a cookie instead and send the following header which is provided as a cookie (e.g. x-xsrf-token:e4edcb6c-bd1c-46c1-863c-421235c522a3) by the MindSphere Gateway:

1
x-xsrf-token:{XSRF-TOKEN}

The following example uses the Fetch API:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
let myXRSFToken = ...

fetch('/api/identitymanagement/v3/Users', {
  credentials: 'include',
  headers: {
    "Content-Type": "application/json",
    "Accept": "application/json",
    "x-xsrf-token": myXRSFToken
  }
})
...

Secure Access to your Application

You as a developer must take care that no untrusted or unauthorized user can access your application. MindSphere provides a security concept using roles, scopes and tokens to every registered application. For more information on these terms, refer to the Roles & Scopes section.

Example

In this example, an application (every endpoint) is protected using expressjs and a custom middleware that intercepts every request and verifies that the request token contains the an application specific scope.

 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
var jwt = require('jsonwebtoken');
var path = require('path');
var includes = require('lodash/includes')

const express = require('express')
const app = express()

// Middleware for checking the scopes in the user token
app.use('/', function (req, res, next) {
  const authorizationHeader = authHeader = req.get("authorization");
  var scopes = [];

  if (authorizationHeader != null) {
    token = jwt.decode(authorizationHeader.replace("bearer ", ""), { complete: true, json: true })
    scopes = token.payload.scope;
  }

  console.log("scopes: ", scopes); // output all scopes

  if (includes(scopes, `${config.mdsp.appname}.${config.mdsp.scope}`)) {
    console.log("request with valid application token")
    next();
  } else {
    console.log("unauthorized request");
    res.status(403).send('no access!');
  }
});
...

Logging of Tokens

Production code must not output any logs of secrets like tokens!

Info

This example is only meant for demonstration purposes and not for productive usage.
Depending on the complexity of your application, you might need to use different frameworks and multiple scopes for protecting your endpoints.

Token Validation

Access tokens issued by MindSphere are JSON Web Tokens (JWTs) as defined in RFC 7519. It is recommended to validate all tokens consumed by your application as described in RFC 7519 - Section 7.2. This validation can be performed offline, i.e. without sending the token to another service.

Info

For details on how to process and validate signed JWTs, refer to RFC 7519 and related RFCs, especially RFC 7515 and RFC 7518.

Validation Recommendations

The following sections provide additional hints for the token validation.

Tip

There are libraries available for validating JWTs, see e.g. https://jwt.io.

Payload Validation

Validate the access token using the following payload claims:

Claim Condition
iss Should match the name of a trusted issuer. By default, applications must only trust tokens issued by the application provider (i.e., the application provider's Provider IAM system). On developer and operator tenants the issuer identifier follows the scheme: https://{provider_tenant_name}.piam.{region}.{mindsphere-domain}/oauth/token.
exp Should be after the current date/time. Developers may provide for a small leeway of a few minutes to allow for clock skew.
iat Should be before or equal to the current date/time. Developers may provide for a small leeway of a few minutes to allow for clock skew.

MindSphere issued tokens do not contain a nbf claim.
scope Should match the values expected by your web application or web API, e.g. api1.do.
aud This step is optional if the audience is encoded in the scope values.
Should match the values expected by your web application or web API, e.g. api1.

Signature Validation

  1. Verify that the access token is signed with a trusted and expected algorithm by checking the value of the alg claim. MindSphere does not issue JWTs with alg = none. Currently, MindSphere signs all tokens using RS256.
  2. Verify that the kid claim in the token header refers to a public key which is valid in the context of the token issuer.
  3. Verify the token signature using the referenced algorithm and the public key.

    Public Keys for Signature Verification

    Public keys for signature verification of tokens issued by MindSphere operator or developer tenants are available at: https://{tenant_name}.piam.{region}.{mindsphere_domain}/token_keys. Make sure to download the public keys from a trusted source using TLS. For further details refer to the OAuth Authorization Server documentation.

    The key pairs for creation and verification of token signatures are regularly updated in MindSphere. Components using those keys should regularly check for updates.

Any questions left?

Ask the community


Except where otherwise noted, content on this site is licensed under the MindSphere Development License Agreement.