Cordova fingerprint authentication on server - javascript

I am trying to create a authentication mechanism in my (cordova) app for android that will allow my users to sign in using a password and username, or allow them to scan their finger in order to sign in.
How can one verify a fingerprint registered on a client, server side? is this even possible at all using Cordova ? I tried transmitting the result of a finger scan to my server: this looked like:
FingerprintAuth.isAvailable(function(result) {
if (result.isAvailable) {
if(result.hasEnrolledFingerprints){
FingerprintAuth.show({
clientId: client_id,
clientSecret: client_secret
}, function (result) {
alert(JSON.stringify(result));
$http.post('http://192.168.149.33:3000/authorize', result).then(
function(response) {}
);
if (result.withFingerprint) {
$scope.$parent.loggedIn = true;
alert("Successfully authenticated using a fingerprint");
$location.path( "/home" );
} else if (result.withPassword) {
alert("Authenticated with backup password");
}
}, function(error) {
console.log(error); // "Fingerprint authentication not available"
});
} else {
alert("Fingerprint auth available, but no fingerprint registered on the device");
}
}
}, function(message) {
alert("Cannot detect fingerprint device : "+ message);
});
Server side i am receiving the following data (3 seperate scans):
{ withFingerprint: 't8haYq36fmBPUEPbVjiWOaBLjMPBeUNP/BTOkoVtZ2ZiX20eBVzZAs3dn6PW/R4E\n' }
{ withFingerprint: 'rA9H+MIoQR3au9pqgLAi/EOCRA9b0Wx1AvzC/taGIUc8cCeDfzfiDZkxNy5U4joB\n' }
{ withFingerprint: 'MMyJm46O8MTxsa9aofKUS9fZW3OZVG7ojD+XspO71LWVy4TZh2FtvPtfjJFnj7Sy\n' }
The patterns seems to vary every time, is there a way one can link the finger print to for example a pattern saved under a user on a database ?

Short answer
The strings returned by this API are not "fingerprint patterns". So you won't be able to authenticate the way you're thinking...
Long answer
Let's start by looking at the source code of the API it looks like you're using.
Looking at this file we see these methods:
public static void onAuthenticated(boolean withFingerprint) {
JSONObject resultJson = new JSONObject();
String errorMessage = "";
boolean createdResultJson = false;
try {
if (withFingerprint) {
// If the user has authenticated with fingerprint, verify that using cryptography and
// then return the encrypted token
byte[] encrypted = tryEncrypt();
resultJson.put("withFingerprint", Base64.encodeToString(encrypted, 0 /* flags */));
} else {
// Authentication happened with backup password.
resultJson.put("withPassword", true);
// if failed to init cipher because of InvalidKeyException, create new key
if (!initCipher()) {
createKey();
}
}
createdResultJson = true;
// ...
/**
* Tries to encrypt some data with the generated key in {#link #createKey} which is
* only works if the user has just authenticated via fingerprint.
*/
private static byte[] tryEncrypt() throws BadPaddingException, IllegalBlockSizeException {
return mCipher.doFinal(mClientSecret.getBytes());
}
Look at what's being put to "withFingerprint". It's a Base64 encoding of the encrypted client secret. Technically, this is your authentication. You would use this token to authenticate requests and your server would decrypt and validate the client secret.
Summary
Fingerprinting adds a level of security, but it is not the only means of security. A relationship needs to be established with the device and server beforehand.
I found this diagram to be helpful in understanding the intent of android's fingerprint authentication (ref: http://android-developers.blogspot.com/2015/10/new-in-android-samples-authenticating.html)

You can't authenticate fingerprint on the server, fingerprints are stored or authenticated using Live Scan/Biometric template. Authentication is done by comparing the current scan template with previously stored templates
First of all you don't have access to these stored templates(Not provided by the OS providers/Phone Manufacturers) and If we assume that you have access to those templates, then an efficient algorithm (Image based /Pattern based ) is required to compare the current template with previously stored templates. You can't simply authenticate it by string comparison.

Use cordova-plugin-fingerprint-aio for fingerprint authentication .
For further info you can consult https://www.npmjs.com/package/cordova-plugin-fingerprint-aio .

Related

Creating a user session - NODE js

I am new to node js & javascript in general. I have the below piece of code that will handle a login. I have a MYSQL database with a customer table. When the customer enters their username and password, it checks does it exist in the database. This part is working.
I now want to enhance this feature so that it will take the username and create some sort of a session variable, which can be used across the application. I am new to JS so I am not yet sure which inbuilt facilities already exist, or best practice around sessions.
I want to be able to use this session variable across the application, and for subsequent logout facility.
Can someone advise me on this, or point me in the right direction? Thanks.
case "/login":
var body = '';
console.log("user Login ");
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
var obj = JSON.parse(body);
console.log(JSON.stringify(obj, null, 2));
var query = "SELECT * FROM Customer where name='"+obj.name+"'";
response.writeHead(200, {
'Access-Control-Allow-Origin': '*'
});
db.query(
query,
[],
function(err, rows) {
if (err) {
response.end('{"error": "1"}');
throw err;
}
if (rows!=null && rows.length>0) {
console.log(" user in database" );
theuserid = rows[0].customerID;
var obj = {
id: theuserid
}
response.end(JSON.stringify(obj));
}
else{
response.end('{"error": "1"}');
console.log(" user not in database");
}
}
);
});
}
There can be multiple ways of implementing a user session.
One, you could use a browser cookie, it comes with many pros and cons and you should read about it a bit to see how its managed. This would also depend on the server you are using (express, hapi, etc).
Two, you can set a JWT token on the backend, and include it in the header of the response, then you can either use your application state or the local storage of the browser to save that token on the UI. Any such follow up requests requiring authentication should contain this auth token as a header for verification.
For more clarity, you can look into related libraries (such as passport), which make this task a lot easier.
PS: If you choose cookies, please make sure the business is going to allow it or not as the end-users do not like being tracked always. :)

