Google api revoke token issue - authentication

I've created an application using google drive API to list and manage all my drive files.
Everything goes fine, except the log out part. I've searched for two days for a solution without a result.
The following is code related to login and works fine:
function checkAuth() {
gapi.auth.authorize(
{
'client_id': CLIENT_ID,
'scope': SCOPES.join(' '),
'immediate': true,
'authuser': '-1'
}, handleAuthResult);
}
function handleAuthResult(authResult) {
var authorizeDiv = document.getElementById('authorize-div');
if (authResult && !authResult.error) {
// Hide auth UI, then load client library.
authorizeDiv.style.display = 'none';
loadDriveApi();
} else {
authorizeDiv.style.display = 'inline';
}
}
function handleAuthClick(event) {
gapi.auth.authorize(
{client_id: CLIENT_ID, scope: SCOPES, immediate: false},
handleAuthResult);
return false;
}
function loadDriveApi() {
gapi.client.load('drive', 'v2', listFiles);
}
I'm able to login and work with files, but when I try to logout with following I get No 'Access-Control-Allow-Origin' error
$(document).on('click', '.logout', function(){
var token = gapi.auth.getToken();
if (token) {
var accessToken = gapi.auth.getToken().access_token;
if (accessToken) {
var revokeToken = 'https://accounts.google.com/o/oauth2/revoke?token=' + accessToken;
jQuery.getJSON(revokeToken).success(function(data) {
console.log(data);
}).error(function(message) {
console.error('error' + message);
}).complete(function() {
console.log('completed!');
});
}
}
gapi.auth.setToken(null);
gapi.auth.signOut();
});
In Google Developers Console I've regitred my website to Authorized JavaScript origins.
Thanks

Related

SvelteKit + Hooks and MSAL.js using Azure AD B2C results in non_browser_environment

