Javascript: Implementing Passwordless Login with Salesforce
Salesforce offers a Headless Passwordless Login Flow that allows registered users to access an application seamlessly. Passwordless login is very user friendly, all it requires is an active email address. In this post, I’ll share some code snippets for implementing the Passwordless login flow with Salesforce.
Requirements
Before we start, ensure the following:
a) You have access to a Salesforce environment.
b) You’ve registered a user and enabled the Passwordless login option.
Step One: Send Username
export async function passwordlessLogin(username, captcha) { const payload = { username, recaptcha: captcha, verificationmethod: "email", }; const config = { headers: { "Content-Type": "application/json", }, method: "POST", body: JSON.stringify(payload), }; const url = `${REPLACE_WITH_YOUR_SALESFORCE_CLOUD_URL}/services/auth/headless/init/passwordless/login`; const response = await fetch(url, config); const result = await response.json(); return result; }
This is the first call to Salesforce. Take note of the following:
a) You’ll need to pass a captcha. For assistance, check out ReCAPTCHA v3.
b) The verificationmethod is set to email, which tells Salesforce to send a one-time password (OTP) via email.
c) Along with captcha and verificationmethod, the only other parameter required is username, which corresponds to the email registered for the user.
If the request is successful, Salesforce will send an email to the username provided and return a response like this:
{ "identifier": "MFF0RWswMDAwMDIxdVRk", "status": "success" }
Step two: Capture OTP
export async function passwordlessAuthorize(identifier, code) { const Authorization = btoa(identifier + ":" + code); const config = { headers: { "Auth-Request-Type": "passwordless-login", "Auth-Verification-Type": "email", Authorization: "Basic " + Authorization, "Content-Type": "application/x-www-form-urlencoded", }, method: "POST", body: new URLSearchParams({ response_type: "code_credentials", client_id: "REPLACE_WITH_YOUR_CLIENT_ID", redirect_uri: "REPLACE_WITH_YOUR_REDIRECT_URI", }), }; const response = await fetch( `${REPLACE_WITH_YOUR_SALESFORCE_CLOUD_URL}/services/oauth2/authorize`, config ); const result = await response.json(); return result; }
This is the second call to Salesforce. Here are a few key points:
a) The identifier is the value returned from step one.
b) The code is the OTP that Salesforce sent via email.
c) Pay attention to how the Auth and Authorization headers are defined.
d) The Content-Type is application/x-www-form-urlencoded. Notice how the body uses URLSearchParams for formatting.
If everything goes smoothly, Salesforce will return a response like this:
{ "code": "aPrxOPPU1bwu2d3SbsSBKLUbZop4sxhra2Tb.p3LApgVIexVmwyIGVaF6vTebI7ottVto18uuQ==", "sfdc_community_url": "https://site.com/application", "sfdc_community_id": "xxxxxxxx" }
Step Three: Exchange Code for Access Token
The final step is to exchange the code from the previous step for an Access Token. The Access Token is crucial because it allows you to make requests on behalf of the user. The presence of the Access Token enables a user's session.
export async function getAccessToken(code) { const config = { headers: { "Content-Type": "application/x-www-form-urlencoded", }, method: "POST", body: new URLSearchParams({ code, grant_type: "authorization_code", client_id: "REPLACE_WITH_YOUR_CLIENT_ID", redirect_uri: "REPLACE_WITH_YOUR_REDIRECT_URI", }), }; const response = await fetch( `${REPLACE_WITH_YOUR_SALESFORCE_CLOUD_URL}/services/oauth2/token`, config ); const result = await response.json(); return result; }
The response should look something like this:
{ "access_token": "00DEj000006DHsR!AQEAQGpj5XvnBl1QQ8PI4XjygHmXAJiG7CA4Ci0mIxZcg7hO_YYZanyXPX9uelAez2905VFnE6VzhmavmnDoBOks.wzhlZHc", "refresh_token": "5Aep861i1Ns2kInCGgjSdz4OOTyJzqw_gZDs5f1PwqH0NfU0AKgLDAw5ptc.qADf.bVZ1aPlUKjyISe2lxx5KQ0", "sfdc_community_url": "https://site.com/application", "sfdc_community_id": "xxxxxxxx", "signature": "jwnfZY2G3phxCl3fJrfJu5X2AyxW7Ozsfg2BZ6bBB74=", "scope": "refresh_token openid user_registration_api api", "id_token": "...", "instance_url": "https://site.com/", "id": "https://test.salesforce.com/id/00000/11111", "token_type": "Bearer", "issued_at": "1733700157803" }
Make sure to securely store the access_token, and from here, you can create a session for your user. For security reasons, it’s best to execute these methods on the server.
The id_token is a JWT token. If you decode it, it will look something like this:
{ "at_hash": "HTa4VEmQhCYi59WLhiL6DQ", "sub": "https://test.salesforce.com/id/00000/11111", "aud": "3MXG9j6uMOMC1DNjcltNj9xPoUi7xNbiSwPqOjmDSLfCW54f_Qf6EG3EKqUAGT6xyGPc7jqAMi4ZRw8WTIf9B", "iss": "https://site.com/", "exp": 1733702662, "iat": 1733702542 }
You can also customize the JWT to include additional data. However, it’s recommended to keep the structure minimal and use the Access Token for fetching additional information as needed.
Conclusion
Passwordless login is convenient for everyone, and most cloud services, like Salesforce, now offer a Passwordless Login Flow. Leverage this feature to simplify the login process and improve the user experience.
The above is the detailed content of Javascript: Implementing Passwordless Login with Salesforce. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.
