Silent Renewal in Ionic 3 with Identity Server 4 - javascript

So I am trying to implement silent renewal in an ionic 3 application, I am still learning about the whole thing so I'll try to be as descriptive as possible please correct me if I am wrong.
Authentication
I am using Implicit flow for my authentication using the In App Browser.
The user is redirected to the authentication server page
After a success authentication I retrieve the id-token & access-token
As I understand the id-token is for authentication and access-token is for authorization with the API.
I have followed this article to help me set this up (Particularly the "Deploy to Mobile Device" section) for my Identity Server.
As done in the article I am using angular-oauth2-oidc to assist me with storing information about redirect links, issuer, etc...
I have attempted to achieve this in 3 different ways, 2 of them work but I don't understand how to retrieve the new access-token and id-token, and the last one returns an error. each of them left me with questions.
First: oauthService
The angular-oauth2-oidc library has a silentRefresh() method, and this github MD describes how to use it using a hidden iframe very vaguely so I barely understand how this works. I have created a silent-refresh.html page in the same directory, but using http://localhost:8000/silent-refresh.html return's a 404. Calling the silentRefresh() method successfully re-authenticates on the server side but the request times-out on the client side, as said in the MD file, something is wrong with the iframe.
Question 1: Does the library create a new iframe and then waits for a response to the http://localhost:8000/silent-refresh.html page but is never found so I never get my response? How to proceed to retrieve my tokens?
Second: iframe
So here I follow this article where I create an iframe and add it to the body. I create my own url (similar to the one made by the silentRefresh() method), and assign it to the src of the iframe. Again on the server side everything is fine and it tries to return the tokens to http://localhost:8000.
public startRenew(url: string) {
this._sessionIframe.src = url;
return new Promise((resolve) => {
this._sessionIframe.onload = () => {
resolve();
}
});
}
Question 2: How to proceed to retrieve the tokens? as it doesn't update my tokens automatically, and I don't see how the code above can do it.
Third: In App Browser
I thought this would work fine as I already know how to process the request using the In App Browser. So I tried to use the same url that worked for the iframe in the 2nd part. However this returns an error: prompt=none was requested. But user is not authenticated. on the server side, which tells that the server can't find the session so it doesn't know who is requesting the token renewal.
Question 3: Is there a specific reason this won't work other than I made a mistake?
NOTE: Took longer than expected to write this will edit this in a bit.

oAuthService
So I looked in to the implementation of the silent refresh, to see what it does. It creates an iframe with a default id, unless you override it. That cleared up a lot of confusion as to what was actually happening.
The next mistake I did was placing the silent-refresh.html file in the src/ folder, that makes it inaccessible to the iframe. Instead the file should have been placed in the www/ folder.
Then inside the iframe I kept getting the net::ERR_CONNECTION_REFUSED error. This was due to CORS and is solved by editing the Client int the Config.cs file on the Authentication Server:
AllowedCorsOrigins = { "http://localhost:8100", "http://<ip>:8100/", "http://<ip>:8100/silent-refresh.html" },
WARNING: This didn't work once I wanted to take this outside serving in the browser (ionic serve) or emulating on my device with ionic cordova run android -c-l-s, these made the root url return something like http://<ip>/. But once ran with ionic cordova run android (without the flags), window.location.href would return file:///<example>/<something>/index.html, using this sort of path (file:///<example>/<something>/silent-refresh.html) as a redirect url caused an ERR_UNSAFE_REDIRECT error to display in the iframe.
Perhaps silentRefresh() is an Angular only solution?
In App Browser
The mistake that caused the original error was having clearsessioncache and clearcache set to yes when creating the browser, caused the session to be wiped so the authentication server didn't know who it was duh, now reduced to this:
const browser = window.cordova.InAppBrowser.open(oauthUrl, '_blank',
'location=no, hidden=yes'
);
Regular redirect url of http://localhost:8100 could be used to catch the request with the new tokens. And the silent-refresh.html page is not needed.
Here is the code for creating the oauthUrl:
buildOAuthRefreshUrl(nonce): string {
return this.oauthService.issuer + '/connect/authorize?' +
'response_type=id_token%20token' +
'&client_id=' + this.oauthService.clientId +
'&state=' + nonce +
'&redirect_uri=' + encodeURIComponent(this.oauthService.redirectUri) +
'&scope=' + encodeURI(this.oauthService.scope) +
'&nonce=' + nonce +
'&prompt=none';
}
The rest of the code is pretty much identical to the originally mentioned article