Meteor - how to securely store and access settings.json variable on the client-side?

I am trying to access a secretKey on the client side of Meteor. I know that using Meteor.settings (http://docs.meteor.com/#/full/meteor_settings) seems to be the best way to access secrets.
My settings.json looks something like this:
{
"public": {
"secretKey": "topsecret!"
}
}
I need to access secretKey on client-side javascript. However, when I go to the browser and in the console I can simply type in Meteor.settings.public.secretKey and the key would be right there!
Is there a better way for me to store and access this secret key on the client-side?
If you want to access private stuff from within the client, you must perform some basic permission handling with user accounts.
Meteor.methods({
getSecretKey: function(){
var user = Meteor.users.findOne(this.userId);
if(!user){
throw new Meteor.Error("login-error", "You must be logged in.");
}
if(!Roles.userIsInRole(user, "admin")){
throw new Meteor.Error("admin-error", "You must be an admin.");
}
return Meteor.settings.secretKey;
}
});
This pseudo-code is using a method to retrieve the secret key from the client and alanning:roles to perform a simple user role check.

Creating a YouTube Service via ASP.NET using a pre-existing Access Token

I've been working on a Website for users to upload videos to a shared YouTube account for later access. After much work I've been able to get an Active Token, and viable Refresh Token.
However, the code to initialize the YouTubeService object looks like this:
UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
// This OAuth 2.0 access scope allows an application to upload files to the
// authenticated user's YouTube channel, but doesn't allow other types of access.
new[] { YouTubeService.Scope.YoutubeUpload },
"user",
CancellationToken.None
);
}
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = Assembly.GetExecutingAssembly().GetName().Name,
});
I've already got a token, and I want to use mine. I'm using ASP.NET version 3.5, and so I can't do an async call anyways.
Is there any way I can create a YouTubeService object without the async call, and using my own token? Is there a way I can build a credential object without the Authorization Broker?
Alternatively, the application used YouTube API V2 for quite some time, and had a form that took a token, and did a post action against a YouTube URI that was generated alongside the token in API V2. Is there a way I can implement that with V3? Is there a way to use Javascript to upload videos, and possibly an example that I could use in my code?
NOTE: I ended up upgrading my Framework to 4.5 to access the google libraries.
To programatically initialize a UserCredential Object you've got to build a Flow, and TokenResponse. A Flow Requires a Scope (aka the permissions we are seeking for the credentials.
using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Responses;
using Google.Apis.Auth.OAuth2.Flows;
string[] scopes = new string[] {
YouTubeService.Scope.Youtube,
YouTubeService.Scope.YoutubeUpload
};
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = XXXXXXXXXX, <- Put your own values here
ClientSecret = XXXXXXXXXX <- Put your own values here
},
Scopes = scopes,
DataStore = new FileDataStore("Store")
});
TokenResponse token = new TokenResponse {
AccessToken = lblActiveToken.Text,
RefreshToken = lblRefreshToken.Text
};
UserCredential credential = new UserCredential(flow, Environment.UserName, token);
Hope that helps.
Currently the official Google .NET client library does not work with .NET Framework 3.5. (Note: this is an old question the library hasn't supported .NET 3.5 since 2014. So the statement would have been valid then as well.) That being said you are not going to be able to create a service for the Google .NET client library using an existing access token. Also not possible to create it with an access token using any .NET Framework you would need to create your own implementation of Idatastore and load a refresh token.
Supported Platforms
.NET Framework 4.5 and 4.6
.NET Core (via netstandard1.3 support)
Windows 8 Apps
Windows Phone 8 and 8.1
Portable Class Libraries
That being said you are going to have to code this yourself from the ground up. I have done it and it is doable.
Authentication :
You have stated you have your refresh token already so I won't go into how to create that.
The following is a HTTP POST call
Refresh access token request:
https://accounts.google.com/o/oauth2/token
client_id={ClientId}.apps.googleusercontent.com&client_secret={ClientSecret}&refresh_token=1/ffYmfI0sjR54Ft9oupubLzrJhD1hZS5tWQcyAvNECCA&grant_type=refresh_token
Refresh Access token response:
{ "access_token" : "ya29.1.AADtN_XK16As2ZHlScqOxGtntIlevNcasMSPwGiE3pe5ANZfrmJTcsI3ZtAjv4sDrPDRnQ", "token_type" : "Bearer", "expires_in" : 3600 }
An call you make to the YouTube API you can either add the access token as the authorization bearer token or you can just take it on to the end of any request
https://www.googleapis.com/youtube/v3/search?access_token={token here}
I have a full post on all of the calls to the auth server Google 3 legged Oauth2 flow. I just use normal webRequets for all my calls.
// Create a request for the URL.
WebRequest request = WebRequest.Create("http://www.contoso.com/default.html");
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams and the response.
reader.Close();
response.Close();
Upgrade .NET 4+
If you can upgrade to the newest version of .NET using the library will be much easier. This is from Googles official documentation Web Applications ASP.NET. I have some additional sample code on my github account which shoes how to use the Google Drive API. Google dotnet samples YouTube data v3.
using System;
using System.Web.Mvc;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Auth.OAuth2.Mvc;
using Google.Apis.Drive.v2;
using Google.Apis.Util.Store;
namespace Google.Apis.Sample.MVC4
{
public class AppFlowMetadata : FlowMetadata
{
private static readonly IAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = "PUT_CLIENT_ID_HERE",
ClientSecret = "PUT_CLIENT_SECRET_HERE"
},
Scopes = new[] { DriveService.Scope.Drive },
DataStore = new FileDataStore("Drive.Api.Auth.Store")
});
public override string GetUserId(Controller controller)
{
// In this sample we use the session to store the user identifiers.
// That's not the best practice, because you should have a logic to identify
// a user. You might want to use "OpenID Connect".
// You can read more about the protocol in the following link:
// https://developers.google.com/accounts/docs/OAuth2Login.
var user = controller.Session["user"];
if (user == null)
{
user = Guid.NewGuid();
controller.Session["user"] = user;
}
return user.ToString();
}
public override IAuthorizationCodeFlow Flow
{
get { return flow; }
}
}
}
Top tip YouTube doesn't support service accounts your going to have to stick with Oauth2. As long as you have authenticated your code once it should continue to work.

