Issue with Auth0 and javascript Lock v11 - javascript

I'm trying to test a basic authentication module on my web app using auth0 and Lock v1 login form.
This is a snapshot of the code I'm using:
<script src="https://cdn.auth0.com/js/lock/11.23.1/lock.min.js"></script>
<script type="text/javascript" src="js/auth0variables.js"></script>
<script type="text/javascript" src="js/auth0app.js"></script>
<script>
$( document ).ready(function() {
console.log("start");
var lock = new Auth0Lock(AUTH0_CLIENT_ID, AUTH0_DOMAIN, {
auth: {
redirectUrl: 'undefined',
responseType: 'code',
params: {
scope: 'openid email' // Learn about scopes: https://auth0.com/docs/scopes
}
}
});
lock.show();
});
</script>
The problem is that I'm not able to get the auth0 modal since I'm getting the following error:
Uncaught TypeError: Cannot read property 'protocol' of null
at Object.getOriginFromUrl (auth0.min.esm.js:8)
at G.run (auth0.min.esm.js:8)
at $.checkSession (auth0.min.esm.js:8)
at nt.getSSOData (auth0.min.esm.js:8)
at t.getSSOData (p2_api.js:190)
at t.getSSOData (web_api.js:64)
at t.fetchFn (data.js:4)
at t.fetch (cache.js:17)
at t.get (cache.js:13)
at r (data.js:7)
I don't understand if I'm configuring in a wrong way my application on Auth0 dashboard, if I'm missing some configuration parameter calling the the Auth0Lock method or if the issue is somewhere else.
Can anybody help me with this? Thanks!

I found a workaround looking at the following discussion hosted on ath0 github repo:
https://github.com/auth0/lock/issues/1638
In order to avoid getLocationFromUrl returning null value I set the redirectUrl option in Auth0Lock constructor
<script src="https://cdn.auth0.com/js/lock/11.23.1/lock.min.js"></script>
<script type="text/javascript" src="js/auth0variables.js"></script>
<script type="text/javascript" src="js/auth0app.js"></script>
<script>
$( document ).ready(function() {
console.log("start");
var lock = new Auth0Lock(AUTH0_CLIENT_ID, AUTH0_DOMAIN, {
auth: {
redirectUrl: 'http://localhost',
//redirectUrl: 'file://',
responseType: 'code',
params: {
scope: 'openid email' // Learn about scopes: https://auth0.com/docs/scopes
}
}
});
lock.show();
});
</script>
Both redirectUrl: 'http://localhost' or redirectUrl: 'file://' options are working fine for my development purposes.

Related

Keycloak login returns 404 using JavaScript adapter

I'm using Keycloak's bower package to create a very basic demo HTML/JS app. I have Keycloak running locally and keycloak.init() seems to work (no error triggered). However when I call keycloak.login() a 404 is returned. Might the login URL be wrongly created by the adapter?
The URL returned by keycloak.createLoginUrl() is
https://<keycloak url>/realms/<realm>/protocol/openid-connect/auth?client_id=account&redirect_uri=file%3A%2F%2F%2FUsers%2Fjgallaso%2FProjects%2Fdemos%2Fkeycloak-simple-web-client%2Findex.html&state=b167dc0b-3e5b-4c67-87f7-fd5289fb7b8f&nonce=1e2cb386-51db-496a-8943-efcf4ef5d5e1&response_mode=fragment&response_type=code&scope=openid
And this is my entire code:
<head>
<script src="bower_components/keycloak/dist/keycloak.min.js"></script>
</head>
<body>
<button id="login">Login</button>
</body>
<script>
var keycloak = Keycloak({
url: 'https://keycloak-keycloak.192.168.37.1.nip.io',
realm: 'demo',
clientId: 'account'
});
keycloak.init()
.success(authenticated => {
document.getElementById("login")
.addEventListener("click", () => { keycloak.login(); });
}).error(err => {
console.log("init, error: " + err);
});
</script>
</head>
Response is a plain:
ERROR 404: Not Found
You have 2 posibilities :
invoque login automatically in init method
login manually after call init without params
1)
<head>
<script src="bower_components/keycloak/dist/keycloak.min.js"></script>
</head>
<body>
<button id="login">Login</button>
</body>
<script>
var keycloak = Keycloak({
url: 'https://keycloak-keycloak.192.168.37.1.nip.io',
realm: 'demo',
clientId: 'account'
});
keycloak.init('login-required')
.success(function(authenticated) => {
}).error(err => {
console.log("init, error: " + err);
});
</script>
</head>
2)
keycloak.init().success(function(authenticated) {
if(authenticated == true){
alert('usuario logeado');
}else{
alert('usuario no logeado');
keycloak.login();
}
}).error(function() {
alert('failed to initialize');
});
I had trouble trying directly from the management.
file://c:/example.html
To do a better test you should leave your index.html on a local test server.
What I did was install the web server plugin for chrome and it worked for me.
I hope it'll help you.
regards

