Authenticate External App to Salesforce instance - authentication

I am building a mobile application that will need to fetch data from my salesforce instance. I have no problem with SOQL to grab the appropriate data. However, I do not want the user of the mobile app to have to log in to get a token, which I need to use to access the data.
Is it possible to authenticate the app via appId and client secret in the application to allow the appropriate use/access of the APIs? This would be similar to authenticating an app to a Parse or Firebase instance without requiring an authenticated user.
Thanks!

This is an example in nodejs/Express , in this example i get the accounts:
var express = require('express');
var router = express.Router();
var nforce = require('nforce');
/* GET home page. */
router.get('/', function(req, res, next) {
var accounts =[];
// create the connection with the Salesforce connected app
var org = nforce.createConnection({
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
redirectUri: process.env.CALLBACK_URL,
mode: 'single'
});
// authenticate and return OAuth token
org.authenticate({
username: process.env.USERNAME,
password: process.env.PASSWORD+process.env.SECURITY_TOKEN
}, function(err, resp){
if (!err) {
console.log('Successfully logged in! Cached Token: ' +
org.oauth.access_token);
// execute the query
org.query({ query: 'select id, name from account' }, function(err, resp){
if(!err && resp.records) {
// output the account names
for (i=0; i<resp.records.length;i++) {
//console.log(resp.records[i].get('name'));
accounts.push(resp.records[i].get('name'));
}
res.render('index', { title:'Accounts',accounts:accounts });
}
});
}
if (err) console.log(err);
});
//console.log(accounts);
});
module.exports = router;
You need to get you api crendentials for authenticate , it does not matter what language are you using the concept is the same.
USERNAME : Your Salesforce User name
PASSWORD: Your Salesforce Password
SECURITY_TOKEN: Your user security token , if you don't have it you can go to My Settings -Personal -Reset my security token and Salesforce will send you the token to your email.
The other parameters are parameters you get from your app , so you have to register the app to get the security tokens.
For create a connected apd You go to : Setup -Build-Create Apps in the section of Connected Apps create a new one. the connected api generate a consumer key and a Consumer secret.
CLIENT_ID: Is the consumer key
CLIENT_SECRET:Is the Consumer secret
CALLBACK_URL: The callback url in my example is : http://localhost:3000

This is not natively possible. All access to data/meta data in salesforce goes through a salesforce user account.
User accounts auth via username/pass, or via SSO (oAuth/SAML), or "Delegated Auth" (a pre-SAML auth service).
Creating a "Connected App" is a feature, enabled by the salesforce admin, which enables your mobile app to connect via oAuth, along with a public/private key pair.
However, Login is still required.
Perhaps you could place middleware between salesforce and your API - the middleware would connect to salesforce using a salesforce user account, while the API that it exposes accepts your public/private key.

Related

NextJS/Next-Auth Backend Authentication with OAuth

I am currently building a web app based on a turborepo (monorepo) in which I want to use Discord OAuth login with next-auth. Therefore I have two modules web and api, where api is my express backend with discord.js. The web app is basically a dashboard for a Discord bot.
I figured that next-auth only provides client side authentication. So my question is how can I validate the OAuth session from the client side in the best manner?
My middleware for express currently looks like this:
function throwUnauthorized(res: Response) {
res.status(401).json({ code: 401, message: 'Unauthorized' });
}
export async function isAuthorized(req: Request, res: Response, next: NextFunction) {
try {
const authorization = req.headers.authorization;
if (!authorization) {
return throwUnauthorized(res);
}
// validate token with Discord API
const { data } = await axios.get('https://discord.com/api/oauth2/#me', {
headers: { Authorization: authorization },
});
// protect against token reuse
if (!data || data.application.id !== process.env.TC_DISCORD_CLIENT_ID) {
return throwUnauthorized(res);
}
// map to database user
let user = await User.findOne({ id: data.user.id });
user ??= await User.create({ id: data.user.id });
data.user.permissions = user.permissions;
req.user = data.user;
next();
} catch (error) {
return throwUnauthorized(res);
}
}
In this approach the Discord OAuth Token would be send via the Authorization header and checked before each request that requires Authorization. Which leads to my problem: The token needs to be validated again causing multiple request to Discord API.
Is there a better way to handle this? Because I need to map Discord user profiles to database profiles. I read that you could try decode the jwt session token from next-auth, but this did not work when I tested it.
Maybe there is a whole different project structure suggested for my project. But I thought I should separate the api and web-app since I would have needed a custom express server because it includes the Discord bot and Prometheus logging functions. I am open for suggestions and your thoughts!

Octokit - how to authenticate as an app (JWT)

