OAuth.io connection failed - javascript

I'm new to web programming and I try to use oauth.io in my web-app. I finished configurations to facebook and Google due to the instruction. Everything works fine when i tested the configuration from their site. However when i tried to implemented to my webapp, OAuth won't connect to the provider.
I loaded the oauth.js in html, created a button in html and use onclick="pop" to invoke the function in javascript. And within the pop() function in javascript I've added:
OAuth.initialize('the-public-key-in-my-acc");
OAuth.popup('facebook', function(err, res) { if (err) { alert(something)});
Then I click the button. a popup window just flashed up and closed immediately. I've also tried to use OAuth.redirect and redirect it to http://oauth-io.github.io/oauth-js or my localhost, but then it says connection failed.
Is there something missing/wrong in the implementation?
Thanks a lot for the help.
PS: I'm working on localhost and i've tried to set redirect-url to localhost:portnr. but still failed. :(
Here is the sample code i've written:
Html:
<div><button onclick="oauthPop()">Try OAuth-io</button></div>
JS:
var oauthPop = function() {
OAuth.initialize('my-pub-key-on-authio');
OAuth.popup('facebook', function(err, res) { // or OAuth.callback
// handle error with err
if (err) {
alert ("error")
} else {
// get my name from fb
res.get('/me').done(function(data) {
alert(data.name)
})
}});
}

OAuth.io needs to have jQuery loaded to make HTTP requests using the result of OAuth.popup(). It use jQuery.ajax() behind the scene to let you a well-known function with all the option you might need.

Related

Can't login to Skype SDK with non-existing domain name

I have problem about SigninManager. When I login in with tan.tastan#abcd.com, abdc.com is a reachable domain. But if I write a wrong domain, for example tan.tastan#abcd***E***.com, I am not getting a response and my application is waiting. Nothing happens and there is no return error code.
Here is my sample code, settings includes username, password, and domain information.
function doLogin(settings) {
return new Promise((resolve, reject) => {
window.skypeWebSDKApi.signInManager.signIn(settings).then((response) => {
resolve(response);
}, (error) => {
reject(error);
}).catch(reject);
});
}
What is the problem?
It's hard to know exactly what is going on without seeing the contents of settings but I suspect you're issue here is a promise not getting resolves. Try simplifying your call:
function doLogin(settings) {
var app = new api.application;
app.signInManager.signIn(settings).then(function () {
console.log('success');
}, function (error) {
console.log(error);
});
}
I've been using the SDK for quite a while now and this is my experience:
When trying to log in using a non existing domain, the Web SDK never returns an error. I've tried different SDK versions and both General Availability and Public Preview API keys.
I ended up starting my own signin timer when trying to sign in.
When no response is received within 20 seconds, I send a signOut request (which cancels the sign in) and show a message to the user (Please make sure you've entered the right username etc..).
It's really lame to have a workaround like this but unfortunately I haven't found a better way yet to deal with this issue, also assuming Microsoft is not going to fix this anymore...

$.get route is not being called on server-side, and no data is being returned, server not console logging

I don't know what happened, but for some reason $.get just doesn't work anymore. I'm trying to make it as basic as possible and it still doesn't work. I have this code:
$("#test").click(function() {
console.log("I'm in the on click event");
$.get("/test", function(data) {
console.log("IM HERE BUT WHY??");
console.log(data);
});
})
When I click the button, here's the server-side route:
router.get("/test", function(req, res) {
console.log("HELLO?");
console.log(req);
res.json(req.body);
})
... I don't get the "HELLO?" console log, but I get the "I'm on the click event!", so it looks like the on click event is working.
Also, for some reason, other routes work. But any new ones that I make just don't work. For example, this code works from the front-end:
function getStock() {
$.get("/api/new/" + stock.name, function(data) {
stock = {
ticker: data.ticker,
price: data.price
}
allStocks.push(stock);
console.log(allStocks);
console.log(allStocks[0])
console.log(allStocks[1])
createNewRow(stock);
});
}
When I look at the network tab in the chrome Developer tools window, I see this:
What is happening??
Ok, so I think I just figured out.
If you check this image
I think it's because I am using passport. So I have two files in my Server folder. One is "account.js", another is "apiRoutes", I use the account.js for my "/login", "/register" routes for when i'm using authentication.
I'm not exactly sure why but it works in my apiRoutes file, not my "account.js" file. Would anyone be able to tell me why? Sorry, i'm very new to programming!

Azure using wrong callback url during implicit flow login

I'm currently struggling with a weird problem in azure active directory implicit flow oauth authentication. I've implemented a spa webapp using msal.js to login users to their microsoft accont.
The userAgentApplication is executed as shown below:
userAgentApplication = new
Msal.UserAgentApplication(client_id,null,function(errorDes,token,error,tokenType)
{
if(error) {
console.log(JSON.stringify(error));
return;
}
},{ redirectUri: 'https://example.com/app/msalCallback.html' });
When they click login executing the is piece of code:
logInPopup = function() {
var uaa = userAgentApplication;
return new Promise(function(resolve,reject) {
uaa.loginPopup([
'https://graph.microsoft.com/user.read'
]).then(function(token) {
//signin success
console.log(token);
var user = uaa.getUser();
console.log(JSON.stringify(user));
resolve(user);
}, function(error) {
console.log(JSON.stringify(error));
reject(error);
});
})
}
The popup comes up and the user tries to login but the following error comes up:
Microsoft account is experiencing technical problems. Please try again later.
In the url the error parameters string is:
error_description=The provided value for the input parameter
'redirect_uri' is not valid The expected value is
'https://login.live.com/oauth20_desktop.srf' or a URL which matches
the redirect URI registered for this client application.
Upon further research I found that though I configured the redirect uri to be
https://example.com/app/msalCallback.html
(Which I confirmed on the application registration page to be true)
The redirect_uri of the /oauth2/v2.0/authorise url in the login popup page is:
redirect_uri=https://example.com/app/
Which is weird but the above uri is not random one. It is in fact the callback uri for a previous previously registered but now deleted app with the same name.
Further investigation showed that when I config Msal to use the old the redirect_uri login passes.
I'm fresh out of ideas. It looks like a bug in the azure network but wanted to know if anyone else has had this problem or at least point me in the right direction towards getting in contact with azure to find a fix.
Thanks in advance
I've found the cause of the problem after carefully reviewing the msal.js documentation i found that i was setting the redirectUri incorrectly. The correct way is as follows:
var userAgentApplication = new
Msal.UserAgentApplication(client_id,null,function(errorDes,token,error,tokenType)
{
if(error) {
console.log(JSON.stringify(error));
return;
}
});
userAgentApplication.redirectUri = 'https://example.com/app/msalCallback.html'
Hope that helps.
regards

Refresh Office365 Authorization Token from Javascript

I currently have an issue with one of my apps.
The issue is that a user can keep the page open for a prolonged period of time before entering any data, so occasionally, when they enter data and hit the submit button, they are redirected to o365 for authentication and therefore lose the entered data.
I have all the standard authentication working for the app. However, i believe in order to do this, i would need to get a refreshed token in javascript when the submit button is clicked, and send this token to an api method in order to give access.
Is this possible and does anybody know how to go about it?
It is an MVC ASP.NET application using Owin O365 security with Microsoft Azure AD.
I am not sure what information or code snippets would be relevant here so if there is anything i can provide, please ask.
I have found multiple examples of getting tokens etc with angular, however, this is not an SPA and does not use angular.
Many Thanks in advance.
UPDATE
I have attempted to retrieve a token using ADAL JS using the following code but it doesnt seem to recognise the AuthorizationContext(config) call:
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.0/js/adal.min.js"></script>
$('#btnSubmit').on('click', function (e) {
e.preventDefault();
CheckUserAuthorised();
});
function CheckUserAuthorised() {
window.config = {
instance: 'https://login.microsoftonline.com/',
tenant: '##################',
clientId: '###################',
postLogoutRedirectUri: window.location.origin,
cacheLocation: 'localStorage'
};
var authContext = new AuthorizationContext(config); //THIS LINE FAILS
var user = authContext.getCachedUser();
if (!user) {
alert("User Not Authorised");
authContext.login();
}
else {
alert('User Authorized');
}
}
This gives the following error in console:
'AuthorizationContext' is undefined
UPDATE
I have no got passed the undefined error. This was because i was calling AuthorizationContext rather than AuthenticationContext. Schoolboy error. However now, whenever i check the user property of the context, it is always null. And i do not know a way around this as the context is initialised on page load.
There is a lack of a step in your code, here is a simple code sample, hope it will help you:
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.10/js/adal.min.js"></script>
<body>
login
access token
get user
</body>
<script type="text/javascript">
var configOptions = {
tenant: "<tenant_id>", // Optional by default, it sends common
clientId: "<client_id>",
postLogoutRedirectUri: window.location.origin,
}
window.authContext = new AuthenticationContext(configOptions);
var isCallback = authContext.isCallback(window.location.hash);
authContext.handleWindowCallback();
function getToken(){
authContext.acquireToken("https://graph.microsoft.com",function(error, token){
console.log(error);
console.log(token);
})
}
function login(){
authContext.login();
}
function getUser(){
var user = authContext.getCachedUser();
console.log(user);
}
</script>
The code sample is from the answer of No 'Access-Control-Allow-Origin' header with Microsoft Online Auth. The issues are different but they are in the same scenario.
any further concern, please feel free to let me know.
I found a similar example on the web and your problem seems to be related to the object you are instantiating.
Instead of
new AuthorizationContext(window.config);
try
new AuthenticationContext(window.config);
The code ran just fine showing that the user was not authenticated.

React/Redux + super agent, first call gets terminated

I am writing a react-redux app where I am making some service calls in my middlewares using superagent. I have found a very strange behavior where the first call to my search api always gets terminated. I have tried waiting 10-30 seconds before making the first call, and logging every step along the process and I cannot seem to pinpoint why this is happening.
My action creator looks like
export function getSearchResults(searchQuery) {
return {
query: searchQuery,
type: actions.GO_TO_SEARCH_RESULTS
}
}
It hits the middleware logic here :
var defaultURL = '/myServer/mySearch';
callPendingAction();
superagent.get(defaultURL)
.query({query: action.query})
.end(requestDone);
//sets state pending so we can use loading spinner
function callPendingAction() {
action.middlewares.searchIRC.readyState = READY_STATES.PENDING;
next(action);
}
//return error or response accordingly
function requestDone(err, response) {
console.log("call error", err);
const search = action.search;
if (err) {
search.readyState = READY_STATES.FAILURE;
if (response) {
search.error = response.err;
} else if (err.message) {
search.error = err.message;
} else {
search.error = err;
}
} else {
search.readyState = READY_STATES.SUCCESS;
search.results = fromJS(response.body);
}
return next(action);
}
The query is correct even when the call is terminated, I get this err message back :
Request has been terminated
Possible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.
at Request.crossDomainError (http://localhost:8000/bundle.js:28339:14)
at XMLHttpRequest.xhr.onreadystatechange (http://localhost:8000/bundle.js:28409:20)
It appears the page refreshes each time too.
I cannot seem to find any clues as to why this happens, it seems not matter what the first call fails, but then it is fine after that first terminated call. Would appreciate any input, thanks!
UPDATE: so it seems this is related to chrome, I am on Version 47.0.2526.80 (64-bit). This app is an iframe within another app and I believe that is causing a problem with chrome because when I try this in firefox there is no issue. What is strange is only the first call gives the CORS issue, then it seems to be corrected after that. If anyone has input or a workaround, I would greatly appreciate it. Thanks for reading.
Had the same problem, just figured it out thanks to the answer provided by #KietIG on the topic ReactJS with React Router - strange routing behaviour on Chrome.
The answer had nothing to do with CORS. The request was cancelled because Chrome had navigated away from the page in the middle of the request. This was happening because event.preventDefault() had not been called in one of the form submit handlers. It seems Chrome handles this differently than other browsers.
See the answer link above for more detail.
In my case this was happening when I tried to set a random HTTP request header (like X-Test) on the client side and either AWS Lambda rejected it during the OPTIONS request or something else did that.
I don't know about the side effects, but you're getting CORS errors. Add the .withCredentials() method to your request.
From the superagent docs:
The .withCredentials() method enables the ability to send cookies from
the origin, however only when "Access-Control-Allow-Origin" is not a
wildcard ("*"), and "Access-Control-Allow-Credentials" is "true".
This should fix it:
superagent.get(defaultURL)
.query({query: action.query})
.withCredentials()
.end(requestDone);
More information on Cross Origin Resource Sharing can be found here.

Categories

Resources