Skip to content

Authentication & Authorization

The most important aspects of authentication and authorization within the MindSphere platform will be presented to you. This introduction is intended to get you up and running quickly when working with MindSphere APIs. If you are interested in the concepts and more information, please check the Related Links section. After reading 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 described in this introduction. The token will contain information about what you are allowed to do, e.g. what APIs you are allowed to use.

Get a one-time Passcode to use Cloud Foundry CLI

Please consult the Before You Start section from the Getting Started for Cloud Foundry applications to learn how to do this.

Get a Token to call MindSphere APIs from your App

If you want to call a MindSphere API from your application, you need to have a valid token.

Prerequisites

  • Create an Application and deploy it: Check the Your first Cloud Foundry Application section on how to do this.
  • Register your application via the Developer Cockpit (and configure the required Roles & Scopes).
  • Assign yourself an application-specific user role.

If a logged in user accesses your application, either via the launchpad or by directly calling the application URL, a token (bearer token) will be passed as a header in the request to your application.

MindSphere offers two different ways of calling MindSphere APIs from your application:

  • Calling APIs from the backend (e.g. Cloud Foundry) by using gateway.<region>.mindsphere.io/api/...
  • Calling APIs from frontend relatively like <web-app-host>/api/...

Calling APIs from Backend

Calls from your backend to MindSphere APIs need to send an authorization header with every request. Therefore, you need to extract the header information of the request to your backend and then use the authorization header in your requests to the MindSphere APIs.

Java

The following Java Code Snippet shows you how to print out all available headers and return 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

Ensure that your production code does not contain any log outputs of secrets like tokens!

With this token you will be able to call the MindSphere APIs listed in the Important URLs section. When doing the request add the token as authorization header.

Node.js

You can do this similarily in Node.js. The following simple example uses expressjs and superagent for the API call.

 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.eu1.mindsphere.io/api/im/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

Calling APIs from the frontend uses a different authentication method. Instead of sending the authorization header we reuse the sessionid that gets set as a cookie. Additionally, you need to send the following headers:

  • origin:<webhost> should match your application route (e.g. origin:https://mytenant-myfirstapp-mytenant.eu1.mindsphere.io/; you can use the window.location.protocol and window.location.host)
  • x-xsrf-token:<XSRF-TOKEN> which is automatically provided by the MindSphere Gateway as a cookie (e.g. x-xsrf-token:e4edcb6c-bd1c-46c1-863c-421235c522a3)

A simple example using the fetch polyfill (find it on https://github.com/github/fetch) is shown below:

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

fetch('/api/im/v3/Users', {
  credentials: 'include',
  headers: {
    "Content-Type": "application/json",
    "Accept": "application/json",
    "x-xsrf-token": myXRSFToken,
    "origin": `${window.location.protocol}//${window.location.host}`
  }
})
...

Secure Access to your application

You as a developer must take care that no untrusted or unauthorized user can access your application. Therefore, MindSphere provides an out-of-the-box User and Access Management based on roles and scopes (permissions). You can find more information on this in the Roles & Scopes section.

Prerequisites

  • Create and register an application by using the Developer Cockpit.
  • Create at least one application-specific scope (e.g. myfirstapp.read).

Example

In this example we demonstrate the protection of your application (every endpoint) with expressjs and a custom middleware that intercepts every request and verifies that your request token contains the aforementioned 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

Ensure that your production code does not contain any log outputs of secrets like tokens!

Info

Keep in mind that this example is only meant for demonstration purposes and is not for productive usage.

Info

Depending on the complexity of your application you might need to use different frameworks and multiple scopes for protecting your endpoints.

Token Validation

Additionally, we advise to validate all tokens that your application is consuming. The validation of JWT access tokens is defined in RFC 7519.

Make sure you do the following:

  • Validate that the access token is signed with the only acceptable algorithm RS256.
  • Validate the access token as described in RFC 7519 - Section 7.2.
  • Validate that the payload of the access token contains at least the following claims (otherwise validation MUST fail):
  • iss: issuer (see below for more details)
  • aud: audience
  • exp: expiration time
  • iat: issued at time

The iss claim must equal to the name of a trusted issuer. By default, applications must only trust in the issuer of their application provider (i.e., trust only in access tokens issued by the application provider's Provider IAM system). The issuer of your application follows this scheme: https://<tenantname>.piam.<region>.mindsphere.io/oauth/.

Any questions left?

Ask the community


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