So I'm building a github app, and I am wanting to be able to authenticate as the app so I can do graphql calls as that user. So, I can authenticate as the app, and get the JWT, but I can't seem to use the JWT. Code looks like:
const { Octokit } = require("#octokit/core");
const { createAppAuth} = require("#octokit/auth-app");
const fs = require('fs')
const auth = createAppAuth( {
appId: process.env.APP_ID,
privateKey: fs.readFileSync(__dirname + "/../" + process.env.PRIVATE_KEY_PATH, "utf-8"),
clientId: process.env.CLIENT_ID,
clientSecret: process.env.WEBHOOK_SECRET
})
// Send requests as GitHub App
async function main() {
const {token} = await auth({type: "app"})
console.log(token);
const appOctokit = new Octokit({
baseUrl: 'https://github.<company>.com/api/v3',
auth: `token ${token}`
});
const { slug } = await appOctokit.request("GET /user");
console.log("authenticated as %s", slug);
}
main().then().catch(err => {
console.log(err.message)
console.log(err.stack)
console.log("oops")
})
I end up getting an HttpError: Bad Credentials.
What am I missing?
The reason for the bad credentials error though is that you are trying to authenticate as the app for the GET /user request. This is a user-specific request, which requires an OAuth token.
Try sending GET /app instead, it should work.
If you do want to authenticate as a user, then there are two ways to receive an OAuth token through a GitHub App (GitHub calls these user-to-server token, because the token is authorized by both, the app and the user).
OAuth Web flow
OAuth Device flow
For the Web Flow, see https://github.com/octokit/auth-app.js/#user-authentication-web-flow. You will need a server that can receive the http redirect from GitHub. You can use the #octokit/app SDK which exports a node middleware for that and other OAuth related usecases , as well as webhooks: https://github.com/octokit/app.js/#middlewares
For the OAuth Device Flow, see https://github.com/octokit/auth-app.js/#user-authentication-device-flow.
If you want to authenticate using the OAuth Device Flow without exposing the OAuth Client Secret, you can use the dedicated OAuth Device Flow authentication strategy: https://github.com/octokit/auth-oauth-device.js

How to pass Firebase Auth Token from client to server?

The website that I'm working on uses Firebase authentication and different users that login have different permissions as to which pages they can visit.
The way signing in is setup is similar to this post:
User Logins in with two parameters - "id" and "email"
Server uses these to create a custom "uid", then uses the Firebase Admin SDK to create a custom token that is sent back to the client.
The client logs in with the Javascript Firebase SDK - firebase.auth().signInWithCustomToken()
Now that the user is logged in, they can click different pages - i.e. '/foo', '/bar'
The issue I'm running into is that when they visit new pages, I'm trying to pass the token from the client back to the server (almost identical to how its done in this Firebase Doc ), verify the token & check if it has permission to view the webpage.
I'm trying to figure out the best (& most secure) way to do this. I've considered the following option:
Construct a URL with the token, but I've heard this isn't good practice because the token is getting exposed and session hijacking becomes a lot easier.
I've been trying to pass the token in the request header, but from my understanding you can't add headers when the user clicks on a link to a different page (or if its redirected in javascript). The same issue applies to using POST.
What can I do to securely pass this information to the server and check permissions when a user clicks on a link to a different page?
You can get the accessToken (idToken) on client side by:
var accessToken = null;
firebase.auth().currentUser
.getIdToken()
.then(function (token) {
accessToken = token;
});
and pass it in your request headers:
request.headers['Authorization'] = 'Bearer ' + accessToken;
and on your server side get the token with your prefered method and authenticate the request with Firebase Admin SDK, like (Node.js):
firebaseAdmin.auth()
.verifyIdToken(accessToken)
.then(decodedIdToken => {
return firebaseAdmin.auth().getUser(decodedIdToken.uid);
})
.then(user => {
// Do whatever you want with the user.
});
Nowadays, it looks like we're meant to use httpsCallable() client-side to get an object pre-authorized to talk to your endpoint.
eg:
// # ./functions/index.js
exports.yourFunc = functions.https.onCall((data, context) => {
// Checking that the user is authenticated.
if (!context.auth) {
// Throwing an HttpsError so that the client gets the error details.
throw new functions.https.HttpsError('failed-precondition', 'The function must be called ' +
'while authenticated.');
}
// ... rest of your method
});
// ./src/models/addMessage.js
const firebase = require("firebase");
require("firebase/functions");
firebase.initializeApp({
apiKey: '### FIREBASE API KEY ###',
authDomain: '### FIREBASE AUTH DOMAIN ###',
projectId: '### CLOUD FUNCTIONS PROJECT ID ###'
databaseURL: 'https://### YOUR DATABASE NAME ###.firebaseio.com',
});
var functions = firebase.functions();
// This is the new code:
var yourFunc = firebase.functions().httpsCallable('yourFunc');
yourFunc({foo: bar}).then(function(result) {
// ...
});
From firebase documentation

How to check/authenticate with email and password using the Auth0 api

I am trying to drop in Auth0 and replace login and registration methods in an existing REST api on the server. The current system uses email and password.
To that end I'm implementing the login and register endpoints using Auth0 as the backing store. I created a user with email and password successfully using the management api via my Node.js server.
var request = require("request");
var options = { method: 'POST',
url: 'https://test.auth0.com/api/v2/users',
headers:
{
'content-type': 'application/json',
authorization: 'Bearer SomeToken' },
body:
{ connection: 'Username-Password-Authentication',
email: 'test#yahoo.com',
password: 'test',
user_metadata: { enable_promotions: true },
email_verified: false,
app_metadata: {} },
json: true };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
I'm stuck trying to figure out how to now authenticate that same user. I couldn't find an authenticate method on the management api, so I tried it using the authentication api but it says that username is required - in my case I created a user via email and not username.
a) do I have to use the autentication API rather than the management api to authenticate with password and email?
b) do I use the email as the username?
Yes, all authentication related endpoints are implemented in the scope of the Authentication API. You should use this instead of the Management API to authenticate a user using email and password.
Also, by default, database connection in Auth0 use the email as user identifier, so if your connection is using default settings you should use the email as the username. It's possible to configure them to also require a traditional username in addition to the email and in those situations you would no longer use the email during authentication.
There are many possible ways to integrate Auth0 authentication, if your usage scenario include a custom user interface where you collect the username/password credentials and then just want to validate them with Auth0, you can use the resource owner endpoint of the Authentication API.

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.