Related

window.onload with querystring Not working on deployed MVC6 project

I have been developing a website that can display some data. In the table, there is a button in each row to open a new window, where the user can see data related to that line.
I am using MVC 6 and I used Javascript to open the window and passing the 'id' parameter through querystring.
My code is:
The Parent View .cshtml:
The Button:
wButtonClass = "btn btn-warning openW";
<a href="javascript:void(0);" class="#wButtonClass" data-id=#id.ToString()>#buttonText</a>
The Script:
<script>
$(document).ready(function () {
$(".openW").click(function (e) {
var x = $(this).data("id");
var new_window = window.open('/MyView/HandleButton?id='+x, '_blank', 'left=200,top=150,width=1000,height=800,toolbar=1,resizable=0');
});
});
</script>
The Controller:
public IActionResult HandleButton(int id)
{
//Filling the List
return PartialView("DataView", myList);
}
So, it is working just fine from VS, but when I deploy the project to an IIS server (not on my machine), it opens the new window, and says "404 - Not Found", although the URL in the newly opened window is correct (the value is passed)
What could be the problem?
I've been looking through several forum questions, but couldn't find an answer.
Update 1:
Well, technicalliy, in the popup window, the URL is:
http://localhost/MyView/HandleButton?id=5
And it says in the 404 Error Details:
Requested URL http://localhost:80/MyView/HandleButton?id=5
Physical Path C:\inetpub\wwwroot\MyView\HandleButton
Update 2:
Well, I have finally found an answer. It looks very silly, but solved the problem.
I found it here:
IIS 8 Can't see partial view
I had to change the URL and add the application name:
So, instead of: /MyView/HandleButton?id='+x
I Typed: /MyWebApp/MyView/HandleButton?id='+x
Well, it works on the server, but doesn't work in VS. It will be fine (I just change the URL everytime I debug), but is there a way to do this more elegantly?
This could be expected if the routing is incorrect and the URL is incorrect. However, since your URL is correct and you still seeing a 404 error, it likely is an issue with the server configuration.
Verify that the IIS server has the correct permissions to access the
files and folders of your application.
Check that the IIS server has the correct .NET Framework version
installed and that your application is targeting the correct version.
Make sure that the IIS server has the correct MVC version installed
and that your application is targeting the correct version.
Check that the IIS server is configured to handle requests to the
.cshtml files.
Make sure that the MVC routing is configured correctly in the
web.config file of your application.
Check whether the IIS server is running in 32-bit or 64-bit mode.
Make sure that your application is built for the same mode.
Confirm that the server is able to find the DLLs and assemblies that
your application needs.
Check the event logs for any info.
This is italicized, and so
is this.
This is bold, just like this.
useEffect(() => {
var aScript = document.createElement("script");
aScript.type = "text/javascript";
aScript.src = "./js/main.js";
}, []);
You can combine them
if you really have to.

BigCommerce Embedded Checkout NotEmbeddableError: Unable to embed the iframe because the content could not be loaded