I am new to SvelteKit and i am trying to use MSAL.js with SvelteKit, the issue is i want to implement something similar to an AuthGuard/HttpInterceptor which checks to see if the user is still logged in as they navigate around the SPA or call the external API.
I am using the OAuth 2.0 authorization code flow in Azure Active Directory B2C
within in my auth.ts file i have the following code
let accountId: string = "";
const signIn = () => {
try {
msalInstance.loginRedirect(loginRequestWithApiReadWrite);
} catch (error) {
isAuthenticated.set(false);
console.warn(error);
}
}
// This captures the response from using the redirect flow to login
await msalInstance.handleRedirectPromise()
.then(response => {
if (response) {
if (response.idTokenClaims['tfp'].toUpperCase() === b2cPolicies.names.signUpSignIn.toUpperCase()) {
handleResponse(response);
}
}
})
.catch(error => {
console.log(error);
});
async function handleResponse(response: msal.AuthenticationResult) {
if (response !== null) {
user.set(response);
isAuthenticated.set(true);
setAccount(response.account);
} else {
selectAccount();
}
}
function selectAccount() {
const currentAccounts = msalInstance.getAllAccounts();
if (currentAccounts.length < 1) {
return;
} else if (currentAccounts.length > 1) {
const accounts = currentAccounts.filter(account =>
account.homeAccountId.toUpperCase().includes(b2cPolicies.names.signUpSignIn.toUpperCase())
&&
account.idTokenClaims?.iss?.toUpperCase().includes(b2cPolicies.authorityDomain.toUpperCase())
&&
account.idTokenClaims.aud === msalConfig.auth.clientId
);
if (accounts.length > 1) {
if (accounts.every(account => account.localAccountId === accounts[0].localAccountId)) { console.log("Multiple accounts belonging to the user detected. Selecting the first one.");
setAccount(accounts[0]);
} else {
console.log("Multiple users accounts detected. Logout all to be safe.");
signOut();
};
} else if (accounts.length === 1) {
setAccount(accounts[0]);
}
} else if (currentAccounts.length === 1) {
setAccount(currentAccounts[0]);
}
}
// in case of page refresh
selectAccount();
function setAccount(account: msal.AccountInfo | null) {
if (account) {
accountId = account.homeAccountId;
}
}
const authMethods = {
signIn,
getTokenRedirect
}
In a +page.svelte file i can then import the authMethods no problem, MSAL redirects me to the microsoft sign in page, i get redirected back and can then request an access token and call external API, great all is well.
<script lang='ts'>
import authMethods from '$lib/azure/auth';
<script>
<button on:click={authMethods.signIn}>Sign In</button>
However, the issue i am having is trying to implement this so i can check to see if the user is logged in against Azure B2C using a hook.server.ts file automatically. I would like to check a variable to see if the user is authenticated and if they arnt the hooks.server will redirect them to signUp by calling the authMethod within the hook, and the user will be automatically redirected to the sign in page.
In the hooks.server.ts i have the following code:
export const handle: Handle = (async ({ event, resolve }) => {
if (isAuthenticated === false) {
authRedirect.signIn();
msalInstance.handleRedirectPromise().then((response) => {
if (response) {
console.log('login with redirect succeeded: ', response)
isAuthenticated = true;
}
}).catch((error) => {
console.log('login with redirect failed: ', error)
})
}
const response = await resolve(event);
return response;
}) satisfies Handle;
When i navigate around the SvelteKit SPA, MSAL.js keeps throwing the error below, which i know is because i am running the code from the server flow rather than in the browser, so it was my understanding that if i implement the handleRedirectPromise() in both the auth.ts file and hooks.server.ts this would await the response from the signIn event and so long as i got a response i can then set isAuthenticated to true.
errorCode: 'non_browser_environment',
errorMessage: 'Login and token requests are not supported in non-browser environments.',
subError: ''
Are you required to use the MSAL library? I have got it working with https://authjs.dev/. I was using Active Directory -https://authjs.dev/reference/oauth-providers/azure-ad but there is also a flow for B2C https://authjs.dev/reference/oauth-providers/azure-ad-b2c which I haven't tried.
Then in the hooks.server.js you can do something like the below.
import { sequence } from '#sveltejs/kit/hooks';
import { redirect } from '#sveltejs/kit';
import { SvelteKitAuth } from '#auth/sveltekit';
import AzureADProvider from '#auth/core/providers/azure-ad';
import {
AZURE_AD_CLIENT_ID,
AZURE_AD_CLIENT_SECRET,
AZURE_AD_TENANT_ID
} from '$env/static/private'
const handleAuth = SvelteKitAuth({
providers: [
AzureADProvider({
clientId: AZURE_AD_CLIENT_ID,
clientSecret: AZURE_AD_CLIENT_SECRET,
tenantId: AZURE_AD_TENANT_ID
})
]
});
async function isAuthenticatedUser({ event, resolve }) {
const session = await event.locals.getSession();
if (!session?.user && event.url.pathname !== '/') {
throw redirect(302, '/');
} else if (session?.user && event.url.pathname === '/') {
throw redirect(302, '/dashboard');
}
const response = await resolve(event);
return response;
}
export const handle = sequence(handleAuth, isAuthenticatedUser);

razor pages with firebase auth - where to put this token ? :)