LDAP - Find user by name only

I am not too familiar with LDAP, however I am working on authentication in a Node.js app, and the user credentials for the web app is going to be gotten from the organization's Windows domain.
I have LDAP lookups working (using the Passport.js Node module), however to make it work, I have to put the user's full-fledged DN into Node. For example, let's say:
My FQDN is mydomain.private.net.
My users are stored in an organizational unit, let's say staff.
Now, if I want to lookup user joe, I have to put this string into Node:
var username = 'CN=joe,OU=staff,DC=mydomain,DC=private,DC=net';
do i really have to keep track of all that?
What if my users are in two different organizational units? The client-side browser doesn't know that! It just knows:
username = 'joe';
password = 'xxxxx';
What if you try to log on as administrator? Administrators are always in a totally different OU by default.
Is there a way to reference an LDAP object by just the name and nothing else?
This is a general LDAP problem. You need to get a unique identifier from the user, and then look for it.
Typically this is what the uid attribute is used for. Active Directory may or may not have that populated, and generally relies on sAMAccountName which must be unique within the domain.
So you need a two step process.
1) Query for uid=joe or samAccountName=joe
2) Use the results to test a bind or password compare.
You would then use the DC=mydomain,DC=private,DC=net value as the root to search from.
(answer to my own question)
geoffc's answer was correct, and this is the working solution adapted to my Node.js app using the activedirectory npm module:
// First search for the user itself in the domain.
// If successfully found, the findUser function
// will return the full DN string, which is
// subsequently used to properly query and authenticate
// the user.
var AD = self.ADs[domain];
AD.findUser(username, function(err, user) {
if (err) {
cb(false, 'AD error on findUser', err);
return;
}
if (!user) {
cb(false, 'User does not exist', void 0);
} else {
username = user.dn;
AD.authenticate(username, password, function(err, authenticated) {
if (authenticated == false) {
cb(false, err, void 0);
return;
} else {
cb(true, 'Authenticated', void 0);
}
});
}
});