I am trying to implement bigcommerce embedded checkout into my rails application.
I followed this url to integrate embedded checkout into my local rails application.
https://developer.bigcommerce.com/api-docs/storefronts/embedded-checkout/embedded-checkout-tutorial
But I have error message of "NotEmbeddableError: Unable to embed the iframe because the content could not be loaded."
These are the steps I did.
I am using rails application locally.
it is running as https://127.0.0.1:3000 (I've tried with localhost, but I can't create site using localhost: it says site name should not contain localhost string)
I created local ssl key and certification and runs the application by
rails s -b 'ssl://127.0.0.1:3000?key=127.0.0.1.key&cert=127.0.0.1.crt'
And I can access the local site by https://127.0.0.1:3000/ although it says 'Not Secure'
I followed the embedded checkout url APIs and able to produce the redirect_urls
for example:
{
"data": {
"cart_url": "https://pbgtest.mybigcommerce.com/cart.php?action=load&id=30df8201-90c9-4950-b784-0d35f16d2b63&token=10b5a5e6853217d23efdaf0b790b707dfd98fabde5495a5f2aaf7238fabbc5a4",
"checkout_url": "https://pbgtest.mybigcommerce.com/cart.php?action=loadInCheckout&id=30df8201-90c9-4950-b784-0d35f16d2b63&token=10b5a5e6853217d23efdaf0b790b707dfd98fabde5495a5f2aaf7238fabbc5a4",
"embedded_checkout_url": "https://pbgtest.mybigcommerce.com/cart.php?embedded=1&action=loadInCheckout&id=30df8201-90c9-4950-b784-0d35f16d2b63&token=10b5a5e6853217d23efdaf0b790b707dfd98fabde5495a5f2aaf7238fabbc5a4"
},
"meta": {}
}
whenever I copy checkout_url or embedded_checkout_url and paste it directly in addressbar it works fine.
I also found that these urls should be at once not twice, so whenever I try a test I regenerate the url
In rails application, I added this code in one of page
<script src="https://checkout-sdk.bigcommerce.com/v1/loader.js"></script>
<script>
$(document).ready(function() {
// const module = await checkoutKitLoader.load('embedded-checkout');
async function show() {
const module = await checkoutKitLoader.load('embedded-checkout');
const service = module.embedCheckout({
url: 'https://pbgtest.mybigcommerce.com/cart.php?embedded=1&action=loadInCheckout&id=30df8201-90c9-4950-b784-0d35f16d2b63&token=10b5a5e6853217d23efdaf0b790b707dfd98fabde5495a5f2aaf7238fabbc5a4',
containerId: 'embedded-checkout-section' #This is div id
});
service
.then(value => {
console.log(value);
})
.catch(err => {
console.log(err);
});
}
show();
}
But I get "NotEmbeddableError: Unable to embed the iframe because the content could not be loaded."
I can't get the proper info like why it failed loading.
I also tested after disable the Anti Virus software but still same error.
Anybody can help?
It is expected behavior that the link is only live for one visit, so you are correct to regenerate these for testing these urls. Is your BigCommerce store published/live? This needs to be true in order for it to be pulled into your embedded checkout experience.
Also, I would recommend using the embedded_checkout url directly.
Got it successful after following steps
Make sure cart channel id matches with one that points to your https localhost
Add route in channel where the embedded checkout needs to be loaded.
In security and privacy settings, check x-frame-options to allow from your https localhost

Google Sign-In API Hang with uncaught error Failed to get parent origin from URL hash

I'm using Google Sign-In JavaScript client for months without problem.
But recently when user tapping on sign in button from webapp that added to homescreen, the signin pop-up just hang without showing any content.
When debugged via remote debugging, an error is displayed in console pane:
Uncaught Failed to get parent origin from URL hash!
originated from 4188232449-v2-idpiframe.js:136 (javascript loaded internally by google library).
I'm sure it's not programming/config error since the same webapp was previously working for months without problem, and I haven't modified any code.
I've tried google search for this particular problem and browse Google documentation for any recent changes in Google Sign-In API without any luck.
Is it bug from Google API Javascript client library, glitch from recent Chrome browser update on Android, or there is some changes in API usage that I doesn't yet aware?
Library used is https://apis.google.com/js/platform.js
This is init param for gapi.auth2.init():
{
client_id: GAPI_CID, // defined as constant
cookiepolicy: 'single_host_origin',
prompt: 'select_account',
ux_mode: 'popup',
fetch_basic_profile: true
}
Any insight will be much appreciated. Thank you.
P.S.: This problem is different with Uncaught Failed to get parent origin from URL hash since on that case the problem is caused by misconfiguration of required credential in Google API console.
If you never had succedded in integrating sign-in flow with your app, perhaps answer from that post can help you.
Otherwise, if you have had successfully integrated sign-in flow for some time but recently problem suddenly/erratically appears with symptom of blank screen on popped-up window, than you have same problem with me.
I can confirm we are experiencing the same problems at my company since recently. It seems a bit erratic, not 100% of the time. But for some users, some time, they are met with an empty sign-in popup with the url pointing to "https://accounts.google.com/o/oauth2/iframe" but nothing happens.
Not a complete answer yet, but this may be a reasonable workaround for some. I updated the ux_mode to use redirect and it is partially working now.
auth2 = gapi.auth2.init({
client_id: '1234.apps.googleusercontent.com',
scope: 'profile email',
ux_mode: 'redirect',
redirect_uri: 'https://blahblah.io/oauth2callback'
})
NOTE: it seems redirect_uri is required, contrary to Google's docs. This isn't a perfect drop-in replacement, but it solves the "URL hash!" error
This blog post and the Git Repo in it could also be helpful for anyone attempting to use redirect
My electron app started to fail today for the same reason. Been debugging quite a lot and I think found the reason, but don't know how to solve it, why it happened, or if it is electron or google's fault.
In my electron app, I have 2 webviews, one for the main content and another one for google popup dialogs.
So when google needs to open the authentication, it generates this IFRAME:
<iframe id="ssIFrame_google"
sandbox="allow-scripts allow-same-origin" aria-hidden="true"
src="https://accounts.google.com/o/oauth2/iframe#origin=https%3A%2F%2Fxxxx.com&rpcToken=dxxd318480305.4777704"
style="... display: none;"></iframe>
Mind that the URL has HASH parameters: your origin and the token.
However, when on the electron side I capture the new-window event in order to open the URL myself in another webview, the event I receive LACKS the hash parameters:
event {
type : "new-window",
url:"https://accounts.google.com/o/oauth2/iframe",
.
.
}
So what google's iframe is complaining about (I debugged it) is exactly that it can't find the origin and rpctoken parameters that should be in the hash parameters.
For a reason I don't understand (I haven't updated electron) the new-window event does not receive the full url anymore.
Using #howMuchCheeseIsTooMuchCheese answer below I have changed the flow to use the redirect callback, then capture that callback myself and restart the application. It is not ideal, but at least I can login into my applications.

