Skip to main content

User Registration Getting Started

Developing and managing an online identity solution continues to be challenging in terms of addressing security concerns, performance issues, or the high cost of the development and maintenance of the solution. LoginRadius provides a complete User Registration platform that can be implemented on any application.

This document covers how you can utilize our various features and functionalities via using JavaScript. We have explained the implantation of LoginRadius via JS in detail below, you can customize the provided code as per your need while implementing it on your web property.

LoginRadius User Registration

This solution covers:

It allows integration of the Login/Registration system across your website. This tool gives you flexibility in terms of design, structure, fields, and content validations during implementation on your site.

Installation

Importing References

To import LoginRadius JavaScript interfaces on your page, add the following script reference to your page. By adding the below URL, you will always get the latest most up-to-date version of the LoginRadiusV2.js via our CDN.

https://auth.lrcontent.com/v2/js/LoginRadiusV2.js

If you are looking to have control over which version of the library you're using, you can either download and serve your own copy of LoginRadiusV2.js. You can also specify any desired version (like 3.10.0) directly in the URL using the following format:

https://auth.lrcontent.com/v2/LoginRadius-vX.Y.Z.js

Here, each letter represents the type of change. For example, X, Y, and Z are Major, Minor, and Patch versions respectively as per Semantic Versioning. Let’s say if you want to access LoginRadiusV2.js version 3.10.0 then the following URL will work for you:

https://auth.lrcontent.com/v2/LoginRadius-v3.10.0.js

Note:

  • You can refer to our updates blog for the current Version of LoginRadiusV2.js.
  • LoginRadius may retroactively push urgent security updates to previous versions of LoginRadiusV2.js.

Initialization of LoginRadius Object

After adding the reference to the page, make sure to include the fallback JS for instantation of LoginRadiusV2 singleton. It can be instantiated by defining the commonOptions parameter and calling creating a new instance of the LoginRadiusV2 Object.

<script type='text/javascript'>
if (typeof LoginRadiusV2 === 'undefined') {
var e = document.createElement('script');
e.src = 'https://auth.lrcontent2.com/v2/js/LoginRadiusV2.js';
e.type = 'text/javascript';
document.getElementsByTagName("head")[0].appendChild(e);
}
var lrloadInterval = setInterval(function () {
if (typeof LoginRadiusV2 != 'undefined') {
clearInterval(lrloadInterval);
LoginRadiusV2JsLoaded();
}
}, 100);
function LoginRadiusV2JsLoaded() {
var commonOptions = {};
commonOptions.apiKey = "your_loginradius_api_key";
commonOptions.hashTemplate= true;
commonOptions.sott ="Get_Sott";
commonOptions.verificationUrl = window.location;//Change as per requirement
var LRObject= new LoginRadiusV2(commonOptions);
}
</script>

A detailed listing of all available parameters for the commonOptions from above, is shown below:

