How to authenticate hyperledger user from webportal? - hyperledger-fabric

I can successfully run the fabrics example to query/insert to ledger.
I want to build a nodejs web portal and I already directly wrapped query.js in my web app code.
Now the question is, how to authenticate a user the webportal? Since the example query.js has code like:
...
return fabric_client.getUserContext('user1', true);
}).then((user_from_store) => {
if (user_from_store && user_from_store.isEnrolled())
//successfully authenticated user1
I noticed the cert/private key/pub key files in
/hfc-key-store
user1-cert
user1-private.key
user1-public.key
Do I need to post any of the keys through parameters or do I create a separate regular username password control?

In my opinion you can create a normal login system for the web portal using a database to store the credentials of the users.
In this database you can associate the user to a specific key, which is retrieved each time the user successfully login in the web portal.
In this way, you will have two different levels of authentication:
one associated to the web portal (username and password)
and the other one associated to the blockchain (the certificate to
write and read).

Related

ExternalLoginSignInAsync() failed for external users created manually

I am using my google account to authenticate on my Kentico website.
Initially, my Google account was added was by using:
userCreation = await _userManager.CreateExternalUser(loginInfo);
I would like now to prevent the automatic creation of users to avoid having people from the outside creating new users and therefore disable the CreateExternalUser() function.
I then tried to create new external user in the "Users" app in the admin website.
To do so, I didn't provide any password and I marked the new user as an external user.
When I try
signInResult = await _signInManager.ExternalLoginSignInAsync(loginInfo.LoginProvider, loginInfo.ProviderKey, isPersistent: false);
I always get a failed result.
I checked the tables (CMS.User) and the user created by CreateExternalUser and the user created by hand in the admin site look identical.
I did step by step for _signInManager.ExternalLoginSignInAsync(loginInfo.LoginProvider, loginInfo.ProviderKey, isPersistent: false); and the loginProvider (Google) and the Providerkey (1182704....61480) are also identical between the 2 users.
Why the external user created by hand return a failed result while when it is created by CreateExternalUser with the same info it works fine?
I am using Kentico 13.0.79.

How to refresh Azure AD B2C (Angular) SPA session data?

Scenario :
I am logged-in through an AD B2C account in my Angular application.
I have integrated msal-browser (^2.15.0) and msal-angular (^2.0.1), for authentication and to access session data.
I use Graph API (from my .NET server) to update my AD B2C User record from my Angular application.
Requirement :
Whenever I update the User record through Graph APIs (indirectly through my server) from my Angular application, I want my browser session to reflect those changes as well.
// user-data.service.ts
public updateUserRecord(userUpdateObj: CustomUserModel) {
this.http.put("https://my-server-calling-graph-api.com/user-data", userUpdateObj ,this.HTTP_OPTIONS)
.pipe(
map((updatedResult: CustomUserModel) => {
console.log('Updated User Record -> ', updatedResult);
// SESSION DATA
this.usersList = this.msalService.instance.getAllAccounts();
this.msalService.instance.setActiveAccount(this.usersList[0]);
const userCustomAttributes = this.usersList[0].idTokenClaims;
console.log('Existing User Record -> ', userCustomAttributes);
}),
retry(2)
);
} // FN
Question :
Is there a way to silently get the session data updated in the background through any msal service calls or should I redirect to login to receive the session data freshly?
The only way to achieve this is to call acquireTokenRedirect() or ssoSilent() MSAL method. These use cookie based logins which will then reprocess the user journey and fetch the latest data. ssoSilent() occurs in a hidden iframe. You may find, due to replication delays, that this still doesn't work reliably.
To avoid this issue, the end user can edit their user profile using an Edit Profile flow. This would be the recommended path.

How can I validate a user exists in the kuzzle database given only <kuid> and a <jwt> of that user?

I am using kuzzle (2.6) as a backend to my app. I'd like to encrypt data stored to Kuzzle by the users of the app, and organize encryption keys separate from the database. The key holding entity (keyStore for short) should give keys only to users that are truly registered in the database, without becoming able to access the user data itself.
So I'm trying to pass, from the app, when the user is logged in, a <kuid> together with a corresponding <jwt> obtained e.g. via kuzzle.auth.login('local', {username: <username>, password: <password>}) to the keyStore via https. The keyStore should send the information to the Kuzzle database, where a Kuzzle plugin can verify the user exists. If Kuzzle confirms the identity of the user to the keyStore, the keyStore will hand out a key to the user such that the user can encrypt/decrypt its data.
In short:
Is there any way I can let a plugin validate that a given <jwt> and a given <kuid> belong to the same user? <username> and <password> would both not be available to the plugin.
Kuzzle core developer here.
Right now we don't have a public API to get the user linked to an authentication token.
Still, you can use the auth:checkToken API action to verify the token validity and the jsonwebtoken package used by Kuzzle to retrieve the user kuid from the token.
const { valid } = await app.sdk.auth.checkToken(token);
if (valid) {
const kuid = require('jsonwebtoken').decode(token)._id;
}
Anyway, that's an interesting feature and we will discuss it in our next product workshop.
I will update this answer accordingly.

Python Salesforce API Authentication

I am trying to automate creating tickets in Salesforce. For this, I am using API with Python. I have got the Client ID and Client secret for my registered python Application. I have read many questions and as per the security purpose, I do not want to use the "user-password" flow for my script. Is there any way that I can only use "CLIENT ID" and "CLIENT SECRET" to get the access token where I can pass this access token in bearer header for other calls
import requests
params = {
"grant_type": "client_credentials",
"client_id": client_id, # Consumer Key
"client_secret": client_secret, # Consumer Secret
}
r=requests.post("https://login.salesforce.com/services/oauth2/token", params=params)
access_token = r.json().get("access_token")
instance_url = r.json().get("instance_url")
print("Access Token:", access_token)
You'll always need a SF user account. There's no way to just make a backend system talk to SF system. Salesforce treats everybody as user so you need to waste an account for "integration user" - but in return you can control access to tables, columns, functionalities just like you control real humans' access. This goes all the way down to the underlying Oracle database and database user privileges.
Whether you use OAuth2 flows (including client secrets) or maybe some certificate-based authentication - there will be always some element of "username and password" required. Best you can do is to make sure your app doesn't need to see & store the password, instead showing normal SF login prompt and on successful login user is redirected to your app to continue with known session id...
There might be something you'll be able to automate more if your app and SF use same Single Sign-On but broadly speaking... You have to either let users login to SF via your app or create the tickets as some dedicated admin user (and then you store this user's credentials in your app)

How implement an access token, so I can bypass login page (sailsjs)

I have a SailsJS website for which I implemented authentication through a form where user needs to fill in email and password. copied from ActivityOverloard 2.0 example code
Login
login: function(req, res) {
console.log("Login hehe!!");
// Try to look up user using the provided email address
User.findOne({
email: req.param('email')
}, function foundUser(err, user) {
if (err) return res.negotiate(err);
if (!user) return res.notFound();
console.log("found email");
// Compare password attempt from the form params to the encrypted password
// from the database (`user.password`)
require('machinepack-passwords').checkPassword({
passwordAttempt: req.param('password'),
encryptedPassword: user.encryptedPassword
}).exec({
error: function(err) {
console.log("There was an error with password");
return res.negotiate(err);
},
// If the password from the form params doesn't checkout w/ the encrypted
// password from the database...
incorrect: function() {
console.log("Password doesn't checkout w/ the encrypted");
return res.notFound();
},
success: function() {
console.log("Good password");
var now = new Date();
User.update(user.id, { online: true, lastLoggedIn: now }, function() {
// Store user id in the user session
req.session.me = user.id;
User.publishUpdate(user.id, {
online: true,
id: user.id,
name: user.name,
lastLoggedIn: now,
action: ' has logged in.'
});
// All done- let the client know that everything worked.
return res.ok();
});
}
});
});
my page is protected with login
myPage: function(req, res) {
if (!req.session.me) {
return res.view('login'); // not authenticated will take you to the login page
}
// It's authenticated, it runs the code below
// DO SOMETHING
Now a very special use case, I need to open my page without user interaction (It can't be through a form) but I still need it to be protected. I'd need to pass some kind of access token.
I understand that passing an "access token" as query param is most probably not a good idea isn't it?
In fact, I don't know how to resolve my problem and allow to access myPage other than a session based authentication through a user interaction via a form ...
It seems to me that I'd need to first get a token programmatically and then open a browse to my page ... I bet there is some best practices to address my problem out there.
Any pointers? may be someone can fill the knowledge gap.
Realisticly speaking, you have multiple options with regards to passwordless or formless logins in node.js/express.js and therefore sails.js, as sails is built on top of both.
How you would approach the solution, really depends on the scale and use of your application/applications. For example; will the same login credentials be used to access multiple applications or a single web application, will the application be available only in an intranet or across the whole WWW.
Regardless of the scenario above, there will next to always be some initial setup required by the user, whether that is an initial sign up with an identity provider or an initial sign up with your application. The sign up form, will not dissappear entirely, rather it will become a one time event.
So let's look at some options and how we might introduce them into an express/sails application/s, I will start with the most basic and work down in difficulty.
Option 1:
Make use of the sails session store. From your code, you have already started doing this. The logic works something like this:
Your user signs up or logs in for the first time. At this stage you set the users session to be authenticated.
// Store user id in the user session
req.session.me = user.id;
req.session.authenticated;
You set a policy on all the pages which require authentication. Luckily, sails has already done some of the heavy lifting here by creating a sessionAuth policy in the folder api/policies. To make use of them open the config/policies.js file and add this policy to your protected pages
'my_app' : {
'route_to_protect' : 'sessionAuth'
},
Finally, you will want to make this session cookie last a really long time, to do this open config/session.js and edit the cookie maxAge to suit your needs. For example, if you want to force the user to login every 365 days, you might do some like this:
// milliseconds * seconds * minutes * hours * days
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 365
},
The draw back to this option is that your sessions will be lost if the application is restarted and all users will have to log in again.
Option 2:
Use a simple third party library like passwordless. Passwordless offers token-based authentication for express web applications and as sails is built on top of express...
The general jist of passwordless is when a user signs up, you deliver them a link to your application via email, this will log them in and in turn set up there session. Passwordless makes use of mongo as a session store, so you can either install mongo or use something like mLab which is a Mongo Database-as-a-Service provider. For a complete run through on using passwordless, take a look at their getting start page here.
Now for the more featureful based options.
Option 3:
If you are developing an application that is public facing, making use of Passport.js with sails is a great option.
Passport is authentication middleware for Node.js. Extremely flexible and modular, Passport can be unobtrusively dropped in to any Express-based web application. A comprehensive set of strategies support authentication using a username and password, Facebook, Twitter, and more.
Passport works with Sails just like it does with Express.
There are already a shed load of guides on setting up passport out in the ether. But a great step-by-step is available here and is also the one referenced by sails in there official documentation here.
Passport is in all essence an authentication middleware. It allows users to identify themselves based on this authentication, you can develop the correct authorization functionality in your application.
Option 4:
Make use of SAML or OAuth. From a development and implementation perspective, these are by far the biggest undertaking out of the options provided.
SAML and OAuth are authorization middleware which refers to rules that determine who is allowed to do what. Both have a very similar setup and make use of an Identity Provider(IdP) and Service Provider(SP), where the IdP represents an online service that authenticates users in the flow and the SP represents an application that relies on a trusted IdP for authentication and authorization.
I am more familiar with SAML, so what follows is with reference to considerations when implementing SAML in a project.
You will first need to register your application (SP) with an IdP. With regards to IdP's, what you choose is based on the scale and requirements of your application, there are free online IdP's like ZXIDP and SSOCircle or if your application required a dedicated IdP you could look at something like OpenSSO. You could also consider creating your own Node.js IdP using the saml-idp package.
Integrating SAML into a sails application is not overly difficult. Make use of the saml2-js package.
Once all configured, the logic works something like this.
User opens their web-browser and goes to yoururl.
To authenticate the user yoururl constructs a SAML Authnrequest, signs, encrypts and encodes it.
Then yoururl redirects the user's to the IdP to authenticate.
The IdP validates the request, in the first signup/login, the IdP will ask the user to enter their username and password, after that it will use the sessioning and other than the address change in the browser address bar the user will not see much.
If the user is successfully authenticated, the IdP generates a SAML token that includes information about the user (username, etc) and redirects them with this token back to yoururl.
Finally yoururl verifies the SAML token, extracts the identity information about the user including authorisations and logs them in.

Resources