Ever wanted to do something after a user logs in or logs out of your Blazor App?
Surprisingly, it fairly simple to do.
In VS Code I created a Blazor WebAssembly project that uses Azure ADB2C for authentication.
1 |
dotnet new blazorwasm -au IndividualB2C --aad-b2c-instance "{AAD B2C INSTANCE}" --client-id "{CLIENT ID}" --domain "{TENANT DOMAIN}" -ssp "{SIGN UP OR SIGN IN POLICY}" -o "{FOLDER_NAME}" |
Once scaffolded, I navigated to the Authenticate.razor
page in the Pages
folder.
The RemoteAuthenticatorView
component supports two events that you can wire up a callback to, OnLogInSucceeded
and OnLogOutSucceeded
.
I just created two methods OnLogInSucceeded
and OnLogOutSucceeded
and wired them up to the appropriate events in the RemoteAuthenticatorView
.
Now when the user logs in I can get additional profile data from my database and/or add a new user to my database, or if the user logs out I can clear the cache.
That’s it!
Pretty easy and pretty powerful!
Discover more from Matt Ruma
Subscribe to get the latest posts sent to your email.
Thanks for this. Solved my puzzle in one google search 😉
Awesome! Glad to help!
Ditto – saved me some time! Thanks!
What should be the value of Action?
The action is provided by the Blazor App, the only thing you should have to worry about is responding to the events.
Hi Matt. I used your example in my Blazor Client App but OnLogInSucceeded is called only once after first login attempt. Is it a right behaviour or am I doing something wrong?
If I remember correctly, it does only get called once.
Hi thanks. One problem (: When I hook up any events in my login flow It looks like I authentication 3 times more and I also got extra redirections
That’s interesting, I have not encountered that problem. Does it eventually login? Wonder if there is an issue with the token being issued?
Yes I get logged in
Interesting … I am NOW (first time I wrote this I had not) seeing the same behavior in a new Blazor App I started.
I opened GitHub issue about this, see https://github.com/dotnet/aspnetcore/issues/29235.
Thanks for opening the issue Matt. I am also seeing the extra calls on the authorization.razor login successful action.
Was this ever solved?
Awesome, just what I was looking after as I wanted to improve the user experience over showing the text: “You are logged out.”
How can I log on the server side when a user logs in successfully. I tried with the Login.cshtml page but it only shows some entries. Looks like when the user logs in again, the page is not called.
Great work, this saved my job