[英]How to run code on login in Blazor WebAssembly?
I'm trying to run a function every time a user logs in. What I tried is to obtain an instance of AuthenticationStateProvider
from the DI container and subscribe to its AuthenticationStateChanged
event.每次用户登录时,我都尝试运行 function。我尝试的是从 DI 容器获取AuthenticationStateProvider
的实例并订阅其AuthenticationStateChanged
事件。 The problem is that my login pages are implemented using server-rendered Razor Pages so the page refreshes after a successful login.问题是我的登录页面是使用服务器渲染的 Razor 页面实现的,因此成功登录后页面会刷新。 This means that my code subscribes to the event after it is fired, so my handler function never runs.这意味着我的代码在事件触发后订阅了该事件,因此我的处理程序 function 永远不会运行。 Can anybody see a way to run custom code upon successful login?任何人都可以看到成功登录后运行自定义代码的方法吗?
If you're using the token based authentication (API), you can attach an event handler to the RemoteAuthenticatorView component located in the Authentication component.如果您使用基于令牌的身份验证 (API),则可以将事件处理程序附加到位于 Authentication 组件中的 RemoteAuthenticatorView 组件。 I think it has an event that is invoked immediately after a user log in. As far as I recall, I've once answered a similar question that way, and then changed my answer to something more useful.我认为它有一个在用户登录后立即调用的事件。据我记得,我曾经以这种方式回答过一个类似的问题,然后将我的答案更改为更有用的东西。 Try this solution, and let us know if it's OK.试试这个解决方案,让我们知道它是否可以。
You can inject the AuthorizationService
into your component and then await the AuthenticationState
to run code if your user is logged in. Further details are in the documentation here .如果您的用户已登录,您可以将AuthorizationService
注入到您的组件中,然后等待AuthenticationState
运行代码。更多详细信息在此处的文档中。
@using Microsoft.AspNetCore.Authorization
@inject IAuthorizationService AuthorizationService
<button @onclick="@DoSomething">Do something important</button>
@code {
[CascadingParameter]
private Task<AuthenticationState> authenticationStateTask { get; set; }
private async Task DoSomething()
{
var user = (await authenticationStateTask).User;
if (user.Identity.IsAuthenticated)
{
// Perform an action only available to authenticated (signed-in) users.
}
}
}
Instead of an onclick handler you can put the auth check in a component's initializedasync method or wherever else is appropriate.代替 onclick 处理程序,您可以将身份验证检查放入组件的初始化异步方法或其他任何合适的地方。
Another approach is to hook into the OnLoginSucceeded
property of the RemoteAuthenticatorView
, like:另一种方法是挂钩到RemoteAuthenticatorView
的OnLoginSucceeded
属性,例如:
<RemoteAuthenticatorView Action="@Action" OnLogInSucceeded="OnLoginSucceeded" />
@code{
[Parameter] public string Action { get; set; }
private void OnLoginSucceeded()
{
// do your stuff here
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.