How do I log out of a chrome.identity oauth provider - google-chrome-extension

I'm using chrome.identity to log into a 3rd party oauth provider in an chrome extension. It works fine for logging in- when I use launchWebAuthFlow I am presented with the third party login screen and redirected back to my application after the signin flow.
However, I can't find a way to enable log out functionality in my extension. There doesn't seem to be a function to clear the cached logged in identity. The next time that launchWebAuthFlow is called, it will automatically log me in as the first user, and not prompt me to log in again.
Is there any way to clear the logged in state of the chrome.identity plugin?

I am not aware about the specific third party provider. But I faced the similar problem when using Google Oauth with chrome.identity.launchWebAuthFlow(). I could sign in the user, but not sign out using removeCachedAuthToken()
In this case, to logout the user, I used chrome.identity.launchWebAuthFlow() with Google's logout URL rather than it's oauth URL
chrome.identity.launchWebAuthFlow(
{ 'url': 'https://accounts.google.com/logout' },
function(tokenUrl) {
responseCallback();
}
);
This worked pretty well.

I've found that calling these two in the sequence is working:
var url = 'https://accounts.google.com/o/oauth2/revoke?token=' + token;
window.fetch(url);
chrome.identity.removeCachedAuthToken({token: token}, function (){
alert('removed');
});

You should add prompt=select_account to your auth URL. Your problem will be solved.
https://accounts.google.com/o/oauth2/auth?client_id={clientId}&response_type=token&scope={scopes}&redirect_uri={redirectURL}&prompt=select_account

For me, https://accounts.google.com/logout does not work. But https://accounts.google.com/o/oauth2/revoke?token=TOKEN work well, using simple window.fetch(url), not with hrome.identity.launchWebAuthFlow.

You can clear the identity cache using the chrome.identity.removeCachedAuthToken(object details, function callback) method.
https://developer.chrome.com/apps/identity#method-removeCachedAuthToken

I happened to hit the same problem recently, and I finally solved it by adding login_hint=<new_user> and prompt=consent in the login URL.

I could achieve result only with this implementation
chrome.identity.getAuthToken({ 'interactive': false }, currentToken => {
if (!chrome.runtime.lastError) {
// Remove the local cached token
chrome.identity.removeCachedAuthToken({ token: currentToken }, () => {})
// Make a request to revoke token in the server
const xhr = new XMLHttpRequest()
xhr.open('GET', `${googleRevokeApi}${currentToken}`)
xhr.send()
// Update the user interface accordingly
// TODO: your callback
}
})

If you try launchWebAuthFlow to logout but get User interaction required error, then you need to add one more flag along with the url:
chrome.identity.launchWebAuthFlow (
{'url': 'https://some-logout-url/',
'interactive': true },
function(result) {
console.log(result);
}
);

Related

Updating Auth0 JWT without invalidating sessions

I have an app using Auth0, made with ReactJS and NodeJS. Things are working fine for the most part.
The design is such that we decorate each request with an admin flag, and I have the Auth0 profile encoded in my JWT token.
This way I can do things like:
server.route({
method: 'POST',
url: '/.../...',
preValidation: server.authenticate,
handler: async (req, res) => {
const { user } = req;
if (!user['admin']) {
...
}
...
}
});
I am happy, with this approach, except for one problem that I have not resolved. How to deal with a request coming from the user to update their own profile. After the profile is updated, JWT stays the same and has outdated profile information.
Can anything be done about this, short of logging users out on each profile update? Is there a way to update JWT without ending the session?
This is practically impossible as it defeats the purpose of statelessness of jwts. However, in this particular usecase, after the profile is updated, you can create a new jwt and add it as part of the response, so the client picks up on the new token and uses it for further requests
Based on my research, the solution is to:
Repeat the login automatically after each profile update or notify the end-user that and let them choose if they want to repeat the login.

Trying to use oauth flow in Electron desktop app (with spotify API)?