i am working on web site with razor pages. part of the site should be accessed only by registred users. decided to go with firebase authentification (now with login and password ).
created everything necessary in firebase.
created backend code for user registration - works well.
created area which requires authorisation
services.AddRazorPages(options =>
{
options.Conventions.AuthorizeAreaFolder("User", "/");
})
added jwt middleware
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
added code to login page to call firebase to get token
function login()
{
firebase.auth().signInWithEmailAndPassword(email, password)
.then((userCredential) => {
// Signed in
var user = userCredential.user;
// ...
alert("signed");
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
alert(errorMessage);
});
}
got token from firebase.
if i'd call service next, i'd simply put token in "bearer" header.
tried to find how to add header to current browser for future requests and failed.
as i understand, i need this token to be added to auth header ? how ? :)
feeling dumb ;( tried to google, but most samples are for using this token later with api calls.
or i am going in the wrong direction?
tia
ish
well. it seems that it is not possible to add bearer from js, so i switched to cookies
in startup.cs use cookies
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
context.Token = context.Request.Cookies["bearer"];
return Task.CompletedTask;
}
};
code to login with firebase, put token into the cookie and redirect
function login() {
firebase.auth().signInWithEmailAndPassword(email, password)
.then((userCredential) => {
// Signed in
var user = userCredential.user;
firebase.auth().currentUser.getIdToken(true).then(function (idToken)
{
document.cookie = "bearer" + "=" + idToken;
window.location.href = "/user/index";
}).catch(function (error) {
// Handle error
});
alert("signed");
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
alert(errorMessage);
});
}
or the same with firebaseUI
function login1()
{
ui.start('#firebaseui-auth-container', {
signInSuccessUrl: '/User/index',
signInOptions: [
{
provider: firebase.auth.EmailAuthProvider.PROVIDER_ID,
requireDisplayName: false
}
],
callbacks:
{
signInSuccessWithAuthResult: function (authResult, redirectUrl)
{
var user = authResult.user;
firebase.auth().currentUser.getIdToken(true).then(function (idToken) {
document.cookie = "bearer" + "=" + idToken;
}).catch(function (error) {
// Handle error
});
return true;
}
}
});
}

Migrate ADAL.js to MSAL.js

I have a SPA which uses the solution provided here to authenticate with Azure AD and everything works as expected. Now I want to migrate this to use MSAL.js.
I use below for login:
import * as MSAL from 'msal'
...
const config = {
auth: {
tenantId: '<mytenant>.com',
clientId: '<myclientid>',
redirectUri: <redirecturi>,
},
cache: {
cacheLocation: 'localStorage',
}
};
const tokenRequest = {
scopes: ["User.Read"]
};
export default {
userAgentApplication: null,
/**
* #return {Promise}
*/
initialize() {
let redirectUri = config.auth.redirectUri;
// create UserAgentApplication instance
this.userAgentApplication = new MSAL.UserAgentApplication(
config.auth.clientId,
'',
() => {
// callback for login redirect
},
{
redirectUri
}
);
// return promise
return new Promise((resolve, reject) => {
if (this.userAgentApplication.isCallback(window.location.hash) || window.self !== window.top) {
// redirect to the location specified in the url params.
}
else {
// try pull the user out of local storage
let user = this.userAgentApplication.getUser();
if (user) {
resolve();
}
else {
// no user at all - go sign in.
this.signIn();
}
}
});
},
signIn() {
this.userAgentApplication.loginRedirect(tokenRequest.scopes);
},
And then I use below to get the token:
getCachedToken() {
var token = this.userAgentApplication.acquireTokenSilent(tokenRequest.scopes);
return token;
}
isAuthenticated() {
// getCachedToken will only return a valid, non-expired token.
var user = this.userAgentApplication.getUser();
if (user) {
// get token
this.getCachedToken()
.then(token => {
axios.defaults.headers.common["Authorization"] = "Bearer " + token;
// get current user email
axios
.get('<azureapi-endpoint>' + '/GetCurrentUserEmail')
.then(response => { })
.catch(err => { })
.finally(() => {
});
})
.catch(err => { })
.finally(() => { });
return true;
}
else {
return false;
}
},
}
but after login I get below error:
Access to XMLHttpRequest at 'https://login.windows.net/common/oauth2/authorize?response_type=code+id_token&redirect_uri=<encoded-stuff>' (redirected from '<my-azure-api-endpoint>') from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Also the token that I get seems to be invalid as I get 401 errors trying to call api using the token. Upon checking the token against https://jwt.io/ I get an invalid signature.
I really appreciate anyone's input as I've already spent good few days and haven't got anywhere yet.
I'm not sure if this is your issue. however, for msal.js, in the config, there is no tenantId parameter, it's supposed to be authority. Here is a sample for graph api using msal.js
https://github.com/Azure-Samples/active-directory-javascript-graphapi-v2
specifically: the config is here: https://github.com/Azure-Samples/active-directory-javascript-graphapi-v2/blob/quickstart/JavaScriptSPA/authConfig.js
as per here, https://learn.microsoft.com/en-us/azure/active-directory/develop/msal-js-initializing-client-applications it is supposed to be hitting login.microsoftonline.com not login.windows.net

