关于如何在自定义类中的Blazor Server Side中访问AuthenticationStateProvider的任何一般指导? 是否应将AuthenticationStateProvider添加为单例服务? 还有其他方法可以通过DI获得它吗? 我不是在谈论使用AuthorizeViews或通过级联参数。 我需要能够在自定义类中而不是控制器,视图等中获取AuthenticationStateProvider.GetAuthenticationStateAsync()。
有什么想法吗?
关于如何在自定义类中的Blazor Server Side中访问AuthenticationStateProvider的任何一般指导? 是否应将AuthenticationStateProvider添加为单例服务? 还有其他方法可以通过DI获得它吗? 我不是在谈论使用AuthorizeViews或通过级联参数。 我需要能够在自定义类中而不是控制器,视图等中获取AuthenticationStateProvider.GetAuthenticationStateAsync()。
有什么想法吗?
以下是与WebAssembly Blazor App一起使用的自定义AuthenticationStateProvider,用于从localStorage读取Jwt令牌,将Jwt令牌写入本地存储,等等。这里最重要的部分是自定义AuthenticationStateProvider覆盖了GetAuthenticationStateAsync方法。
注意:WebAssembly Blazor中需要创建自定义AuthenticationStateProvider。 但是,不建议使用Blazor Server Apps这样做,在这种情况下,其创建要复杂得多,并且可能构成安全风险。 通常,您在服务器端Blazor中也不需要自定义AuthenticationStateProvider。
关于如何在自定义类中的Blazor Server Side中访问AuthenticationStateProvider的任何一般指导
如果您是说如何询问身份验证状态,那么答案是肯定的。 您可能会在文档中找到有关此示例。 一般来说,应该在组件和类中注入AuthenticationStateProvider,并调用GetAuthenticationStateAsync方法,该方法返回Authentication State对象,可以从中读取ClaimPrincipal对象。 但是,如果您问是否存在创建自定义AuthenticationStateProvider的指南,我只能说我曾经读过一个github问题,其中Steve Anderson说不推荐这样做。 但是我想有时候这是不可避免的...
AuthenticationStateProvider应该作为单例服务添加吗?应限制在连接范围内
我需要能够在自定义类中获取AuthenticationStateProvider.GetAuthenticationStateAsync()
当查询自定义服务器AuthenticationStateProvider对象的身份验证状态时,将从何处获取身份验证状态? 告诉我,我会告诉你如何做。 如果我没记错的话,我已经告诉过你不能使用HttpContext,对吗?
注意:如果要实现自定义AuthenticationStateProvider,则应从ServerAuthenticationStateProvider派生对象,ServerAuthenticationStateProvider是Blazor Server Apps的默认AuthenticationStateProvider。
如果您认为我的回答有用,请接受
public class TokenAuthenticationStateProvider : AuthenticationStateProvider { private readonly IJSRuntime JSRuntime; public TokenAuthenticationStateProvider(IJSRuntime JSRuntime) { JSRuntime = JSRuntime; } public async Task<string> GetTokenAsync() => await _JSRuntime.InvokeAsync<string>("localStorage.getItem", "authToken"); public async Task SetTokenAsync(string token) { if (token == null) { await JSRuntime.InvokeAsync<object>("localStorage.removeItem", "authToken"); } else { await JSRuntime.InvokeAsync<object>("localStorage.setItem", "authToken", token); } NotifyAuthenticationStateChanged(GetAuthenticationStateAsync()); } public override async Task<AuthenticationState> GetAuthenticationStateAsync() { var token = await GetTokenAsync(); var identity = string.IsNullOrEmpty(token) ? new ClaimsIdentity() : new ClaimsIdentity(ServiceExtensions.ParseClaimsFromJwt(token), "jwt"); return new AuthenticationState(new ClaimsPrincipal(identity)); } }
感谢您提供Isaac的信息,但实际上我可以回答自己的问题。 我的解决方案是确保我的助手类是作用域的,而不是单例的,以获取authstateprovider的实例。
services.AddScoped<Classes.GlobalHelper>();
然后,我可以像其他任何DI一样调用authstateprovider,例如:
public async Task<HttpClient> MyHttpClient() { AuthenticationState _authstate = _authStateProv.GetAuthenticationStateAsync().Result; HttpClient http = new HttpClient(); string signedInUserID = _authstate.User.FindFirst(ClaimTypes.NameIdentifier).Value;