I have a React app in Electron, and I'm trying to access the spotify API using the spotify-web-api-node library. However, I'm not sure exactly how the oauth flow is meant to work inside of an Electron app... Firstly, for the redirect URL, I used this question and added a registerFileProtocol call to my file. Then I added a specific ipcMain.on handler for receiving the spotify login call from a page, which I've confirmed works with console logs. However, when I get to actually calling the authorizeURL, nothing happens?
This is part of my main.js:
app.whenReady().then(() => {
...
protocol.registerFileProtocol(
"oauthdesktop",
(request, callback) => {
console.log("oauthdesktop stuff: ", request, callback);
//parse authorization code from request
},
(error) => {
if (error) console.error("Failed to register protocol");
}
);
});
ipcMain.on("spotify-login", (e, arg) => {
const credentials = {
clientId: arg.spotifyClientId,
clientSecret: arg.spotifySecret,
redirectUri: "oauthdesktop://test",
};
const spotifyApi = new SpotifyWebApi(credentials);
console.log("spapi: ", spotifyApi);
const authorizeURL = spotifyApi.createAuthorizeURL(
["user-read-recently-played", "playlist-modify-private"],
"waffles"
);
console.log("spurl: ", authorizeURL);
axios.get(authorizeURL);
}
I'd expect the typical spotify login page popup to show up, but that doesn't happen. I'd also expect (possibly) the registerFileProtocol callback to log something, but it doesn't. What am I meant to be doing here? The authorization guide specifically mentions doing a GET request on the auth url, which is what I'm doing here...
In a desktop app it is recommended to open the system browser, and the Spotify login page will render there, as part of creating a promise. The opener library can be used to invoke the browser.
When the user has finished logging in, the technique is to receive the response via a Private URI Scheme / File Protocol, then to resolve the promise, get an authorization code, then swap it for tokens. It is tricky though.
RESOURCES OF MINE
I have some blog posts on this, which you may be able to borrow some ideas from, and a couple of code samples you can run on your PC:
Initial Desktop Sample
Final Desktop Sample
The second of these is a React app and uses a Private URI scheme, so is fairly similar to yours. I use the AppAuth-JS library and not Spotify though.

Vue.js 2 Authentication JWT

[ Post has been edited: see below for answer ]
I am trying to make a Vue.js2 application using this boilerplate https://github.com/vuejs-templates/webpack
I am stuck on the Authentication process, using this library: https://github.com/websanova/vue-auth and attempting to use JWT as the authentication method. Never having rolled my own authentication before, I am slightly lost.
Packages I have installed which may be relevant: passport, passport-jwt, jsonwebtokens, passport-local, passport-local-mongoose
Looking at my logs I get a successful login response, but then it attempts to get /auth/user and responds with a 401 (unauthorized error). Perusing the auth library code, a GET req to /auth/user seems to be the expected behavior.
Here is the login code (client side):
methods: {
login() {
this.$auth.login({
body: this.data.body
success(res) {
console.log('Success: '+this.context);
this.localStorage.setItem('auth-token', res.body.token);
},
error(res) {
console.log("Error: " + this.context);
this.error = res.data;
},
rememberMe: true,
fetchUser: true
});
}
}
And here is the appropriate code server-side:
Removed Link | See Edits Section *
What I am sure of is this:
the server does in fact create a JWT which is valid (checked on jwt.io) during the login request. It does not appear to be set anywhere afterwards. It just sits there and then dies. There are mentions of an Authorization Bearer header in the response, which I am certain is not being set. Nor do I understand where or how to do this. There is no token set in localStorage after the login request. I'm not sure if this should exist, but think it likely that it should. In my console, searching local storage yields some strings and large integers, but no mention of a token in it.
Edits (8+ months later)
Gist to Solution here (slashes replaced by dashes in filenames):
https://gist.github.com/wcarron27/b0db7a16df9ceff924d4a75050093c55
The reason my login method originally did not work was that the localStorage token was not set correctly, and thus failed to pass the getData method on the client-side redirect. vue-auth does this by default. By editing the url it hits in the vue-auth config, I was able to direct it to the proper route(BUT only after I properly set the localstorage token. Use Vue.http.options.rootUrl (or something, it's in the main.js file in the gist) to set the Authorization header.
In the code, You must register vue-auth on the client side main.js, and call to it in the Login.vue "login" method. The client side config directs the http calls to the specified route in main.js. In the callback, the user and tokens are set in localStorage and the Vuex store.
The Http reqs go the the API side and hit the route in accounts.js. That route uses a passport strategy defined in ./util/passport.js, as well as a setJWT function defined in ./util/jwtLib.js.
After this, the client is redirected to a route of my choice, and data is populated by my store and ajax calls. Keep in mind, that while this should solve logins, i have not verified code correctness, as basically I would have needed to post the whole of two separate codebases.
Additionally, this does not account for refresh errors. State is dropped on refresh, so do not rely on vuex for persistence. A combination of localStorage and vuex does the trick, though.
I didn't verify this but, does remove the 'this' from your code on line 7 do the magic?
methods: {
login() {
this.$auth.login({
body: this.data.body
success(res) {
console.log('Success: '+this.context);
// original code here --> this.localStorage.setItem('auth-token', res.body.token);
localStorage.setItem('auth-token', res.body.token);
},
error(res) {
console.log("Error: " + this.context);
this.error = res.data;
},
rememberMe: true,
fetchUser: true
});
}
}

Using Hapijs and Bell with twitter provider. How to handle the authorize rejection from Twitter using the Bell module?

I'm using the Hapi framework (nodejs) with the Bell module, working with the Twitter provider.
It was pretty simple to get a working code with the example given in the github page. I access the /login route and I get redirected to Twitter, where I authorize the app and then I'm redirected back to /login?oauth_token=xxxxxxx&oauth_verifier=xxxxxxx where I can have access to the user profile in the request.auth.credentials.
The problem came when I tried to reject the app. Instead of clicking the "Sign In" button on Twitter, I clicked the "Cancel" button and then the "Return to site name" button. This last button redirects me to /login?denied=xxxxxx and then I'm redirected (again) to Twitter to approve the app.
I tried to handle this scenario using another example in the same page https://github.com/hapijs/bell#handling-errors but can't get it to work.
server.route({
method: ['GET', 'POST'],
path: '/login',
config: {
auth: {
strategy: 'twitter',
mode: 'try'
},
handler: function (request, reply) {
if (!request.auth.isAuthenticated) {
return reply('Authentication failed due to: ' + request.auth.error.message);
}
return reply.redirect('/home');
}
}
});
It seems that before checking the request.auth it interprets the /login route and redirects to Twitter. I still don't understand very well the Bell module but it might be that the Twitter strategy is expecting the oauth_token and oauth_verifier in the request.params, but the denied param is not interpreted by the strategy and that's why the redirect happens.
Has somebody managed to handle this scenario?
I found a workaround. It's not an optimal solution but at least allows me to handle the rejection from Twitter.
I had to modify a file inside the bell module. In bell/lib/oauth.js, before the verification of oauth_token
exports.v1 = function (settings) {
var client = new internals.Client(settings);
return function (request, reply) {
var cookie = settings.cookie;
var name = settings.name;
// Sign-in Initialization
// Verify if app (Twitter) was rejected
if (name=='twitter' && request.query.denied) {
return reply(Boom.internal('App was rejected'));
}
if (!request.query.oauth_token) {
// Obtain temporary OAuth credentials
var oauth_callback = request.server.location(request.path, request);
With that change I can catch and show the auth error in the handler, without the automatic redirect.
At least this is the way I managed to make it work. The cons of this modification is that if the bell module is updated then the modification is lost and the bug arise again, unless the updated module comes already with a fix for this. So, you have to keep an eye on that.
Here's the link off the Github issue I created on the Bell repository regarding this bug.

redirect to another app with session token (jwt) in AngularJS and NodeJS

I have a startup module in angularjs. This module is just to login and have public information (login, prices, newsletter...). I have many roles and for each role, i have an app (angular module). I made this architecture because i have complex module for each role and it was impossible to put all roles in one module.
So, for login, i use jsonwebtoken in node like this :
var token = jwt.sign(user, config.secureToken, { expiresInMinutes: 20*5});
res.json({ token: token, user: user });
It works perfectly. I can login into my app. After that, i have to propose a list of roles to redirect to the right module.
In angular, I have AuthHttp service that adds security headers (with token) to call rest service with $http.
How can i redirect to 'mydomain:port/anotherModule' with $location or $http ?
With this code in nodejs :
app.get('/secondModule', expressJwt({secret: config.secureToken}), function (req, res) {
res.render('restricted/secondModule/index.html');
});
NodeJs sends an html code in response and does'nt redirect...
And if i do this in my angular controller :
location.href = route;
i have this result on nodejs console :
Error: No Authorization header was found
I am not sure about the libraries you are using, but issue seems that you are loosing the token because you navigate to a altogether new page.
Based on your auth library you need to pass the token that you get after auth from one page to another.
The options here are to either use browser sessionStorage or querystring to pass the token along and at it back to the http header collection on the new page (module)
This is an old post but I recently took a long time to figure this out. I may be wrong but I believe nodeJS/expressJS can't read the token from the session storage. I believe you will need to pass the token via the request header using AngularJS.
This depends on the front end that you are using. For me, I am using AngularJS and I have to do something like this.
angular.module('AngularApp').factory('authFactory',
function($window){ //the window object will be able to access the token
var auth = {};
auth.saveToken = function(token){
$window.localStorage['token_name'] = token; //saving the token
}
auth.getToken = function(){
return $window.localStorage['token_name']; //retrieving the token
}
return auth;
}
.service('authInterceptor, function(authFactory){
return { headers: {Authorization: 'Bearer "+ authFactory.getToken()}
} //the last line gets the retrieved token and put it in req.header
Then, you just need to include 'authInterceptor' in all the http methods when you communicate with the backend. This way, nodeJS will be able to pick up the token.
You can see the Authorization field in req.header if you use the chrome developer tool and look at the Network tab. Hope this helps.

Resources