How to ask to the service worker to ignore requests matching a specific URL pattern in Polymer? - authentication

My application is built on Polymer v2 and uses the Firebase Auth service for authentication. Actually, I use the login-fire element. For a better experience on mobile devices, I choose to sign-in with redirect.
In the "network" tab of the DevTool (in Chrome) I see that a request containing the /__/auth/handler? pattern is sent for requesting Google authentication (for example, if the provider used is Google).
With the service workers enabled, this request is caught and the response is the login page of my application. No login attempted, the response comes from the service worker and I get a Network Error from Firebase API because of a timeout.
When I deploy the app without service workers the authentication process is working and I can reach the app.
I tried many ways to config the service workers to ignore all requests to a URL with the /auth/ pattern but I failed.
See the last version of my config file bellow.
sw-precache-config.js
module.exports = {
globPatterns: ['**\/*.{html,js,css,ico}'],
staticFileGlobs: [
'bower_components/webcomponentsjs/webcomponents-loader.js',
'images/*',
'manifest.json',
],
clientsClaim: true,
skipWaiting: true,
navigateFallback: 'index.html',
runtimeCaching: [
{
urlPattern: /\/auth\//,
handler: 'networkOnly',
},
{
urlPattern: /\/bower_components\/webcomponentsjs\/.*.js/,
handler: 'fastest',
options: {
cache: {
name: 'webcomponentsjs-polyfills-cache',
},
},
},
{
urlPattern: /\/images\//,
handler: 'cacheFirst',
options: {
cacheableResponse: {
statuses: [0, 200],
},
},
},
],
};
Do you have a better solution? Do you notice what I missed?
Thank you for your help.

You can add this to your sw-precache-config.js file
navigateFallbackWhitelist: [/^(?!\/auth\/)/],

