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

Undress AI Tool
Undress images for free

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

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

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

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

If JavaScript applications load slowly and have poor performance, the problem is that the payload is too large. Solutions include: 1. Use code splitting (CodeSplitting), split the large bundle into multiple small files through React.lazy() or build tools, and load it as needed to reduce the first download; 2. Remove unused code (TreeShaking), use the ES6 module mechanism to clear "dead code" to ensure that the introduced libraries support this feature; 3. Compress and merge resource files, enable Gzip/Brotli and Terser to compress JS, reasonably merge files and optimize static resources; 4. Replace heavy-duty dependencies and choose lightweight libraries such as day.js and fetch