Twitter OAuth Ionic 2

Its possible generate a Twitter token and secret token in Nodejs and after use it to open the browser for authenticate with "https://api.twitter.com/oauth/authenticate"?
I use this way to get the token:
app.get('/auth/twitter/token', function (req, res) {
var requestTokenUrl = 'https://api.twitter.com/oauth/request_token';
var requestTokenOauth = {
consumer_key: "2z8MTR8KAZuFafPHsEQ0ZBgo1",
consumer_secret: "ksPiaQz7ihCrOh3m4iRCsXZzQuSkkmcv4CLGiJQwREWeaQl7St"
};
request.post({
url: requestTokenUrl,
oauth: requestTokenOauth
}, function (err, response, body) {
var oauthToken = qs.parse(body);
res.send(oauthToken);
});
});
When I get this token in the client "https://api.twitter.com/oauth/authenticate?oauth_token=TOKEN" I got this problem: "This page is no longer valid. It's looks like someone already used the token information your provider, blabla.."
The problem is due to the way that I get the Token?
I'm using ng2-cordova-auth but this lib dont have twitter auth, I'm just trying to implement
This is my implementation:
"use strict";
var utility_1 = require("../utility");
var PROVIDER_NAME = "Twitter";
var Twitter = (function () {
function Twitter(options) {
this.twitterOptions = options;
this.flowUrl = ""
}
Twitter.prototype.login = function (token, tokenSecret) {
var _this = this;
return new Promise(function (resolve, reject) {
_ this.flowUrl = "https://api.twitter.com/oauth/authenticate?oauth_token="+token;
var browserRef = window.cordova.InAppBrowser.open(_this.flowUrl);
browserRef.addEventListener("loadstart", function (event) {
if ((event.url).indexOf(_this.twitterOptions.redirectUri) === 0) {
browserRef.removeEventListener("exit", function (event) { });
browserRef.close();
var parsedResponse = event.url.split("?")[1].split("&");
if (parsedResponse) {
resolve(parsedResponse);
}
else {
reject("Problem authenticating with " + PROVIDER_NAME);
}
}
});
browserRef.addEventListener("exit", function (event) {
reject("The " + PROVIDER_NAME + " sign in flow was canceled");
});
});
};
return Twitter;
}());
exports.Twitter = Twitter;
In my component/controller I make this:
//With twitterToken I get the token from NodeJs
this.API.twitterToken().subscribe(
data => {
this.twitterOAuth.login(data.oauth_token, data.oauth_token_secret).then((success) => {
alert(JSON.stringify(success))
}, (error) => {
alert(JSON.stringify(error));
});
},
err => alert(JSON.stringify(err))
);
Have you tried the Twitter Connect plugin? Does this help?
Plugin to use Twitter Single Sign On Uses Twitter's Fabric SDK
An example of use is
import {TwitterConnect} from 'ionic-native';
function onSuccess(response) {
console.log(response);
// Will console log something like:
// {
// userName: 'myuser',
// userId: '12358102',
// secret: 'tokenSecret'
// token: 'accessTokenHere'
// }
}
TwitterConnect.login().then(onSuccess, onError);

Anonymous meeting join - Skype UCWA for online