Use Gmail account to log into my App?

For the android app I'm working on, it requires the creation of a profile to send and recieve content to other users. For the login process, is it possible for the user to login with the Gmail account associated on the phone? Which would be the same account that is active to use google play.
This would make the whole login process very smooth, and I think it would be the best possible scenario.
Many thanks!
Yes it is possible, and it is quiet simple. Before you start you need to add, one permission to you AndroidManifest.xml
<uses-permission android:name="android.permission.GET_ACCOUNTS"></uses-permission>
It allows you to read the accounts associated with the device. Then you do the following inside the app:
Account[] accounts = AccountManager.get(context).getAccountsByType("com.google");
This will return all google accounts of the user. In your case maybe you need only the emails, so here is a quick static function that will give them to you:
public static String[] getAccounts(Context context) {
Account[] accounts = AccountManager.get(context).getAccountsByType("com.google");
String[] names = new String[accounts.length];
for (int i = 0; i < accounts.length; ++i) names[i] = accounts[i].name;
return names;
}
This function will return a string array of all gmail emails (Google accounts) on the device.
However, if you need to "talk" with some Google services for some more information, you will have to do the following. First add one more permission to the manifest:
<uses-permission android:name="android.permission.USE_CREDENTIALS"></uses-permission>
This permission will allow your app to use the use credentials to identify the user in front of some Google service. It will NOT give you the credentials(passwords).
To use some Google service you will need a token. Here it is a quick function for that:
public static String getToken(Activity activity, String serviceName) {
try {
Bundle result = AccountManager.get(activity).getAuthToken(account, serviceName, null, activity, null, null).getResult();
return result.getString(AccountManager.KEY_AUTHTOKEN);
} catch (OperationCanceledException e) {
Log.d("Test", "Operation Canceled");
} catch (AuthenticatorException e) {
Log.d("Test", "Authenticator Exception");
} catch (IOException e) {
Log.d("Test", "Auth IOException");
}
return null;
}
Once you have the token you just the HTTP API they have and you have fun :-)

Categories