You should only whitelist the paths of your application. This should be known to you.
So everything you do not whitelist, will not be served from the serviceworker.
navigateFallbackWhitelist: [/^\/news\//,/^\/msg\//, /^\/settings\//],
With this example, only news/*, msg/*,settings/* will be delivered.
/auth/*,/api/*,... will not be caught.

Related

NUXT Redirect issue when making a POST request to external API

I have a form that I built in Nuxt. I'm trying to submit it to an external API. The expected response is a JWT token.
async login() {
const res = await this.$axios.$post(`/api/token`, {
username: this.username,
password: this.password
}, this.headers )
console.log(res)
}
Trying to call the API directly gets me a CORS error, so I use proxy settings in my nuxt.confix.js.
...
modules: [
'#nuxtjs/axios',
'#nuxtjs/proxy'
],
axios: {
baseURL: '/',
proxy: true
},
proxy: {
'/api/': { target: 'https://<apiurl>.com/', changeOrigin: true }
},
...
Now when I check the network tab, it shows a 301 redirect, but the data that was sent in the post request gets thrown away, and it makes a get request to the API which returns a 405 error (because it's expecting a POST request with a data and not an empty GET request).
How can I make a POST request to an external API using NUXT? Is this an option at all?
I tried changing changeOrigin: false, and that seems to get rid of the issue, but it throws a 500 server error instead and an npm error that says
ERROR [HPM] Error occurred while proxying request localhost:3000/api/token to https://<apiurl>.com/ [ERR_TLS_CERT_ALTNAME_INVALID] (https://nodejs.org/api/errors.html#errors_common_system_errors)
Thank you
The problem is not how to send api to an external API ... the problem is in the external API it self ... make sure the external API has no credentials required to make any action ...
if you can make a request to https://jsonplaceholder.typicode.com/posts and get results that means there is no problems in your code ... cors erros in most cases are backend issue ... which means .. the backend developer who worked on it should fix it

Simple peer different network calling Issue

I am using simple peer for my video call web application. when I call people in the same network video call is working perfectly. But in the different networks, it is not working. I also added ICE servers(stun/turn) to simple peer. Still, the same issue is happening can anyone please help me out. I am getting this issue in the console
Error: Connection failed. at h (index.js:17)at f.value (index.js:654) at RTCPeerConnection.t._pc.onconnectionstatechange (index.js:119)
const peer = new Peer({
initiator: true,
trickle: false,
stream,
config: {
iceServers: [
{
urls: "stun:numb.viagenie.ca",
username: "************",
credential: "************"
},
{
urls: "turn:numb.viagenie.ca",
username: "************",
credential: "************"
}
]
}
});
I had facing through the same issue.
I'm not sure if that has to do with those specific iceServers but I replace them with this ones on it works
iceServers: [
{ urls: 'stun:stun.l.google.com:19302' },
{ urls: 'stun:stun1.l.google.com:19302' },
{ urls: 'stun:stun2.l.google.com:19302' },
{ urls: 'stun:stun3.l.google.com:19302' },
{ urls: 'stun:stun4.l.google.com:19302' },
{
url: 'turn:turn.bistri.com:80',
credential: 'homeo',
username: 'homeo',
},
{
url: 'turn:turn.anyfirewall.com:443?transport=tcp',
credential: 'webrtc',
username: 'webrtc',
},
Everything is working good but now my problem is that safari is not working just chrome with iOS
If someone knows how to handle this compatibility please contact me! :D
my issue here was with the stun/turn server.we can check the status of servers using
https://webrtc.github.io/samples/src/content/peerconnection/trickle-ice/
If you test a STUN server, it works if you can gather a candidate with type "srflx". If you test a TURN server, it works if you can gather a candidate with type "relay".
check you are getting this

No Microsoft ID platform and OpenID Connect protocol login parameters

The client id parameter is not passed when logging in from an app add-in to outlook.
The default browser uses Microsoft edge and uses the Microsoft openid login function.
The code below is the msal code set in my angular app.
const isIE = window.navigator.userAgent.indexOf('MSIE ') > -1 || window.navigator.userAgent.indexOf('Trident/') > -1 || window.navigator.userAgent.indexOf('Chrome') > -1;
export var _msalConfig: Configuration = {
auth: {
clientId: '', // This is your client ID
authority: 'https://login.microsoftonline.com/common/', // This is your tenant ID
redirectUri: '', // This is your redirect URI
},
cache: {
cacheLocation: "localStorage",
storeAuthStateInCookie: isIE,
}
};
#NgModule({
declarations: [
AppComponent,
HomeComponent,
],
imports: [
BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
HttpClientModule,
FormsModule,
RouterModule.forRoot(appRoutes, { useHash: true }),
MsalModule.forRoot(_msalConfig, {
popUp: !isIE,
consentScopes: [
'user.read',
'openid',
'profile',
],
unprotectedResources: [],
protectedResourceMap: [
['https://graph.microsoft.com/beta/me', ['user.read']]
],
extraQueryParameters: {}
})
],
})
If you log in from the web page, it works normally, but if you log in through the add-in app inside Outlook, the following error message appears.
error:invalid_request
error_description:The mandatory 'client_id' parameter is missing.
If anyone knows about the error, please help me.
Sounds like client-id is not passed correctly. I would suggest you to debug and see how the control flow works; also i would suggest you to use developer tools in IE/Edge. This way you can see whether the value is passed correctly or not. In addition, i want you to check the documentation.
When using the SSO token as an identity in an Outlook add-in, we recommend that you also use the Exchange identity token as an alternate identity. Users of your add-in may use multiple clients, and some may not support providing an SSO token. By using the Exchange identity token as an alternate, you can avoid having to prompt these users for credentials multiple times. Here is the link.

vue/cli-plugin-pwa: server requests (with axios) aren’t cached by the service worker

I’m unsuccessfully trying to add PWA to the project. Server requests aren’t cached by the service worker. Request addresses aren’t added to Cache Storage. Accordingly, the offline mode doesn’t work.
Project config:
vue spa
requests to the server using axios library
server responses don’t contain cache-control header
pwa is implemented using the standard vue plugin: vue /
cli-plugin-pwa
PWA config in vue.config.js:
module.exports = {
publicPath: '/',
pwa: {
name: 'Old Vehicles',
manifestOptions: {
name: "Old Vehicles",
display: "standalone",
scope: "/",
start_url: "/"
},
workboxPluginMode: 'GenerateSW',
workboxOptions: {
navigateFallback: '/index.html',
runtimeCaching: [{
urlPattern: new RegExp('^http'),
handler: 'NetworkFirst',
options: {
networkTimeoutSeconds: 2,
cacheName: 'api-cache',
cacheableResponse: {
statuses: [0, 200],
},
},
}]
}
}
};
PS And also this: developer console in browser -> Application tab -> Installability -> "Page does not work offline". The service worker successfully connected (excepting request caching), the manifest is identified. Why does it show such a message?
I'm currently learning about PWA too. What I read about this issue:
Axios is using behind the lines XHR requests and not fetch requests.
Because workers run separately from the main thread, service workers are independent of the application they are associated with, consequences : synchronous XHR and localStorage cannot be used in a service worker
So I guess you may need to use standard fetch requests.
The other answer is misleading.
Assuming the service worker is successfully registered/etc, any (https) network request on the main thread (or web worker threads) will be sent via the service worker.
Axios is part of the main thread, not the service worker thread.
XHR in the main thread are the same as any other method (eg js: fetch(), html: , css: url())...all requests will trigger the 'fetch' event in the service worker (presumably to be cached).
The problem is quite likely to be because the network requests in the main thread are http, not https.
If possible, upgrade the server serving the resources from http to https, and change the URLs used on the main thread. It will not be possible to 'rewrite' the protocol in the service worker.
If you cannot change the code on the main thread for some reason (eg legacy app with no source), then it should be possible to get the server that is sending the document that causes the request (ie the js file with fetch('http://.../')/XHR, the html file with <img src="http://.../">, the css file with url(http://.../)) to add a header:
Content-Security-Policy: upgrade-insecure-requests
More info: https://github.com/w3c/ServiceWorker/issues/813
and https://w3c.github.io/webappsec-upgrade-insecure-requests/#goals

How to avoid that AWS Amplify OAuth tries to parse every oauth process

I'm working with a react-native application where i have implement the Authentication flow using AWS Amplify and Federated signin. This is the amplify configuration:
Auth: {
identityPoolId: 'XXX',
region: 'XXX',
mandatorySignIn: false,
userPoolId: 'XXX',
userPoolWebClientId: 'XXX',
oauth: {
domain: env.AWS_OAUTH_DOMAIN,
scope: ['email', 'profile', 'openid','aws.cognito.signin.user.admin', 'given_name', 'family_name', 'user_gender', 'user_birthday', 'user_location'],
redirectSignIn: myapp://signin,
redirectSignOut: myapp://logout,
responseType: 'code',
},
},
Everything works fine. Until now.
Now i have to add another OAuth authentication for other purposes (connecting Strava to my application). Everything works fine, until the Strava authorization dialog redirect to my app at the url: runcard://profilo/servizi?code=XXX&scope=activity%3Aread%2Cread (this callback url is different from the one i've set for amplify configuration). Once redirected, amplify is there, ready to raise an exception by Amplify OAuth:
WARN Possible Unhandled Promise Rejection (id: 0):
TypeError: undefined is not an object (evaluating '_a.accessToken')
I believe that since the callback url has a code parameter, Amplify is trying to do the job himself. Without success.
Does anyone faced the same issue?
I found the cause of the issue!
Amplify is specifically looking for a param in any deeplinked URL called code.
I too was using code for a purpose other than the oauth callback (sign up confirmation code).
Changing the param to anything else (e.g. confirmationCode) prevents the accessToken error.
At the end, I've used this workaround: I removed the Amplify listener and I added a new listener that will parse only Amplify OAuth URLs.
Amplify.configure({ ... });
Analytics.getInstance();
// Workaround: this is to avoid that Amplify OAuth try to parse EVERY url as a OAuth callback url
// https://stackoverflow.com/questions/59883011/how-to-avoid-that-aws-amplify-oauth-tries-to-parse-every-oauth-process
Linking.removeAllListeners('url');
Linking.addEventListener('url', (url) => {
if (url.url.indexOf(AWS_OAUTH_REDIRECT_SIGNIN !== -1 || url.url.indexOf(AWS_OAUTH_REDIRECT_SIGNOUT) !== -1) {
Amplify.Auth._handleAuthResponse(url.url);
}
});
AWS_OAUTH_REDIRECT_SIGNIN and AWS_OAUTH_REDIRECT_SIGNOUT are the same specified in Amplify configuration:
AWS: {
Auth: {
oauth: {
redirectSignIn: AWS_OAUTH_REDIRECT_SIGNIN,
redirectSignOut: AWS_OAUTH_REDIRECT_SIGNOUT,
responseType: 'code'
}
}
}