I am trying to join a meeting anonymously through a meeting URI and this does not seem to work. I went to the SKYPE UCWA site and went to the interactive SDK - and tried to join a meeting anonymously from there but the page does not do anything.
https://ucwa.skype.com/websdk
Below is the code that I am trying to join a meeting anonymously, but the call to client.signInManager.signIn never completes and neither any exception is thrown.
Looking for suggestions to resolve this issue. Also, if someone has working code of joining a meeting anonymously using SKYPE web sdk (UCWA), please share the same. Thanks.
function InitialiseSkype() {
Skype.initialize({ apiKey: config.apiKey }, function (api) {
window.skypeWebAppCtor = api.application;
window.skypeWebApp = new api.application();
client = new window.skypeWebAppCtor;
//once intialised, sign in
alert("Skype SDK Initialized");
JoinAnonymous();
}, function (err) {
console.log(err);
alert('Cannot load the SDK.');
});
}
function JoinAnonymous(){
client.signInManager.signIn({
version: config.Version,
name: $('#name').val(),
meeting: $('#meetingUri').val()
}).then(function () {
alert('Signed In, Anonymously');
var conversation = application.conversationsManager.getConversationByUri(uri);
}, function (error) {
alert(error);
});
}
Actually I did sign in anonymously using that code :
//Init
var config = {apiKey: 'a42fcebd-5b43-4b89-a065-74450fb91255', // SDK
apiKeyCC: '9c967f6b-a846-4df2-b43d-5167e47d81e1' // SDK+UI
};
Skype.initialize({ apiKey: config.apiKey }, function (api) {
window.skypeWebApp = new api.application;
}, function (err) {
console.log("cannot load the sdk package", err);
});
//Actual code
var uri ="sip:xxxxxxxx;gruu;opaque=app:conf:focus:id:xxxxxxxx";
window.skypeWebApp.signInManager.signIn({
name: "pseudo",
meeting:uri
}).then(function () {
alert('Signed In, Anonymously');
}, function (error) {
alert(error);
});
I did connect with the uri given in the ucwa.skype interactive web sdk page.
But I did not manage to join the conversation after that, probably because the interactive sample does not really create the room.
I can join a meeting from a office365 account while logged in with a sample account. However I can not join anonymously my meeting room.
Do you try with an on-premise account or with a office365 account ?
Looks like Anonymous join for a meeting is not yet available for Skype For Business online.
New update of WebSDK now support anonymous meeting join for SfB Online
(function () {
'use strict';
// this will be populated when the auth token is fetched
// it is later needed to sign into Skype for Business
var authDetails = {};
// A reference to the Skype SDK application object
// set during initialization
var app;
displayStep(0);
registerUIListeners();
// Initializing the Skype application
Skype.initialize({
apiKey: '9c967f6b-a846-4df2-b43d-5167e47d81e1'
}, function (api) {
console.log('Skype SDK initialization successful');
app = api.UIApplicationInstance;
// Once it is initialized, display a UI prompt for a meeting URL
displayStep(1);
}, function (err) {
console.error('Skype SDK initialization error:', err);
});
// After the user submits the meeting URL the next step is to
// fetch an auth token
function getToken(evt) {
var input = evt.target.querySelector('input'),
meetingUrl = input.value,
request = new XMLHttpRequest(),
data;
evt.preventDefault();
console.log('Fetching auth token from meeting url:', meetingUrl);
function guid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
var sessionId = guid();
data = 'ApplicationSessionId=' + sessionId +
'&AllowedOrigins=' + encodeURIComponent(window.location.href) +
'&MeetingUrl=' + encodeURIComponent(meetingUrl);
request.onreadystatechange = function () {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status === 200) {
var response = JSON.parse(request.response);
authDetails.discoverUrl = response.DiscoverUri;
authDetails.authToken = "Bearer " + response.Token;
console.log('Successfully fetched the anonymous auth token and discoverUrl', authDetails);
displayStep(2);
}
else {
console.error('An error occured, fetching the anonymous auth token', request.responseText);
}
}
};
request.open('post', 'http://webrtctest.cloudapp.net/getAnonTokenJob');
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);
}
// This uses the auth token and discovery URL to sign into Skype
// and join the meeting
function joinAVMeeting(evt) {
var input = evt.target.querySelector('input'),
name = input.value;
evt.preventDefault();
console.log('Joinig meeting as:', name);
app.signInManager.signIn({
name: name,
cors: true,
root: { user: authDetails.discoverUrl },
auth: function (req, send) {
// Send token with all requests except for the GET /discover
if (req.url != authDetails.discoverUrl)
req.headers['Authorization'] = authDetails.authToken;
return send(req);
}
}).then(function () {
// When joining a conference anonymously, the SDK automatically creates
// a conversation object to represent the conference being joined
var conversation = app.conversationsManager.conversations(0);
console.log('Successfully signed in with anonymous online meeting token');
registerAppListeners(conversation);
// This turns on local video and joins the meeting
startVideoService(conversation);
}).catch(function (error) {
console.error('Unable to join conference anonymously:', error);
});
function registerAppListeners(conversation) {
conversation.selfParticipant.video.state.when('Connected', function () {
console.log('Showing self video');
document.querySelector('.self').style.display = 'inline-block';
setupContainer(conversation.selfParticipant.video.channels(0), document.querySelector('.self .video'));
displayName(document.querySelector('.self'), conversation.selfParticipant);
console.log('The video mode of the application is:', conversation.videoService.videoMode());
if (conversation.videoService.videoMode() === 'MultiView') {
// Loading the sample in any other browser than Google Chrome means that
// the videoMode is set to 'MultiView'
// Please refer to https://msdn.microsoft.com/en-us/skype/websdk/docs/ptvideogroup
// on an example on how to implement group video.
}
// When in active speaker mode only one remote channel is available.
// To display videos of multiple remote parties the video in this one channel
// is switched out automatically, depending on who is currently speaking
if (conversation.videoService.videoMode() === 'ActiveSpeaker') {
var activeSpeaker = conversation.videoService.activeSpeaker;
setupContainer(activeSpeaker.channel, document.querySelector('.remote .video'));
activeSpeaker.channel.isVideoOn.when(true, function () {
document.querySelector('.remote').style.display = 'inline-block';
activeSpeaker.channel.isStarted(true);
console.log('ActiveSpeaker video is available and has been turned on.');
});
activeSpeaker.channel.isVideoOn.when(false, function () {
document.querySelector('.remote').style.display = 'none';
activeSpeaker.channel.isStarted(false);
console.log('ActiveSpeaker video is not available anymore and has been turned off.');
});
// the .participant object changes when the active speaker changes
activeSpeaker.participant.changed(function (newValue, reason, oldValue) {
console.log('The ActiveSpeaker has changed. Old ActiveSpeaker:', oldValue && oldValue.displayName(), 'New ActiveSpeaker:', newValue && newValue.displayName());
if (newValue) {
displayName(document.querySelector('.remote'), newValue);
}
});
}
});
conversation.state.changed(function (newValue, reason, oldValue) {
if (newValue === 'Disconnected' && (oldValue === 'Connected' || oldValue === 'Connecting')) {
console.log('The conversation has ended.');
reset();
}
});
}
function setupContainer(videoChannel, videoDiv) {
videoChannel.stream.source.sink.format('Stretch');
videoChannel.stream.source.sink.container(videoDiv);
}
function displayName(container, person) {
container.querySelector('.displayName .detail').innerHTML = person.displayName();
}
function startVideoService(conversation) {
conversation.videoService.start().then(null, function (error) {
console.error('An error occured joining the conversation:', error);
});
displayStep(3);
}
}
function endConversation(evt) {
var conversation = app.conversationsManager.conversations(0);
evt.preventDefault();
conversation.leave().then(function () {
console.log('The conversation has ended.');
reset();
}, function (error) {
console.error('An error occured ending the conversation:', error);
}).then(function () {
reset();
});
}
//-----------------------------------------------------------------------
//UI helper functions
function displayStep(step) {
var nodes = document.querySelectorAll('.step');
for (var i = 0; i < nodes.length; ++i) {
var node = nodes[i];
node.style.display = 'none';
if (i === step) {
node.style.display = 'block';
}
}
}
function registerUIListeners() {
document.querySelector('.step1').onsubmit = getToken;
document.querySelector('.step2').onsubmit = joinAVMeeting;
document.querySelector('.step3').onsubmit = endConversation;
}
function reset() {
window.location = window.location.href;
}
})();
https://github.com/OfficeDev/skype-docs/blob/master/Skype/WebSDK/samples/Meetings/Anonymous%20Online/standalone/index.js