NameRequiredActionDescription
apiKey (String)YesAllThis parameter is used to provide the API Key to your JS Interface.
sott (String)YesRegistrationSecure One Time Token used during Registration. For details see our SOTT documentation.
verificationUrl (URI String)YesRegistration, Login, Resend Email Verification, Add Email, Verify Email, Social LoginUsed to pass the desired URL in the verification email where the user will get verified.
appName (String)NoAllSet to your LoginRadius site name, this is required for User Registration to work with Single Sign On API.
hashTemplate (Boolean)NoSocial Login, Link Account, Custom InterfaceRecommended: Used when the interface template contains hash (#).
smsTemplateInstantOTPLogin (String)NoLoginUsed to select the name of OTP login SMS template.
customObjectName (String)NoCustom ObjectUsed to set the name of custom object.
callbackUrl (Encoded URI String)NoSocial Login, Custom InterfaceRecommended: LoginRadius redirects the user to this URL with token, default value is located on your LoginRadius Admin Console.
debugMode (Boolean)NoAllRecommended: Used to show console log during debugging.
deleteUrl (URI String)NoDelete UserRecommended: Url, where you handle Delete user functionality.
maskSensitiveInput (Boolean)NoLogin,RegistrationRecommended: To show otp and security answers in encrypted form while entering.
formValidationMessage (Boolean)NoAllRecommended: Set value true if you want to show form validation message just below the form elements.
periodicPasswordReset (Boolean)NoLoginRecommended: If set to true user can reset password if its expired.
showTwoFactorOnProfile (Boolean)NoProfile EditorRecommended: Shows Multi-Factor Authentication button on profile page.
v2Recaptcha (Boolean)NoRegistrationIf True, this enables reCAPTCHA see our advanced customization documentation for details.
v2RecaptchaSiteKey (String)NoRegistrationYour reCAPTCHA Public Key, see our advanced customization documentation for details.
v2RecaptchaLanguage (String)NoRegistrationUsed to change the Google reCAPTCHA language. The Google reCAPTCHA language code e.g. fr (French), de (German), ru (Russian).
invisibleRecaptcha (Boolean)NoRegistrationIf true, enables invisible reCAPTCHA if set to true, see our advanced customization documentation for details.
accessTokenResponse (Boolean)NoLogin, Social LoginIf set to false then V2 JS will not handle token, Default value is true.
appPath (String)NoSSO Login, LogoutUsed to define the path to set cookies.
callbackInsideSameWindow (Boolean)NoSocial Login, Custom Interface, Link AccountRedirect user inside the child window(pop-up window) on successful login when set to true, Default is false.
callbackType (String)NoSocial Login, Custom InterfaceFor determining the method used to return the token to the user. Available options are "Post", "QueryString" and "Hash". It is set to "Post" by default.
enableHeaderSott (Boolean)NoRegistrationSet the value false if you want to pass the secure one time token(SOTT) in query string. Default value is true.
existPhoneNumber (Boolean)NoRegistrationThis option check in LoginRadius Database that phone number exist or not.
formRenderDelay (Int)NoRegistrationSet the delay in milliseconds before rendering the User Registration interface.
passwordLength (Object)NoRegistration, Reset Password, Forgot Password,Set password length, object must be in form{min : 10, max :32}.
passwordlessLogin (Boolean)NopasswordlessLoginValidateTo initiate one click login.
passwordlessLoginOTP (Boolean)NoLoginTo initiate one click OTP login when phone number login enabled at your site.
integrationName (String)NoLogin, Social Login, SSO LoginPass the JWT appname which you created in LoginRadius Admin Console.
projectionFields (JSON Object)NoAllTo fetch only provided fields from api for given action, object should be in this format: {"login":["Profile","access_token"]}, where key is action and value is array of fields.
providerCountry (String)NoSocial Login, Custom Interface, Link AccountFor filtering social providers based on country.
providersList (Array)NoSocial Login, Custom Interface, Link AccountTo show only provided list of social providers.
resetPasswordConfirmationEmailTemplate (String)NoReset PasswordUsed to set the name of reset password confirmation email template.
resetPasswordEmailTemplate (String)NoReset PasswordUsed to set the name of reset password template.
deleteUserEmailTemplate (String)NoDelete UserTemplate use to delete user action.
addEmailTemplate (String)NoAdd EmailUsed to set the name of add email template.
onetouchLoginEmailTemplate (String)NoonetouchLoginUsed to set the name of no registration email template.
resetPasswordUrl (URI String)NoReset PasswordSet dynamic URL for reset password.
smsTemplate2FA (String)NoLoginUsed to set the name of SMS template for Multi-Factor Authentication.
smsTemplate2FAWelcome (String)NoLoginName of welcome SMS template for Multi-Factor Authentication.
smsTemplatePhoneVerification (String)NoRegistrationUsed to set the name of phone number verification template.
smsTemplateWelcome (String)NoRegistrationUsed to set the name of welcome SMS template.
smsTemplateOneTouchLoginWelcome (String)NoOne Touch LoginUsed to set the template of the welcome email for One Touch Login via SMS.
smsTemplateOneTouchLogin (String)NoOne Touch LoginUsed to set the name of one touch login SMS template.
smsTemplateForgot (String)NoForgot PasswordName of forgot pasword SMS template.
smsTemplateUpdatePhone (String)NoUpdate PhoneName of update phone SMS template.
termsAndConditionHtml (String)NoRegistrationThis HTML is shown just above the submit button and displays terms and conditions text to user.
tokenExpire (Boolean)NoLogoutSet to True to expire token.
tokenType (String)NoLogin, Social Login, SSO LoginPass "jwt" to get a JWT Token see our JWT Login Flow documentation for details
unLinkAccountCallbackUrl (Encoded URI String)NoUnlink AccountWhen you unlink the account from account linking interface. At that time, you can add unlink callback URL.
verificationEmailTemplate (String)NoRegistrationUsed to set the name email verification template name. This is used in registration and resend email verification event.
welcomeEmailTemplate (String)NoRegistrationUsed to set the name of welcome email template. This will be sent after successful account verification.
promptPasswordOnFirstLoginForSocial (Boolean)NoRegistrationUsed to present the user with a password prompt to setup a traditional profile login during their initial Social Login.
autoFilledFieldForSocial (Boolean)NoLoginEnabling this property prompts the user with pre-filled details from the social login along with any missing required fields.
otpEmailVerification (Boolean)NoRegistration, Reset PasswordIf set to "True" this changes both the Registration and Reset Password Interfaces flow so that once a user provides their email they will be prompted to enter an OTP (One Time Password) that is sent to that email, once the OTP is provided the interfaces will go back to their standard flow, this OTP can further can be passed to the Verification or Reset Password APIs. Please contact LoginRadius Support Team to enable this feature.
loginOnEmailVerification (Boolean)NoVerify EmailLog user in after the verification link is clicked in the verification email.
promptPasswordOnSocialLogin (Boolean)NoSocial LoginAfter authentication for social login, it will prompt a password filling interface. By filling it, user is also going to generate a traditional account besides his/her social account.
usernameLogin (Boolean)NoAllEnable users to log in with either username or email.
phoneLogin (Boolean)NoAllTo enable phone number login. Note: This option also has to be enabled by LoginRadius support from backend.
twoFactorAuthentication (Boolean)NoLogin, Registration, Profile EditorAn Extra Layer of Security Enable Multi-Factor Authentication as mandatory for your customers. Note: This option also has to be enabled by LoginRadius support from backend.
optionalTwoFactorAuthentication (Boolean)NoLogin, Registration, Profile EditorAn Extra Layer of Security Enable Multi-Factor Authentication as mandatory for your customers. Note: This option also has to be enabled by LoginRadius support from backend.
qrCodeAuthentication (Boolean)NoProfile EditorEnable Authenticator Code.
askEmailForUnverifiedProfileAlways (Boolean)NoAllEvery time an unverified user with social account which doesn't provide email (social login user(twitter,vk) ) tries to login, it would ask for new email address.
disabledEmailVerification (Boolean)NoAllEnabling this property would allow the user to login without verifying email Id and no email would be sent to the user. Note: This options also has to be enabled by LoginRadius support from backend.
optionalEmailVerification (Boolean)NoAllEnabling this property would allow the user to login without verifying email Id and the user would also get a verification email. Note: This options also has to be enabled by LoginRadius support from backend.
stayLogin (Boolean)NoLoginEnabling this property would allow the users to check 'keep me sign in' options Note: This options also has to be enabled by LoginRadius support from backend.
askRequiredFieldForTraditionalLogin (Boolean)NoLoginEnabling this property would prompt an interface of required fields for a traditional legacy or old user account if the registration schema has changed.
displayPasswordStrength (Boolean)NoRegistration, Reset Password, Forgot PasswordTo enable password strength.
securityQuestionsCount (Number)NoAllNumber of security questions to update.
duplicateEmailWithUniqueUsername (Boolean)NoRegistrationEnabling this property would allow the user to add duplicate email and unique username but email is required.
isMobile (Boolean)NoAllTo enable for mobile devices.
noCallbackForSocialLogin (Boolean)NoSocial LoginAllowing or configuring no callback feature won’t return any token from the social authentication and the GUID used with no callback social login request can be used to fetch the profile from the smartLogin Ping API.
disableAccountLinking (Boolean)NoLink AccountTo disable the Number of security questions to update.account linking feature.
customDomain (String)NoAllTo add a custom site domain that will replace the .hub.loginradius.com with your own domain. Note: This options also has to be enabled by LoginRadius support from backend.
securityQuestionEnabled (Boolean)NoAllTo enable security question feature.
askRequiredFieldsOnPasswordLessLogin (Boolean)NoonetouchLoginPrompt users to fill out mandatory/required fields during a Passwordless Login.
customizeSocialPopup (String)NoSocial LoginCustomize the Social Popup window.
askOptionalFieldsOnRegistration (Boolean)NoRegistrationPrompt users to fill out optional fields durring registration.
tencentCaptcha(Boolean)NoRegistration, LoginIf True, this enables Tencent Captcha.
tencentCaptchaAsFallback(Boolean)NoRegistration, LoginIf True, firstly it checks V2 Google captcha JS and if its not found then it load the Tencent Captcha.
tencentCaptchaAppid(String)NoRegistration, LoginTencent Captcha App ID.
progressiveProfilingTraditional(Boolean)NoProgressive ProfilingIf True, this will show traditional progressive profiling steps after social login.
askOptionalFieldsOnProgressiveSteps (Boolean)NoProgressive ProfilingIf false, optional fields would not be prompted in progressive profiling steps, by default value is true.
verifyEmailByOTP(Boolean)NoVerify EmailIf True, this will send verification link with OTP on email to verify email.
passwordlessLoginEmailTemplate(String)NopasswordlessLoginValidatePasswordless login email template.
passwordlessLoginSMSTemplate(String)NopasswordlessLoginValidatePasswordless login OTP template.
autoFilledFieldForTraditional(Boolean)NoLoginIf True, it allows to pre-fill the Registration form fields.
preventVerificationEmail(Boolean)NoRegistrationIf True, it will prevent the verification email from being sent. note: this only applies if you have the Optional Email Verification workflow enabled.
disableButtonOnsubmit(Boolean)NoAllIf True, it will disable submit button to prevent executing same request on multiple clicks. By default, it will remain disabled even after successful API call. Set enableSubmitOnSuccess to True to enable it after the successful API call.Refer our Handling Idempotent Request section for more detail.
enableSubmitOnSuccess(Boolean)NoAllIf True, the "Submit Button" will be enabled after successful API call.Refer our Handling Idempotent Request section for more detail.
vNextUX (Boolean)NoRegistrationIf True, In case where SOTT is invalid or expired then the below relevant error message will be displayed:“An error occurred, please refresh the page to proceed with registration".
disableResendOTPButton (Boolean)NoSmart Login, onetouchLogin, Login, createTwoFactorAuthentication, updatePhone, Forgot PasswordIf True, the Resend OTP button will be disabled for the specified time provided by common option "disableResendOTPButtonDelay". It will help to limit the frequent OTP request triggers.
disableResendOTPButtonDelay (String)NoSmart Login, onetouchLogin, Login, createTwoFactorAuthentication, updatePhone, Forgot PasswordCustomize the disable time (in seconds) for the Resend OTP button, after that certain time the button will get enable. For example, disableResendOTPButtonDelay: 5, here the Resend OTP button will be disabled for 5 seconds and after 5 seconds it will get enabled automatically.
apiCustomDomain (String)NoAllTo add a custom site domain that will replace the api.loginradius.com with your own domain. Note: This options also has to be enabled by LoginRadius support from backend.
cloudApiCustomDomain (String)NoAllTo add a custom site domain that will replace the cloud-api.loginradius.com with your own domain. Note: This options also has to be enabled by LoginRadius support from backend.

Init Method

This method takes two parameters. The signature of this method is:

LRObject.init(action, options);

Here is a table outlining the type and description of each parameter.

ParameterTypeDescription
optionsObjectSee below for a sample options object initialization
actionStringWhich action to perform. Allowed actions are login, registration, resetpassword, forgotpassword, emailverification sociallogin and so on.

A detailed table for the options parameter from above:

ParameterRequiredDescription
container (String)YesId/class of div or any HTML element where the form of this action will be rendered. (Not for SSO)
templateName (String)YesId of Script which contain Social Login/Account Linking Template
classPrefix (String)NoThis is an optional parameter, this is required when using two forms on the same page, example values are "registration-form1", "registration-form2" etc.
onSuccess (Function)YesCallback function to be called on successful action. Signature of this callback function should be function(response,data) because on success response will be returned and data is original form data as JSON type.
onError (Function)NoCallback function to be called on error (validation error, username exists, CAPTCHA error etc.) of action. Signature of this callback function should be function(errors) because on error, errors will be returned and this will be an array of errors.

A detailed table for the action parameter from above:

ParameterTypeDescription
loginStringPerform Login Action
registrationStringPerform Registration Action
resetPasswordStringPerform Reset Password Action
forgotPasswordStringPerform Forgot Password Action
verifyEmailStringPerform Email Verification Action
changePasswordStringPerform Change Password Action.When user is logged in.
socialLoginStringPerform Social Login with User Registration.
linkAccountStringPerform account Linking action. When user is logged in.
unLinkAccountStringPerform account unLinking action. When user is logged in.
profileEditorStringPerform Profile update action
deleteUserStringSend delete user email.
deleteUserConfirmStringHandle Delete User functionality
updatePhoneStringPerform Update Phone Action
changeUsernameStringPerform Change username Action. When user is logged in.
resendVerificationEmailStringPerform resend Email Verification Action
addEmailStringPerform add Email Action. When user is logged in.
removeEmailStringPerform remove email Action. When user is logged in.
createTwoFactorAuthenticationStringPerform Multi-Factor Authentication action.
onetouchLoginStringPerform No Registration Password Less Login.
updateSecurityQuestionStringUpdates answers to the given security questions.When user is logged in.
resetPasswordBySecurityQuestionStringResets password using security questions.
smartLoginStringEmail Prompt Smart Login.
passwordlessLoginStringPassswordless Login interface.
backupCodeButtonStringShow Backup Code button.
resetBackupCodeButtonStringShow Reset Backup Code button.

Registration

To implement registration form interface, use LRObject.init method with the registration action. Following code can be used for reference:

var registration_options = {};
registration_options.onSuccess = function (response) {
//On Success
console.log(response);
};
registration_options.onError = function (errors) {
//On Errors
console.log(errors);
};
registration_options.container = "registration-container";
LRObject.util.ready(function () {
LRObject.init("registration", registration_options);
});
<div id="registration-container"></div>

Note: Success callback function will return a JSON object {IsPosted: true} as response.

Registration Form Schema

To provide custom schema for registration form, following code can be used for reference. It will override the default schema.

LRObject.registrationFormSchema = [
{
type: "string",
name: "emailid",
rules: "valid_email|required",
options: "",
DataSource: null,
ParentDataSource: null,
Parent: "",
Checked: true,
display: "Email Id",
permission: "w",
},
{
type: "password",
name: "password",
rules: "min_length[6]|max_length[32]|required",
options: "",
DataSource: null,
ParentDataSource: null,
Parent: "",
Checked: true,
display: "Password",
permission: "w",
},
{
type: "string",
name: "firstname",
rules: "",
options: "",
Parent: "",
Checked: true,
display: "First Name",
permission: "w",
},
];

Login

To implement login interface, use LRObject.init method with the login action. Following code can be used for reference:

var login_options = {};
login_options.onSuccess = function (response) {
//On Success
console.log(response);
};
login_options.onError = function (errors) {
//On Errors
console.log(errors);
};
login_options.container = "login-container";

LRObject.util.ready(function () {
LRObject.init("login", login_options);
});
<div id="login-container"></div>

Note: Success callback function will return a response as this:

{Profile: Object, access_token: "xxxxxxxxxxxxxxxxxxxxxxxxxx", expires_in: "2017-01-28T08:41:59.10265Z"}

Object which contains user profile, access token and expiry time. After maximum failed login attempts, login will get locked. You can set the value of MaximumFailedLoginAttempts and LoginLockedType from the Admin Console.

Social Login

To implement social login interface, use LRObject.init with sociallogin action. Please have a look at the following sections for more details.

Social Login Interface

Here first of all, a custom interface needs to be defined as per the code shown below:

var custom_interface_option = {};
custom_interface_option.templateName = 'loginradiuscustom_tmpl';
LRObject.util.ready(function() {
LRObject.customInterface(".interfacecontainerdiv", custom_interface_option);
});
<div id="interfacecontainerdiv" class="interfacecontainerdiv"></div>

Then, a template should be applied for the interface. It can be done with the help of following code:

<script type="text/html" id="loginradiuscustom_tmpl">
<a class="lr-provider-label" href="javascript:void(0)" onclick="return <#=ObjectName #>.util.openWindow('<#=Endpoint #>');" title="<#=Name #>" alt="Sign in with <#=Name #>">
<#=Name #>
</a>
</script>

Handle Social Login Response

When a user logs in with the selected social provider, a social profile of the user is returned as response. If the returned profile contains missing fields that are marked as "required" in your LoginRadius Admin Console (For example, logging in with Twitter doesn't return email which is required by default), it will prompt a form to let the user input the needed information. If the email is missing from the profile, then the user has to verify his email address as well. Refer to the following code for more details.

var sl_options = {};
sl_options.onSuccess = function (response) {
//On Success
//Here you get the access token
console.log(response);
};
sl_options.onError = function (errors) {
//On Errors
console.log(errors);
};
sl_options.container = "sociallogin-container";

LRObject.util.ready(function () {
LRObject.init("socialLogin", sl_options);
});
<div id="sociallogin-container"></div>

Note: If you want to change the button name of the rendered required field form then use following code:

LRObject.\$hooks.call('setButtonsName',{
socialregistration: "Submit Required Field"
});

Success callback function will return a response as this

{Profile: Object, access_token: "xxxxxxxxxxxxxxxxxxxxxxxxxx"}

Object which contains user profile, access token and expiry time.

Social Interface Customization

You have complete control over the look, feel and behavior of the custom template. There are few parameters available for some possible customizations. Please find them below:

  1. Available Parameters
  2. Setting Custom Icons
  3. Setting Custom CSS Classes
  4. Browser Specific Templates
  5. Programmatic Link Creation
Custom Interface parameters

Additional parameters can be appended to the url in the Custom Interface template as a query parameter

JavaScript

<#=Endpoint #>&is_access_token=true
ParameterTypeDescription
lrinterfacebackgroundHexadecimal color codeThis sets the background color of the LoginRadius interface, Default is transparent
lrsocialloginheadingStringSets a header for your social login interface, Default is blank
same_windowBoolRedirect user inside the child window(pop-up window) on successful login when set to true, Default is false
scopeStringAccepts a valid LoginRadius scope or custom scope set, please refer to scoping documentation for further information, Default value determined by LoginRadius end user settings
enableapicachingBoolIf set to true the LoginRadius interface will cache loaded API responses in local storage, this will improve the interface rendering time. Default value is false
isConnectingTextOnInterfaceString (True or False)For enabling and disabling connecting text on interface when clicking on any provider and default value is ‘false’
InsidePopupfavIconURI StringFor changing favicon of login popup window, default value is LoginRadius’s icon. Make sure loading image URL should be absolute and has HTTPS domain.
isConnectingInsidePopupBoolFor disabling Loading image inside popup and default value is 'true'
ConnectingTextInsidePopupBoolFor changing text inside popup and default value is Connecting...
ConnectingImageURLInsidePopupURI StringFor changing loading image inside popup and default value is LoginRadius's default image. Make sure loading image URL should be absolute and has HTTPS domain.
ac_linkingBoolFor determining whether this is an account linking interface or a standard Login interface. Single Sign On behaviour differs with the account linking interface, Set to false by default
Setting Custom Icons

You can create custom icons for all the providers by customizing their names as per your need. For example, If you want to change Facebook's icon name to Facebook.png. You can achieve the same by modifying the template to generate the links with an img tag included. This img tag should point to the location where you are storing the custom icons.

HTML

<script type="text/html" id="loginradiuscustom_tmpl">
<a
href="javascript:void()"
onclick="return <#=ObjectName #>.util.openWindow('<#=Endpoint #>');"
>
<img
src="/your-image-directory-path/<#=Name #>.png"
title="sign in with <#=Name #>"
/>
</a>
</script>

We have included <#=Name #> to generate the provider name based on specified interface and in the above it will generate the image sources like "Facebook.png". You can also add a prefix or suffix for long names like Facebook-login.png where "Facebook" was generated with the <#=Name #> but you will need to change the names of the images appropriately.

Adding Custom CSS Classes

The Custom Interface templating engine is flexible and supports modifications to the generate HTML Structure. You can add classes directly to the generate icons links by including a class parameter in it.

HTML

<script type="text/html" id="loginradiuscustom_tmpl">
<a
href="javascript:void()"
onclick="return <#=ObjectName #>.util.openWindow('<#=Endpoint #>'); "
class="login-icons <#=Name #>"
></a>
</script>

In the above example, login-icons class contains background and <#=Name #> is the class name and contains the icon position in the sprite image. <#=Name#> defines to the Social Provider Name ie. Facebook, Twitter, etc

Or you can include additional containers within the template and apply classes/styling to them.

HTML

<script type="text/html" id="loginradiuscustom_tmpl">
<div class="<#=Name #>">
<a
href="javascript:void()"
onclick="return <#=ObjectName #>.util.openWindow('<#=Endpoint #>');"
></a>
</div>
</script>

The "div" class in the above script will have a dynamic class name according to the provider ie. Facebook, Twitter, etc

Handling Browser Specific Redirects

Many mobile browsers handle the redirection of pop-up windows differently and do not allow for normal redirection of the LoginRadius authentication systems. You can handle the redirection in mobile browsers by including an additional custom interface specific to Mobile browsers as shown below:

a. Add a check to the location you set the Custom Interface Template.

JavaScript

var custom_interface_option = {};
if (navigator.userAgent.match("CriOS") || navigator.userAgent.match("iPhone")) {
// Is Chrome iOS or iPhone
custom_interface_option.templateName = "loginradiuscustom_tmpl_MOBILE";
} else {
custom_interface_option.templateName = "loginradiuscustom_tmpl";
}

Note: The above check determines whether the current browser is iOS Chrome or an iPhone and uses the custom template rather than the regular web template. You can use these links for determining what mobile browsers you would like to support:

Common User Agent Strings

Mobile Specific Strings

b. Add the Mobile Specific custom interface, This interface should include the "callbacktype" parameter set to "hash" parameter in order to redirect in mobile devices.

HTML

<script type="text/html" id="loginradiuscustom_tmpl_MOBILE">
<span
class="lr-provider-label lr-sl-shaded-brick-button lr-flat-<#=Name.toLowerCase() #>"
onclick="window.location.href='<#=Endpoint#>&is_access_token=true&callback=<#=window.location.href.split('#')[0] #>&callbacktype=hash';"
title="Sign up with <#=Name#> Mobile"
alt="Sign in with <#=Name #> Mobile"
>
<span class="lr-sl-icon lr-sl-icon-<#=Name.toLowerCase() #>"></span>
Sign up with <#=Name#> Mobile
</span>
</script>

You can bypass the template engine entirely and create your own links to be included on buttons or triggered events. In order to trigger the authentication you should format your links as follows:

Text

https://<Site-Name
>.hub.loginradius.com/RequestHandler.aspx?apikey=<LoginRadius API Key
>&provider=<Provider Name></Provider></LoginRadius
></Site-Name>

In the above, replace <Site-Name> with your LoginRadius Site Name, <LoginRadius API Key> with your Loginradius API Key, and <Provider Name> with the lowercase social provider name(facebook, twitter, etc)

You will need to have configured the social providers on your LoginRadius account before using them with the above link.

Sample Code

Refer to the following sample code to implement the Social login using the above programmatic link. The following code gets the token using the post method.

<!DOCTYPE html>
<html>
<head>
<title>Social Login | LR User Registration</title>
<meta charset="utf-8" />
<script src="https://auth.lrcontent.com/v2/js/LoginRadiusV2.js"></script>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
</head>

<body>
<h3>Soicallogin by programmatic links</h3>
<div id="provider-container">
<button class="provider" onclick="openWin()">login with facebook</button>
</div>
<script type="text/javascript">
function openWin() {
let callback = window.location.href,
let appname = "<LR app name>";
let apikey = "LR API key"
let url = `https://${appname}.hub.loginradius.com/RequestHandler.aspx?apikey=${apikey}&provider=facebook&callback=${callback}&same_window=&is_access_token=true&callbacktype=&disablesignup=undefined&scope=lr_basic`;
window.open(url, "childWindow", 'menubar=1,resizable=1,width=450,height=450,scrollbars=1');
window.addEventListener("message", LRReceiveMessage, false);
function LRReceiveMessage(event) {
if (event.origin.indexOf(('hub.loginradius.com')) > -1) {
console.log("LRTokenKey", event.data);
}
}
}
</script>
</body>
</html>

Social Login By Ping

Social Login with Ping API workflow allows you to access the LoginRadius token via the SocialLogin by Ping API. In this workflow, when the social login is initiated, LoginRadius starts calling continually SocialLogin by Ping API. in the parent window. Once the social login is completed at the social provider’s interface, LoginRadius returns the access token in the SocialLogin by Ping API calls.

Note: The NoCallback feature is not enabled by default, for enabling this feature contact the LoginRadius support team. By enabling the Social Login with Ping API feature, you can leverage SocialLogin by Ping API to get the access token with the user profile so that you don’t have to use a callback page for your Social login.

Using LoginRadius SocialLogin library functions

You need to define the commonOptions.noCallbackForSocialLogin = true to get the token via the Ping API. LoginRadius starts calling the SocialLogin by Ping API automatically and returns the token with the user profile data in the sl_options.onSuccess function. Refer to Social Login for more details on how to implement social login workflow using LoginRadius library function.

You can bypass the template engine entirely and create your own links to be included on buttons or triggered events for ping API. You will need to create a unique random string callbackguid and include it in your programmatic link. In order to trigger the authentication, you should format your links as follows:

https://<Your_Site_Name>.hub.loginradius.com/RequestHandler.aspx?apikey=<API_Key>&provider=google&nocallback=true&callbackguid=<uniuqe random guid value>

Here, nocallback=true in query indicates that the login request will be without the callback, and callbackguid=Random_Identifier is a random unique identifier. You will need to call the SocialLogin by Ping API continually with the same callbackguid value to fetch the access token with the user profile data.

Forgot Password

To implement forgot password interface, use LRObject.init with forgotPassword action. Following code can be used for reference:

var forgotpassword_options = {};
forgotpassword_options.container = "forgotpassword-container";
forgotpassword_options.onSuccess = function (response) {
// On Success
console.log(response);
};
forgotpassword_options.onError = function (errors) {
// On Errors
console.log(errors);
};

LRObject.util.ready(function () {
LRObject.init("forgotPassword", forgotpassword_options);
});
<div id="forgotpassword-container"></div>

Note

Success callback will return a json object {IsPosted:true} as a response.

Reset Password

After the forgot password operation, there might be a need for reset password interface. To implement the reset password interface, use LRObject.init with resetPassword action. Following code can be used for reference:

var resetpassword_options = {};
resetpassword_options.container = "resetpassword-container";
resetpassword_options.onSuccess = function (response) {
// On Success
console.log(response);
};
resetpassword_options.onError = function (errors) {
// On Errors
console.log(errors);
};

LRObject.util.ready(function () {
LRObject.init("resetPassword", resetpassword_options);
});
<div id="resetpassword-container"></div>