So I have a react app with nextjs where I'd need to get an event trigger when the user uses the Phantom wallet extension and switches accounts. I cannot find anything relevant on their docs: https://docs.phantom.app/
I was wondering if anyone encounter this issue. Basically I have the window.solana object but it does not have a trigger for when the user siwtches accounts
So Phantom itself does not expose any account switching specific API on their window.solana object.
There are some tricks you can do to find out when the account switches though.
You can continuously poll for the currently connected account and set the publicKey to some variable. When the publicKey changes, you can trigger your event.
Example psuedocode:
let currentKey = '';
poll(() => {
if (/* wallet available and connected */) {
await /* Action that updates publicKey */
if (currentKey !== wallet.publicKey.toBase58()) {
currentKey = wallet.publicKey.toBase58();
this.publicKey = wallet.publicKey;
this.emit('change')
}
}
})
You can find a writeup and PR we currently have on wallet-adapter going over this flow here
Phantom now emits accountChanged event: https://docs.phantom.app/integrating/extension-and-in-app-browser-web-apps/establishing-a-connection#changing-accounts
I has this error when trying to loginRedirect in React app using #azure/msal-react#1.0.0-alpha.6 and #azure/msal-browser#2.11.2. The login data returns correctly but the exception is raised in the console.
Uncaught (in promise) BrowserAuthError: interaction_in_progress:
Interaction is currently in progress. Please ensure that this
interaction has been completed before calling an interactive API.
import * as msal from "#azure/msal-browser";
const msalConfig = {
auth: {
clientId: '995e81d0-',
authority: 'https://login.microsoftonline.com/3a0cf09b-',
redirectUri: 'http://localhost:3000/callback'
},
cache: {
cacheLocation: "sessionStorage", // This configures where your cache will be stored
storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
}
};
const msalInstance = new msal.PublicClientApplication(msalConfig);
try {
msalInstance.handleRedirectPromise()
.then(res=>{
console.log(res)
})
.catch(err => {
console.error(err);
});
var loginRequest = {
scopes: ["api://58ca819e-/access_as_user"] // optional Array<string>
};
msalInstance.loginRedirect(loginRequest);
} catch (err) {
// handle error
console.log(err)
}
The exception
Uncaught (in promise) BrowserAuthError: interaction_in_progress: Interaction is currently in progress. Please ensure that this interaction has been completed before calling an interactive API.
at BrowserAuthError.AuthError [as constructor] (http://localhost:3000/static/js/vendors~main.chunk.js:852:20)
at new BrowserAuthError (http://localhost:3000/static/js/vendors~main.chunk.js:8943:24)
at Function.BrowserAuthError.createInteractionInProgressError (http://localhost:3000/static/js/vendors~main.chunk.js:9023:12)
at PublicClientApplication.ClientApplication.preflightInteractiveRequest (http://localhost:3000/static/js/vendors~main.chunk.js:13430:30)
at PublicClientApplication.<anonymous> (http://localhost:3000/static/js/vendors~main.chunk.js:12581:33)
at step (http://localhost:3000/static/js/vendors~main.chunk.js:215:17)
at Object.next (http://localhost:3000/static/js/vendors~main.chunk.js:146:14)
at http://localhost:3000/static/js/vendors~main.chunk.js:118:67
at new Promise (<anonymous>)
at __awaiter (http://localhost:3000/static/js/vendors~main.chunk.js:97:10)
at PublicClientApplication.ClientApplication.acquireTokenRedirect (http://localhost:3000/static/js/vendors~main.chunk.js:12565:12)
at PublicClientApplication.<anonymous> (http://localhost:3000/static/js/vendors~main.chunk.js:13760:16)
at step (http://localhost:3000/static/js/vendors~main.chunk.js:215:17)
at Object.next (http://localhost:3000/static/js/vendors~main.chunk.js:146:14)
at http://localhost:3000/static/js/vendors~main.chunk.js:118:67
at new Promise (<anonymous>)
at __awaiter (http://localhost:3000/static/js/vendors~main.chunk.js:97:10)
at PublicClientApplication.loginRedirect (http://localhost:3000/static/js/vendors~main.chunk.js:13755:12)
at Module.<anonymous> (http://localhost:3000/static/js/main.chunk.js:192:16)
at Module../src/App.tsx (http://localhost:3000/static/js/main.chunk.js:292:30)
at __webpack_require__ (http://localhost:3000/static/js/bundle.js:857:31)
at fn (http://localhost:3000/static/js/bundle.js:151:20)
at Module.<anonymous> (http://localhost:3000/static/js/main.chunk.js:2925:62)
at Module../src/index.tsx (http://localhost:3000/static/js/main.chunk.js:3028:30)
at __webpack_require__ (http://localhost:3000/static/js/bundle.js:857:31)
at fn (http://localhost:3000/static/js/bundle.js:151:20)
at Object.1 (http://localhost:3000/static/js/main.chunk.js:3570:18)
at __webpack_require__ (http://localhost:3000/static/js/bundle.js:857:31)
at checkDeferredModules (http://localhost:3000/static/js/bundle.js:46:23)
at Array.webpackJsonpCallback [as push] (http://localhost:3000/static/js/bundle.js:33:19)
at http://localhost:3000/static/js/main.chunk.js:1:67
msalInstance.loginRedirect(loginRequest);
The piece of code above does next:
Looks into session storage for key msal.[clientId].interaction.status and other temp values required for redirection process. If such key exist and its value equals 'interaction_in_progress' error will be thrown.
Creates entry in session storage msal.[clientId].interaction.status = interaction.status
Redirects user to auth-page.
In case of successful login user will be redirected to initial page with your code and go through 1-3 steps and will catch an error;
The piece of code below removes all temp values in session storage and completes auth redirection flow but it is async and never will be completed.
msalInstance.handleRedirectPromise()
.then(res=>{
console.log(res)
})
.catch(err => {
console.error(err);
});
The solution will be
// Account selection logic is app dependent. Adjust as needed for different use cases.
// Set active acccount on page load
const accounts = msalInstance.getAllAccounts();
if (accounts.length > 0) {
msalInstance.setActiveAccount(accounts[0]);
}
msalInstance.addEventCallback((event) => {
// set active account after redirect
if (event.eventType === EventType.LOGIN_SUCCESS && event.payload.account) {
const account = event.payload.account;
msalInstance.setActiveAccount(account);
}
}, error=>{
console.log('error', error);
});
console.log('get active account', msalInstance.getActiveAccount());
// handle auth redired/do all initial setup for msal
msalInstance.handleRedirectPromise().then(authResult=>{
// Check if user signed in
const account = msalInstance.getActiveAccount();
if(!account){
// redirect anonymous user to login page
msalInstance.loginRedirect();
}
}).catch(err=>{
// TODO: Handle errors
console.log(err);
});
I believe this is the correct answer and way to set this up. Others here led me to clues to solve this.
TLDR; set your code up like this:
// authRedir.ts (or authRedir.vue inside mounted())
await msalInstance.handleRedirectPromise();
// mySignInPage.ts (or userprofile.vue, or whatever page invokes a sign-in)
await msalInstance.handleRedirectPromise();
async signIn(){
const loginRequest: msal.RedirectRequest = {
scopes: ["openid", "profile", "offline_access","your_other_scopes"]
redirectUri: "http://localhost:8080/authredirect"
};
const accounts = msalInstance.getAllAccounts();
if (accounts.length === 0) {
await msalInstance.loginRedirect();
}
}
If you do this correctly, you wont need the code #shevchenko-vladislav shared, wherein setActiveAccount() has to be manually done by you. Remember to verify all async/await wherever you call this in your app! And notice how I did NOT use handleRedirectPromise().then() or anything, really, in my main authredirect.vue file. Just handleRedirectPromise() on load.
Other solutions on Stackoverflow suggest things like checking for and deleting the interaction state from the session. Um, no! If you have that state left over after a sign-in, it means the process wasn't done right! MSAL cleans itself up!
Full details:
It is super important to understand what MSAL is actually doing during it's entire lifecycle (especially the redir path as opposed to popup), and sadly the docs fail to do a good job. I found this little "side note" extremely, extremely important:
https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/errors.md#interaction_in_progress
"If you are calling loginRedirect or acquireTokenRedirect from a page
that is not your redirectUri you will need to ensure
handleRedirectPromise is called and awaited on both the redirectUri
page as well as the page that you initiated the redirect from. This is
because the redirectUri page will initiate a redirect back to the page
that originally invoked loginRedirect and that page will process the
token response."
In other words, BOTH your Redirect page AND the page that INVOKED the sign-in request MUST call handleRedirectPromise() on page load (or on mounted(), in my case, since I am using Vue)
In my case, I have this:
http://localhost:8080/authredirect *
http://localhost:8080/userprofile
*Only my AuthRedirect Uri needs to be registered as a RedirectUri with my app registration in Azure AD.
So here is the loginRedirect() lifecycle, which I had NO idea, and lost a days work sorting out:
/UserProfile (or some page) invokes a sign-in request
The request calls handleRedirectPromise() (which sets MSAL up with info about where the request was made AND the interaction state that will bite you later if you dont complete the process)
and THEN calls loginRedirect(loginRequest)
-> user is redirected, completes sign-in
Azure redir back to -> /AuthRedirect
/AuthRedirect invokes handleRedirectPromise(), which forwards along to -> /UserProfile
/UserProfile invokes handleRedirectPromise() which does the actual processing of tokens AND internally calls setActiveAccount() to save your user to session.
Dang. That was fun. And not explained in the docs AT ALL.
So, the reason you are getting the interaction-in-progress error is because you are thinking you're all done on step 6. NOPE! Step 7 is where that interaction_in_progress state gets settled and cleaned up so that subsequent calls wont trip up on it!!
Final thought:
If you have a designated sign-in page you want users to always start/finish from (and itself is the registered redirect Uri), I suppose these steps will be reduced (no forwarding like in step 6 here). In my case, I want the user redirected back to wherever they might have gotten bumped out of due to a session expiration. So I just found it easier to call handleRedirectPromise() on every single page load everywhere, in case said page it needs to finalize authentication. Or, I could build my own redirect logic into a dedicated sign-in page that can put the user back where they were prior to hitting it. It's just that as for MSAL, I had NO idea the process was finishing up on the requesting page rather than contained within my AuthRedirect page, and THAT is what bit me.
Now, if we could just get MS to provide far better docs on the delicate and critical nature of MSAL, and to provide a Vue plugin (why does only Angular and React get all the glory? :) ), that would be great!
During development, it is possible that you left the sign-in flow in a progress-state due to a coding issue that you will need to correct. You can clear the immediate problem by deleting the msal.interaction.status cookie from the browser. Of course, if this problem persists, then you need to correct the problem using one of the other solutions suggested on this page.
You can clear the browser storage before open the loginPopup:
let msalInstance: PublicClientApplication = this._msauthService.instance as PublicClientApplication;
msalInstance["browserStorage"].clear();
I have found that in msal.js v2 you can check interaction status in vanilla .js code to see if there is an interaction in progress, should you need to do this for some reason:
const publicClientApplication = new window.msal.PublicClientApplication(msalConfig);
var clientString = "msal." + msalConfig.clientId + ".interaction.status";
var interaction-status = publicClientApplication.browserStorage.temporaryCacheStorage.windowStorage[clientString]
Update #azure/msal-browser#2.21.0.
For folks with an Azure/Active Directory situation:
My issue wasn't with my code. It was with deactivating the "Access tokens (used for implicit flows)" setting found in the Active Directory > Authentication > Implicit grant and hybrid flows section.
After you put the proper Redirect URIs into the Web section:
ex: https://example.com/.auth/login/aad/callback
And after you put the proper Redirect URIs into the Single-page application section:
ex: https://example.com
ex: https://localhost:4200
The last step is to make sure you disable the Access tokens I mentioned in the beginning:
When I was migrating my apps from .NET5 to .NET6 and the prior Angular Authentication over to MSAL, this setting was already checked for me (both were checked). After unchecking this setting, everything ended up working.
This may not be a clean solution. But this does work at least in Vue.js.
Next to your acquireToken() logic, add this
// Check Local or Session storage which may have already contain key
// that partially matches your Azure AD Client ID
let haveKeys = Object.keys(localStorage).toString().includes('clientId')
// That error will just go away when you refrest just once
let justOnce = localStorage.getItem("justOnce");
if (haveKeys && !justOnce) {
localStorage.setItem("justOnce", "true");
window.location.reload();
} else {
localStorage.removeItem("justOnce")
}
I have faced the similar error in my project.I took reference of the below link. It takes hardly 10 minutes to go through it. It will surely resolve if you face the scenarios given in it.
Link:
https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-angular/docs/v2-docs/redirects.md
I'm trying to use web sockets to add a new notification to my app. I'm using Backand as my server, and can't seem to get a grasp on responding to the new event. Here's my server side code to send the event:
//Action: Update - After data saved and committed
function backandCallback(userInput, dbRow, parameters, userProfile) {
//Send to array of users
socket.emitUsers("new_notification",userInput, ["admins"]);
return {};
}
And my client code to receive it:
//Wait for server updates on 'items' object
Backand.on('new_notification', function (data) {
//Get the 'items' object that have changed
console.log(data);
});
But when I try to receive the event in my app code, I never see a notification of type "new_notification". Can someone please let me know what's going on?
Make sure you are using emitRole instead of emitUsers. The code above emits to a user array, but it looks like you want to send a notification to the "admins" role. Change this to emitRole() and you should be ok.
For role you want to keep it case sensitive so it will be:
socket.emitRole("items_updated",userInput, "Admin");
For users the syntax is:
socket.emitUsers("items_updated",userInput, ["user2#gmail.com","user1#gmail.com"]);
I am using the $firebaseAuth.$createUser() method to register a user to my firebase backend, I then immediately try to create a /profile/ for the user. In 'profile' security rules I have rule that only the current user can create/edit their profile.
"profile": {
".read": true,
"$profileId":{
".write": "auth.uid == $profileId"
}
}
However it appears because I do this right after I call $createUser() using the then() chainining method that the auth variable isn't correct when the security rules process. Do I need to call an auth() method or something after I call $createUser() ??
Ok, after digging through the documentation, I found that $createUser() does NOT authenticate the user. Once the account is created, the user may be authenticated with the authWithPassword() function.
Is there a way to bind an auth error message to the scope condition of the auth component?
For instance say I have:
'Auth' => array('authenticate' => array('Blowfish' => array('scope' => array('User.activated' => 1))));
I would like set an error if the scope condition fails. I need to be able to differentiate that from the error that is presented if the user/pass is incorrect.
Is this possible?
Right, I've had a root around CakePHP's source code and I've come to the conclusion that it doesn't do anything fancy when using scoped conditions, it simply appends them as additional query conditions. It will either find the user which matches the username/password combination and any scope conditions, or it doesn't.
One possible solution would be to manually log users in and check for the activated field like so:
public function login()
{
if ($this->request->is('post')) {
if ($this->Auth->login($this->data['User'])) {
// check activated field
if ($this->Auth->user('activated') == 1) {
// user is activated
$this->redirect(...);
} else {
// user is not activated
// log the user out
$this->Auth->logout();
// redirect to an error page for inactive users
$this->redirect(..);
}
}
// redirect to an error page for wrong username/password
$this->redirect(..);
}
}
I should clarify that you should not specify scope conditions in configuring the authentication component.
I hope this helps!