Google API Uncaught exception when use gapi.load

When I used this type of initialization:
var auth2;
gapi.load('auth2', function() {
gapi.auth2.init({
client_id: 'MY_CLIENT_ID.apps.googleusercontent.com',
}).then(function(){
auth2 = gapi.auth2.getAuthInstance();
console.log(auth2.isSignedIn.get()); //now this always returns correctly
});
});
I got the following error:
uncaught exception: gapi.auth2.ExternallyVisibleError: Missing required parameter 'client_id' (unknown)
TypeError: auth2 is undefined
But if I initialized using meta tag
<meta name="google-signin-client_id" content="MY_CLIENT_ID.apps.googleusercontent.com">
That works, but auth2.isSignedIn.get() gave me inconsistent values.
How can I solved this issue?
You may have included the below line of code to display Google's Sign In button.
<div class="g-signin2" data-onsuccess="onSignIn"></div>
If so, remove that from your html page and check if you are still getting error in console.
Building on Krishna's answer, specifically, you want to remove the data-onsuccess="onSignIn"></div> section, then create a custom button:
<div id="my-signin2"></div>
<script>
function renderButton() {
gapi.signin2.render('my-signin2', {
'scope': 'profile email',
'width': 240,
'height': 50,
'longtitle': true,
'theme': 'dark',
});
}
</script>
As my sign-in is handled server-side I've added another jquery function to redirect to my backend flow, but you can adjust accordingly:
<script>
$('#my-signin2').click(function() {
// if your sign in is handled by your backend:
location.href = "/signin";
// signInCallback defined in step 6.
// auth2.grantOfflineAccess().then(signInCallback);
});
</script>

How to get user email id using hello.js?

I am trying to login website with hello.js. I get the user name but I can't get user email id. How can I get this?
I am following this link.
This is my code :
<script src="hello.js" ></script>
<script>
hello.init({
google: "742850147964-r4pfusmgmp2mtfbngh387e30k3692p79.apps.googleusercontent.com"
}, {redirect_uri: 'index.php'});
hello.on('auth.login', function(auth) {
// Call user information, for the given network
hello(auth.network).api('/me').then(function(r) {
console.log("r.email = "+r.email);
console.log("r.name== = "+r.name);
});
});
</script>
I got my problem solved by simple changing in the hello.js.
for google :-
scope: {
basic: 'https://www.googleapis.com/auth/plus.me profile',
}
to
scope: {
basic: 'https://www.googleapis.com/auth/userinfo.email',
}
for facebook :-
scope: {
basic: 'public_profile',
}
to
scope: {
basic: 'public_profile,email',
}
First, please keep just one js file ref, you don't need both:
<script src="hello.js" ></script>
<script src="hello.min.js" ></script>
I tried adding the button for google and it worked, I think something is wrong with the configuration for Yahoo, check if the client id is correct.

Getting email from LinkedIn Javascript API reliably

Keen to get at the user's email reliably, there doesn't appear to be anything in the API documentation about this from LinkedIn. I have the cod working which grabs the basic profile and I've tried what I can find on the web to get additional fields. But this doesn't return anything. Here is the code:
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: 11111111111
onLoad: onLinkedInLoad
authorize: true
scope: r_basicprofile
</script>
<script type="text/javascript">
// Setup an event listener to make an API call once auth is complete
function onLinkedInLoad() {
IN.Event.on(IN, "auth", getProfileData);
}
// Handle the successful return from the API call
function onSuccess(data) {
console.log(data);
}
// Handle an error response from the API call
function onError(error) {
console.log(error);
}
// Use the API call wrapper to request the member's basic profile data
function getProfileData() {
var fields = ['firstName', 'lastName', 'emailAddress'];
IN.API.Profile("me").fields(fields).result(onSuccess).error(onError);
}
</script>
and HTML:
<script type="in/Login"></script>
I do not know if it is possible with the current version to return the email or the email is user setting so varies with each user.
You are missing r_emailaddress to the scope:
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: 11111111111
onLoad: onLinkedInLoad
authorize: true
scope: r_basicprofile r_emailaddress
</script>
Also be sure you are using the right syntax for the fields:
var fields = ['first-name', 'last-name', 'email-address'];
And finally check in your app setting on LinkedIn developer that you grant r_emailaddress access.

how to add a basic keen.io event with javascript

