Keycloak login returns 404 using JavaScript adapter - javascript

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

Related

Uncaught ReferenceError: gapi is not defined at makeApiCall?

function makeApiCall(){
gapi.client.load('calendar', 'v3', function () {
var request = gapi.client.calendar.events.insert
console.log(request);
({
'calendarId': '',
"resource": resource
});
});
}
Unless you have forgotten to post a section of your code you have probably forgotten to register the library, as well as authorizing the user.
<script src="https://apis.google.com/js/client:platform.js"></script>
full example using Google sign-in
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello cal v3 </title>
<!-- Create a client id on Google developer console. Web credentials https://youtu.be/pBVAyU4pZOU -->
<meta name="google-signin-client_id"
content="YourClientId">
<meta name="google-signin-scope" content="https://www.googleapis.com/auth/calendar">
</head>
<body>
<h1>Hello cal v3 </h1>
<!-- The Sign-in button. This will run `getFileAsync()` on success. -->
<p class="g-signin2" data-onsuccess="makeacall"></p>
<!-- The API response will be printed here. -->
<textarea cols="80" rows="20" id="query-output"></textarea>
<script>
// Query the API and print the results to the page.
async function makeacall() {
try {
await gapi.client.load('calendar', 'v3');
const response = gapi.client.calendar.events.insert({
calendarId: 'XXX',
resource: resource
});
displayResults(response)
} catch (e) {
console.error('Error getting files', e)
}
}
function displayResults(response) {
var formattedJson = JSON.stringify(response.result, null, 2);
document.getElementById('query-output').value = formattedJson;
}
</script>
<!-- Load the JavaScript API client and Sign-in library. -->
<script src="https://apis.google.com/js/client:platform.js"></script>
Redirect uri mismatch JavaScript origin error
Make sure that you have configured your web client properly on Google developer console and added the proper javascript origin. Simple solution for redirect_uri_mismatch error with JavaScript
you need to init gapi on page load
gapi.auth2.init({
client_id: 'xxxxxxxxxxx'
});

Issue with Auth0 and javascript Lock v11

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.

getting stuck ,Log in with facebook with firebase

