Backend apps
You can use the IBM Cloud® App ID SDKs and APIs to protect your backend application endpoints and APIs.
Understanding the flow
Part of developing backend apps is verifying that your APIs are protected from unauthorized access. The App ID SDKs help you protect your API endpoints and ensure the security of your app.
What is the flow's technical basis?
App ID implements the OAuth 2.0 and the OIDC spec, which uses bearer tokens for authentication and authorization. These tokens are formatted as JSON Web Tokens, which are digitally signed and contain claims that describe the subject that is being authenticated and the identity provider. The APIs of your application are protected by access and identity tokens. Clients that need access to your APIs can authenticate with the identity provider through App ID in exchange for these tokens. The claims in the tokens must be validated to grant access to the protected APIs.
For more information about how tokens are used in App ID, see Understanding tokens.
What does the flow look like?
-
A client makes a POST request to the App ID authorization server to obtain an access token. A POST request generally takes the following form:
POST /oauth/v4/<tenantID>/token HTTP/1.1 Content_type: application/x-www-form-urlencoded Authorization header = "Basic" + base64encode(<clientID>:<secret>) FormData = <grantType>
-
If the client meets the qualifications, the authorization server returns an access token.
-
The client sends a request to the protected resource. Requests can be sent in multiple ways, depending on which HTTP client library you're using but a request generally takes the following form:
curl -H 'Authorization: Bearer <accessToken>' <https://my-protected-resource.com>
-
The protected resource or API validates the token. If the token is valid, access to the resource is granted for the client. If the token cannot be validated, access is denied.
For information about how to configure your app to use Liberty for Java, see Quick start: Liberty for Java backend apps tutorial.
Protecting resources by using the Node.js SDK
You can use the App ID SDKs to enforce authentication and authorization for your server-side applications. The ApiStrategy
works to secure your backend resources by requiring that access and identity tokens are validated as part
of the request. The App ID Node.js SDK works with the Passport framework.
Check out the following video to learn about protecting backend Node applications with App ID. Then, try it out yourself by using a simple Node sample app.
Before you begin
Before you get started with the Node.js SDK, you must have the following prerequisites.
- An instance of App ID
- NPM version 4 or higher
- Node version 6 or higher
Installing the Node.js SDK
-
Add the App ID Node.js SDK to your app's
package.json
file."dependencies": { "ibmcloud-appid": "^7.0.0" }
-
Run the following command.
npm install
Initializing the Node.js SDK
-
Obtain your
oauth server url
.- Navigate to the Service Credentials tab of the App ID dashboard.
- If you don't already have a set of credentials, click New credential and then click Add to create a new set. If you do, skip this step.
- Click the View credentials toggle to see your information.
- Copy your
oauth server url
to use in the next step.
-
Initialize the App ID passport strategy as shown in the following example.
var express = require('express'); var passport = require('passport'); var APIStrategy = require('ibmcloud-appid').APIStrategy; passport.use(new APIStrategy({ oauthServerUrl: "<oauthServerUrl>" })); var app = express(); app.use(passport.initialize());
Securing the API with the API Strategy
The following snippet demonstrates how to use ApiStrategy
in an Express app to protect the /protected
GET API.
If your Node.js app runs on IBM Cloud and is bound to your instance of App ID, there's no need to provide the API strategy configuration. The App ID configuration obtains the information by using the VCAP_SERVICES environment variable.
app.get('/protected_resource', passport.authenticate('APIStrategy.STRATEGY_NAME', { session: false }), function(request, response){
console.log("Security context", request.appIdAuthorizationContext);
response.send(200, "Success!");
}
);
When the tokens are valid, the next middleware in the request chain is called and the appIdAuthorizationContext
property is added to the request object. The property contains the original access and identity tokens and the decoded
payload information of the tokens.
Protecting resources by using the Swift SDK
The App ID server-side Swift SDK provides an API protection middleware plug-in that is used to protect your backend apps. By associating your APIs with the middleware, you can protect your app from unauthorized access. After the API is protected, the middleware ensures that the tokens that are generated by App ID are validated. You can then modify the behavior of the API depending on the validation results.
import Foundation
import Kitura // server
import Credentials // middleware
import IBMCloudAppID // SDK
// setup routes
let router = Router()
// mandatory option to be passed in if app not deployed on IBM Cloud
let options = [
"oauthServerUrl": "https://us-south.appid.cloud.ibm.com/oauth/v4/d8438de6-c325-4956-ad34-abd49194affd",
]
let apiCreds = Credentials()
// Minimum macOS version required
if #available(OSX 10.12, *) {
// setup API protection
let apiKituraCredentialsPlugin = APIKituraCredentialsPlugin(options: options)
apiCreds.register(plugin: apiKituraCredentialsPlugin)
// associate route with API protection
router.all(middleware: apiCreds)
// create protected API
router.get("/protectedendpoint") { request, response, next in
response.headers["Content-Type"] = "text/html; charset=utf-8"
do {
if let userProfile = request.userProfile {
try response.status(.OK).send(
"<!DOCTYPE html><html><body>" +
"Welcome " + userProfile.displayName +
"! You are logged in with " + userProfile.provider + "." +
"</body></html>\n\n").end()
next()
return
}
try response.status(.unauthorized).send(
"<!DOCTYPE html><html><body>” + “You are not authorized!" +
"</body></html>\n\n").end()
}
catch {}
next()
}
// Start server
Kitura.addHTTPServer(onPort: 8090, with: router)
Kitura.run()
}
Protecting resources manually
To secure your backend apps and protected resources, you need to validate a token. When a client sends a request to your resource, you can verify that the token meets the defined specifications. The token might include identifying information, scope, or any other configuration that you have in place. You can validate App ID access and identity tokens in several ways. For help, check out Validating tokens.
Next steps
With App ID installed in your application, you're almost ready to start authenticating users! Try doing one of the following activities next:
- Configure your identity providers
- Customize and configure the Login Widget
- Learn more about the Node.js SDK
- Learn more about the Swift SDK