CherryPy terminates session after $window.location.href

For a Django 1.8 app with Angular.js & Django Rest Framework I'm using CherryPy server to serve the app over WSGI.
For this purpose I'm basically reusing this code, which works fine, until I use the following angular.js command in one of my *.js files:
url = patientDetailView + response.data.id + '/';
$window.location.href=url;
The view this link is pointing to requires (like other views as well) the user to be logged in(authenticated). However, although the user has been already logged in after $window.location.href=url django redirects to the login screen where the user needs to log-in again! My guess is that this may be due to the session being terminated (?). I don't see this problem while running the django dev server (./manage.py runserver)
Anybody can point me to why this is happening and how to fix that? I'm running out of ideas...

How to force client reload after deployment?

I'm using the MEAN stack (mongo, express, angular and node). I'm deploying relatively frequently to production...every couple of days. My concern is that I'm changing the client side code and the API at times and I would rather not have to ensure backwards compatibility of the API with previous versions of the client code.
In such a scenario, what is the most effective way of ensuring that all clients reload when I push to production? I have seen that Evernote for example has a pop-up that says something along the lines of please reload your browser for the latest version of Evernote. I would like to do something similiar...do I need to go down the path of socket.io or sock.js or am I missing something simple and there is a simpler way to achieve this?
Update:
AppCache was deprecated summer 2015 so the below is no longer the best solution. The new recommendation is to use Service Workers instead. However, Service Workers are currently still experimental with sketchy (read: probably no) support in IE and Safari.
Alternatively, many build tools now seamlessly incorporate cache-busting and file "versioning" techniques to address OPs question. WebPack is arguably the current leader in this space.
This might be a good use case for using HTML5's AppCache
You'd probably want to automate some of these steps into your deployment scripts, but here is some code you might find useful to get you started.
First, create your appcache manifest file. This will also allow you to cache resources in the client's browser until you explicitly modify the appcache manifest file's date.
/app.appcache:
CACHE MANIFEST
#v20150327.114142
CACHE:
/appcache.js
/an/image.jpg
/a/javascript/file.js
http://some.resource.com/a/css/file.css
NETWORK:
*
/
In app.appcache, the comment on line #v20150327.114142 is how we indicate to the browser that the manifest has changed and resources should be reloaded. It can be anything, really, as long as the file will look different to the browser from the previous version. During deployment of new code in your application, this line should be modified. Could also use a build ID instead.
Second, on any pages you want to use the appcache, modify the header tag as such:
<html manifest="/app.appcache"></html>
Finally, you'll need to add some Javascript to check the appcache for any changes, and if there are, do something about it. Here's an Angular module. For this answer, here's a vanilla example:
appcache.js:
window.applicationCache.addEventListener('updateready', function(e) {
if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
// Browser downloaded a new app cache.
// Swap it in and reload the page to get the latest hotness.
window.applicationCache.swapCache();
if (confirm('A new version of the application is available. Would you like to load it?')) {
window.location.reload();
}
}
else {
// Manifest didn't changed. Don't do anything.
}
}, false);
Alternatively, if AppCache won't work for your situation, a more ghetto solution would be to create a simple API endpoint that returns the current build ID or last deployment date-time. Your Angular application occasionally hits this endpoint and compares the result to it's internal version, and if different, reloads itself.
Or, you may consider a live-reload script (example), but, while very helpful in development, I'm not sure how good of an idea it is to use live/in-place-reloading of assets in production.
I will tell you my problem first then I will recommend a tentative solution. I wanted to force my user to log out and then log in when a production build is been deployed. At any point in time, there will be two versions of software deployed on production. A version which software which FE knows and a version which Backend knows. Most of the time they would be the same. At any point in time if they go out of sync then we need to reload the client to let the client know that a new production build has been pushed.
I am assuming 99.99% of the time the backend would have the knowledge of the latest version of the deployed software on production.
following are the two approaches which I would love to recommend:-
The backend API should always return the latest version of the software in the response header. On the frontend, we should have a common piece of code that would check if the versions returned by the API and that present on the FE are the same. if not then reload.
Whenever a user logs in. the BE should encode the latest software version in the JWT. And the FE should keep sending this as a bearer token along with every API request. The BE should also write a common interceptor for every API request. which would compare the software version in the JWT received from the API request and the
Maybe you can add hash to your client code file name. eg app-abcd23.js.
So the browser will reload the file instead of get it from cache. or you can just add the hash to url.eg app.js?hash=abcd23 but some browser may still use the cached version.
i know rails has assets-pipline to handle it, but i am not familiar with MEAN stack. there should be some package in npm for that purpose.
And i dont think it is really necessary to use socket.io if you want to notify the user their client code is out of date. you can define your version in both html meta tag and js file,if mismatch, show a popup and tell the user to refresh.
Try to limit your js/files to expire within smaller periodic time, ie: 1 days.
But in case you want something that pop-out and tell your user to reload (ctrl+f5) their browser, then simply make a script that popup that news if you just changed some of your files, mark the ip/session who have just reload/told to reload, so they will not be annoyed with multiple popup.
I was facing the same problem recently. I fixed this by appending my app's build number with my js/css files. All my script and style tags were included by a script in a common include files so it was trivial to add a 'build number' at the end of the js/css file path like this
/foo/bar/main.js?123
This 123 is a number that I keep track of in my same header file. I increment it whenever I want the client to force download all the js files of the app. This gives me control over when new versions are downloaded but still allows the browser to leverage cache for every request after the first one. That is until I push another update by increment the build number.
This also means I can have a cache expiry header of however long I want.
Set a unique key to local storage during the build process
I am using react static and loading up my own data file, in there i set the ID each time my content changes
Then the frontend client reads the key with from local storage
(if the key does not exist it must be the first visit of the browser)
if the key from local storage does not match it means the content has changed
fire line below to force reload
window.replace(window.location.href + '?' + key)
in my case i had to run this same line again a second latter
like
setTimeout( (window.replace(window.location.href + '?' + key))=> {} , 1000)
full code below:
const reloadIfFilesChanged = (cnt: number = 0, manifest: IManifest) => {
try {
// will fail if window does not exist
if (cnt > 10) {
return;
}
const id = localStorage.getItem('id');
if (!id) {
localStorage.setItem('id', manifest.id);
} else {
if (id !== manifest.id) {
// manifest has changed fire reload
// and set new id
localStorage.setItem('id', manifest.id);
location.replace(window.location.href + '?' + manifest.id);
setTimeout(() => {
location.replace(window.location.href + '?' + manifest.id + '1');
}, 1000);
}
}
} catch (e) {
// tslint:disable-next-line:no-parameter-reassignment
cnt++;
setTimeout(() => reloadIfFilesChanged(cnt, manifest), 1000);
}
};

Categories

Resources