I am trying to set up a basic example that sends a custom keen.io event via js. At the moment I do not need any presentation, visualisation, etc.
Here is the example that I created from another one I found online. I attempted several variations, and all of them work in Google Chrome, but none of them works in Firefox (38.0 for Ubuntu canonical - 1.0).
if I add to the head the inline script (!function(a,b){a("Keen"...) as it is proposed in the manual, I do not get any errors in FF, but it seems that addEvent never gets called and it produces no response, "err" nor "res".
if I include the library from the CDN (d26b395fwzu5fz.cloudfront.net/3.2.4/keen.min.js), I get an error when the page is loaded:
ReferenceError: Keen is not defined
var keenClient = new Keen({
If I download the js file and serve it locally, after the button is clicked, I get the following error response:
Error: Request failed
err = new Error(is_err ? res.body.message : 'Unknown error occurred');
All of these attempts work from Chrome, but I need this to work from other browsers too.
I received a response from keen.io team. It turned out that Adblock Plus is interfering with the script. After I disabled it everything works in FF as in Chrome.
After some investigation in turned out that request to http://api.keen.io was blocked by "EasyPrivacy" filter of ABP with these filter rules: keen.io^$third-party,domain=~keen.github.io|~keen.io
So, sending a request to an "in-between" server (a proxy) seems to be the only solution that I can see.
We have a bit specific use case - a need to track a static site and also an available access to a rails api server, but the solution we ended up using may come useful to someone.
error.html
<html>
<head>
<title>Error</title>
<script src="/js/vendor/jquery-1.11.2.min.js"></script>
<script src="/js/notification.js"></script>
<script type="text/javascript">
$(document).on('ready', function () {
try {
$.get(document.URL).complete(function (xhr, textStatus) {
var code = xhr.status;
if (code == 200) {
var codeFromPath = window.location.pathname.split('/').reverse()[0].split('.')[0];
if (['400', '403', '404', '405', '414', '416', '500', '501', '502', '503', '504'].indexOf(codeFromPath) > -1) {
code = codeFromPath;
}
}
Notification.send(code);
});
}
catch (error) {
Notification.send('error.html', error);
}
});
</script>
</head>
<body>
There was an error. Site Administrators were notified.
</body>
</html>
notification.js
var Notification = (function () {
var endpoint = 'http://my-rails-server-com/notice';
function send(type, jsData) {
try {
if (jsData == undefined) {
jsData = {};
}
$.post(endpoint, clientData(type, jsData));
}
catch (error) {
}
}
// private
function clientData(type, jsData) {
return {
data: {
type: type,
jsErrorData: jsData,
innerHeight: window.innerHeight,
innerWidth: window.innerWidth,
pageXOffset: window.pageXOffset,
pageYOffset: window.pageYOffset,
status: status,
navigator: {
appCodeName: navigator.appCodeName,
appName: navigator.appName,
appVersion: navigator.appVersion,
cookieEnabled: navigator.cookieEnabled,
language: navigator.language,
onLine: navigator.onLine,
platform: navigator.platform,
product: navigator.product,
userAgent: navigator.userAgent
},
history: {
length: history.length
},
document: {
documentMode: document.documentMode,
documentURI: document.documentURI,
domain: document.domain,
referrer: document.referrer,
title: document.title,
URL: document.URL
},
screen: {
width: screen.width,
height: screen.height,
availWidth: screen.availWidth,
availHeight: screen.availHeight,
colorDepth: screen.colorDepth,
pixelDepth: screen.pixelDepth
},
location: {
hash: window.location.hash,
host: window.location.host,
hostname: window.location.hostname,
href: window.location.href,
origin: window.location.origin,
pathname: window.location.pathname,
port: window.location.port,
protocol: window.location.protocol,
search: window.location.search
}
}
}
}
return {
send: send
}
}());
example of sending notification manually from js code:
try {
// some code that may produce an error
}
catch (error) {
Notification.send('name of keen collection', error);
}
rails
# gemfile
gem 'keen'
#routes
resource :notice, only: :create
#controller
class NoticesController < ApplicationController
def create
# response to Keen.publish does not include an ID of the newly added notification, so we add an identifier
# that we can use later to easily track down the exact notification on keen
data = params['data'].merge('id' => Time.now.to_i)
Keen.publish(data['type'], data) unless dev?(data)
# we send part of the payload to a company chat, channel depends on wheter the origin of exception is in dev or production
ChatNotifier.notify(data, dev?(data)) unless data['type'] == '404'
render json: nil, status: :ok
end
private
def dev?(data)
%w(site local).include?(data['location']['origin'].split('.').last)
end
end

Categories

Resources