Custom application Integegrate on Cumulocity - cumulocity

I have a custom application developed standalone using angular 4 and bootstrap version 3.
I do build a custom application using angular-cli using 'ng build' command.
I want to integrate this application with cumulocity.
Can someone suggest the approach to integrate this application with Cumulocity considering this standalone application need to work standalone as well and within cumulocity as well?
I want to follow cumulocity brandings also. (I can modify my less files to use Cumulocity variables)

You can simply to the ng build, zip everything in the dist folder and then upload it as a custom application. The application will then run in the context of your Cumulocity tenant.
To connect to the REST endpoints of Cumulocity (documentation) you need to configure basic auth with your username and password. If you are using the ng2 http client you can do that the following way:
import {Injectable} from '#angular/core';
import {Http, Headers} from '#angular/http';
#Injectable()
export class ApiService {
constructor(private http: Http) {}
call(url): Observable<any> {
let username: string = 'username';
let password: string = 'password';
let headers: Headers = new Headers();
headers.append("Authorization", "Basic " + btoa(username + ":" + password));
return this.http.get(url, {headers: headers})
}
}
However, remember that you should not write the username and password fixed into the application because everyone could read it then. Better is to use a form to authenticate the user and only use it in the context of your Single Page Application.
For branding, you can find the defined less variables in the examples.

Related

How to integrate HTTP Digest Auth into Strongloop's Loopback?

I'm relatively new to Strongloop's Loopback.
A project I'm working on requires HTTP-Digest to use as authentication.
I have setup the ACL on the models (and endpoints). SPA client uses REST to consume services.
I'm stuck on how to use http digest auth (username:realm:password) / nonce instead of the plain login of username/password.
I still would like to use the token auth also.
I'm currently looking at the ff 3 projects though:
loopback-component-auth
passport-http
loopback-component-passport
Any help would be appreciated! Thank you!
You can use Express Middleware to configure HTTP authentication:
Use this node module: http-auth
Create digest-auth.js boot script in server/boot folder
var auth = require('http-auth');
var basic = auth.basic({
realm: "<your authentication realm>",
file: __dirname + "<path to your .htpasswd file"
});
module.exports = function (app) {
app.use(auth.connect(basic));
// Setup route.
app.get("/", (req, res) => {
res.send("Secured resource access granted!");
});
}
You can check more option available with "http-auth" module to use "username:realm:password" for authentication
Hope this would help you !

Angularfire2 custom authentication