i try to login with facebook in firebase using java script and html. i also create a facebook application and set app secret and app id in firebase dashbord.
and all the other setting in facebook app that firebase said in their doc
but im getting this.
<html>
<head>
<script src='https://cdn.firebase.com/js/client/2.0.4/firebase.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
</head>
<body>
<div id='messagesDiv'></div>
<input type='text' id='nameInput' placeholder='Name'>
<input type='text' id='messageInput' placeholder='Message'>
<script>
var myDataRef = new Firebase('https://fiery-inferno-9432.firebaseio.com/');
myDataRef.authWithOAuthPopup("facebook", function(error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
}
});
myDataRef.authWithOAuthRedirect("facebook", function(error, authData) {
if (error) {
console.log("Ridi Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
}
});
$('#messageInput').keypress(function (e) {
if (e.keyCode == 13) {
var name = $('#nameInput').val();
var text = $('#messageInput').val();
myDataRef.push({name: name, text: text});
$('#messageInput').val('');
}
});
myDataRef.on('child_added', function(snapshot) {
var message = snapshot.val();
displayChatMessage(message.name, message.text);
});
function displayChatMessage(name, text) {
$('<div/>').text(text).prepend($('<em/>').text(name+': ')).appendTo($('#messagesDiv'));
$('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight;
};
</script>
</body>
</html>
im getting
Login Failed! Error: There are no login transports available for the requested method.code: "TRANSPORT_UNAVAILABLE"message: "There are no login transports available for the requested method."stack: (...)get stack: function () { [native code] }set stack: function () { [native code] }proto: dconstructor: function Error() { [native code] }message: ""name: "Error"toString: function toString() { [native code] }proto: Object
i found the problem. i must run the html file by running a file server
simply by this on cmd
python -m SimpleHTTPServer
and then run html by
http://localhost/test.html
From https://www.firebase.com/docs/web/guide/user-auth.html:
Note: Browser popups and redirects are not available on all platforms
or browser environments. Popups are not available in Chrome for iOS,
iOS Preview Panes, or local, file:// URLs.
Also, when authenticating via popup on PhoneGap / Cordova apps, including cordova.js and the InAppBrowser plugin in the scope of the page are both required.
I solved it by running my page via server on localhost instead of running the file directly from file system.

File not uploading using Skydrive file picker javascript api

I'm using Skydrive file picker javascript api to upload files to Skydrive. But as soon as I click on upload button...it opens the login window and closes instantly. Error log shows that WL.login : The pop up is closed without receiving any consent.
I've hosted my web-app on local domain: apidomain and published my files to IIS # Default Web Site/onedriveapi folder.
Following is the code:
[HTML]
<button onclick="uploadFile()">Save file</button>
<label id="info"></label>
[Javascript]
<script src="//js.live.net/v5.0/wl.js" type="text/javascript"></script>
<script type="text/javascript">
WL.init({
client_id: "00000000XXXXXXXX",
redirect_uri: "http://apidomain.com/onedriveapi/default.html",
scope: ["wl.signin", "wl.skydrive", "wl.skydrive_update"],
response_type: "token"
});
function uploadFile() {
WL.login({
scope: "wl.skydrive_update"
}).then(
function (response) {
alert(response);
WL.upload({
//path: "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!170",
path: "response.data.folders[0].id",
element: "file",
overwrite: "rename"
}).then(
function (response) {
document.getElementById("info").innerText =
"File uploaded.";
},
function (responseFailed) {
document.getElementById("info").innerText =
"Error uploading file: " + responseFailed.error.message;
}
);
},
function (responseFailed) {
document.getElementById("info").innerText =
"Error signing in: " + responseFailed.error.message;
}
);
}
</script>
Redirect_URL in app settings is also same as mentioned above. I've also created callback.html as mentioned in few places, and replaced my redirect_url with
redirect_uri: "http://apidomain.com/onedriveapi/callback.html",
in page as well as appsettings of https://account.live.com/developers/applications/apisettings.
I also want to save the token received and location of the file uploaded into my db.Please anybody help to fix this issue as I'm struggling with this from last few days.
Thanks
FYI. This is the screenshot of the html page.
<html>
<head>
<script src="http://js.live.net/v5.0/wl.js" type="text/javascript"></script>
<script type="text/javascript">
WL.init({
client_id: "################",
redirect_uri: "http://yashlocal.com/skydrive/response",
scope: ["wl.signin", "wl.skydrive", "wl.skydrive_update"],
response_type: "token"
});
function uploadFile() {
WL.login({
scope: "wl.signin"
}).then(
function (response) {
alert(response);
WL.upload({
//path: "folder.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!170",
path: "response.data.folders[0].id",
element: "file",
overwrite: "rename"
}).then(
function (response) {
document.getElementById("info").innerText =
"File uploaded.";
},
function (responseFailed) {
document.getElementById("info").innerText =
"Error uploading file: " + responseFailed.error.message;
}
);
},
function (responseFailed) {
document.getElementById("info").innerText =
"Error signing in: " + responseFailed.error.message;
}
);
}
</script>
</head>
<body>
<button onclick="uploadFile()">Save file</button>
<label id="info"></label>
</body>
</html>

Error validating access token in Hello.js

I am using Hello.js for social login in my website . I am using a standard code that has been provided in the documentation HERE.
my code looks something like this
<script>
//user;
hello.on('auth.login', function (auth) {
// call user information, for the given network
hello(auth.network).api('/me').then(function (r) {
// Inject it into the container
//alert(r.name);
window.user = r.email;
window.im_name = r.name;
if (r.email) ajax1();
});
});
hello.init({
facebook: 'xxxxxxxxxxxxxxxxx',
google: 'xxxxxxxxxxxxxxxxxxxxxx5-q6xxxxxxxxxxxxxxxeusercontent.com',
}, {
redirect_uri: 'http://wstation.yzx.com/',
scope: 'email'
});
</script>
HTML
<button class="btn-fb" onclick="hello( 'facebook' ).login()">Facebook</button>
<button class="btn-google" onclick="hello( 'google' ).login()">Google</button>
Every thing is working fine I am able to login through Facebook and then send the credentials to the server to sign in the user. But after the user sign in . The Ajax1() method is called again and again all the time.
I am trying to read through the Documentation but nothing is helping out
UPDATE
I changed the code into something like this
function connect(x){
hello(x).api("/me").then(function(r){
window.user = r.email;
window.im_name = r.name;
if (r.email) ajax1();
}, function(e){
alert("Whoops! " + e.error.message );
});
}
and HTML
<button class="btn-fb" onclick="connect('facebook')">Facebook</button>
<button class="btn-google" onclick="connect('google')">Google</button>
Now I am getting error
Whoops! Error validating access token: This may be because the user logged out or may be due to a system error.
as an alert
Please help me if any one had same problem
Thanks in advance
I got it worked Hopefully it helps some one else having the same problem
<script>
function connect(x){
hello(x).login().then(function(r){
hello(r.network).api('/me').then(function(r){
alert('Login');
window.user = r.email;
window.im_name = r.name;
if (r.email) ajax1();
}, function(e){
alert("Whoops! " + e.error.message );
});
});
}
hello.init({
facebook: '2xxxxxxxxxxx4',
google: '3xxxxxxxxx5-qxxxxxxxxxxxxx6k1nunigepmsd3.apps.googleusercontent.com',
twitter: 'Yxxxxxxxxxxxw'
}, {
redirect_uri: 'http://wstation.inmotico.com/',
scope: 'email'
});
</script>
Thanks & Regards

Categories

Resources