I creating a website which has register link multiple auth providers and custom token as well. I also using AngularFire2 to communicate between Angular2 and Firebase but seem it doesn't have method similar with Firebase, e.g:
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com/");
ref.authWithCustomToken(AUTH_TOKEN, function(error, authData) {
Anyone can show up to me how can deal with issue?
To authenticate using a custom token, you can call AngularFire2's login method with the following configuration options:
angularFire.auth.login(AUTH_TOKEN, {
provider: AuthProviders.Custom,
method: AuthMethods.CustomToken
});
Internally, this will call Firebase's signInWithCustomToken method.

Multiple auth schemes in hapijs?

I am building an application using hapi.js . The clients of this application are going to be either a web application, so authentication is via JWT in the coookie or via OAuth2 clients which are going to be sending the Bearer key header.
Is there some way that the framework allows using both schemes for the same route? I want the authentication to fail if both schemes fail, but pass if either of the go through.
Look at http://hapijs.com/api#route-options under auth.strategies. This will allow you to set multiple strategies for your route. You can define the behaviour with auth.mode.
hapi supports multiple authentication strategies for a route. Register the indiviual plugins for authentication and set the default auth scheme afterwards.
var Hapi = require('hapi')
var BasicAuth = require('hapi-auth-basic')
var CookieAuth = require('hapi-auth-cookie')
// create new server instance
var server = new Hapi.Server()
// register plugins to server instance
server.register([ BasicAuth, CookieAuth ], function (err) {
if (err) {…}
server.auth.strategy('simple', 'basic', { validateFunc: basicValidationFn })
server.auth.strategy('session', 'cookie', { password: '…' })
server.auth.default('simple')
})
Each authentication scheme may require dedicated configuration (like a cookie password, a validation function, etc.) that you need to provide.

What is the proper way to set up API endpoints for usage with Keystone?

It's not clear in the docs how one would use existing Keystone models to expose API endpoints that return json within a Keystone.js app. I would simply like to be able expose REST API endpoints with Keystone and be able to use the Keystone CMS capabilities to manage content via interacting with those endpoints. Thanks!
Now that they've standardized the admin API I found that it's pretty trivial to use the same methods. For my read only APIs that are powering my react app I've done put something like this in my routes/index.js
router.get('/api/:list/:format(export.csv|export.json)',middleware.initList,require('keystone/admin/server/api/list/download'));
And I've made my own version of the admin initList middleware:
exports.initList = function(req, res, next) {
console.log('req.keystone', req.keystone);
req.keystone = keystone;
req.list = keystone.list(req.params.list);
if (!req.list) {
if (req.headers.accept === 'application/json') {
return res.status(404).json({ error: 'invalid list path' });
}
req.flash('error', 'List ' + req.params.list + ' could not be found.');
}
next();
};
You may consider using:
restful-keystone by #creynders, or
keystone-rest by #danielpquinn
I've never actually used either of these because I have my own implementation, which I will open source once Keystone implements it plugin architecture (see Keystone Issue #912: Proposed Keystone Package Architecture).
I suspect many other similar modules will start surfacing once Keystone is more "plugin friendly".

How to use Firebase's email & password authentication method to connect with AWS to make Fine Uploader S3 work?

I decided to use Fine Uploader for my current AngularJS project (which is connected to hosted on Firebase) because it has many core features that I will need in an uploader already built in but, I am having trouble understanding how to use Firebase's email & password authentication method to communicate with AWS (Amazon Web Services) to allow my users to use Fine Uploader S3 to upload content. Based on Fine Uploader blog post Uploads without any server code, the workflow goes like:
Authenticate your users with the help of an identity provider, such as Google
Use the temporary token from your ID provider to grab temporary access keys from AWS
Pass the keys on to Fine Uploader S3
Your users can now upload to your S3 bucket
The problem is that I won't be using OAuth 2.0 (which is used by Google, Facebook or Amazon to provide user identities) to allow my user's to sign into my app and upload content. Instead I will be using Firebase's email & password authentication.
So how can I make Firebase's email & password authentication method create a temporary token to grab temporary access keys from AWS and pass those keys on to Fine Uploader S3 to allow my users to upload content to S3?
To connect AWS with an outside application, Cognito is going to be a good solution. It will let you generate an OpenID token using the AWS Node SDK and your secret keys in your backend, that you can then use with the AWS JavaScript SDK and WebIdentityCredentials in your client.
Note that I'm unfamiliar with your specific plugin/tool, but this much will at least get you the OpenID and in my work it does let me connect using WebIdentityCredentials, which I imagine is what they are using.
Configure Cognito on AWS
Setup on Cognito is fairly easy - it is more or less a walkthrough. It does involve configuring IAM rules on AWS, though. How to set this up is pretty project specific, so I think I need to point you to the official resources. They recently made some nice updates, but I am admittedly not up to speed on all the changes.
Through the configuration, you will want to setup a 'developer authenticated identity', take note of the 'identity pool id', and the IAM role ARN setup by Cognito.
Setup a Node Server that can handle incoming routes
There are a lot of materials out there on how to accomplish this, but you want to be sure to include and configure the AWS SDK. I also recommend using body-parser as it will make reading in your POST requests easier.
var app = express();
var bodyParser = require('body-parser');
var AWS = require('aws-sdk');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
Create POST Function to talk with Cognito
Once you have your server setup, you then reach out to Cognito using getOpenIdTokenForDeveloperIdentity. In my setup, I use authenticated users because I expect them to come back and want to be able to continue the associations, so that is why I send in a UserID in req.body.UserIDFromAngularApp.
This is my function using express.router().
.post(function(req, res) {
if(req.body.UserIDFromAngularApp) {
var cognitoidentity = new AWS.CognitoIdentity();
var params = {
IdentityPoolId: 'your_cognito_identity_pool_id',
Logins: {
'your_developer_authenticated_identity_name': req.body.UserIDFromAngularApp
}
};
cognitoidentity.getOpenIdTokenForDeveloperIdentity(params, function(err, data) {
if (err) { console.log(err, err.stack); res.json({failure: 'Connection failure'}); }
else {
console.log(data); // so you can see your result server side
res.json(data); // send it back
}
});
}
else { res.json({failure: 'Connection failure'}); }
});
If all goes well, that will return an OpenID Token back to you. You can then return that back to your Angular application.
POST from Angular, Collect from Promise
At the very least you need to post to your new node server and then collect the OpenID token out of the promise. Using this pattern, that will be found in data.Token.
It sounds like from there you may just need to pass that token on to your plugin/tool.
In case you need to handle authentication further, I have included code to handle the WebIdentityCredentials.
angular.module('yourApp').factory('AWSmaker', ['$http', function($http) {
return {
reachCognito: function(authData) {
$http.post('http://localhost:8888/simpleapi/aws', {
'UserIDFromAngularApp': authData.uid,
})
.success(function(data, status, headers, config) {
if(!data.failure) {
var params = {
RoleArn: your_role_arn_setup_by_cognito,
WebIdentityToken: data.Token
};
AWS.config.credentials = new AWS.WebIdentityCredentials(params, function(err) {
console.log(err, err.stack);
});
}
});
}
}]);
This should get you on your way. Let me know if I can help further.
Each OAuth provider has a slightly unique way of handling things, and so the attributes available in your Firebase authenticated token vary slightly based on provider. For example, when utilizing Facebook, the Facebook auth token is stored at facebook.accessToken in the returned user object:
var ref = new Firebase(URL);
ref.authWithOAuthPopup("facebook", function(error, authData) {
if (authData) {
// the access token for Facebook
console.log(authData.facebook.accessToken);
}
}, {
scope: "email" // the permissions requested
});
All of this is covered in the User Authentication section of the Web Guide.