我尝试自己构建此应用程序,但是在此过程中遇到了几个绊脚石。我认为最好退后一步,更广泛地了解我尝试创建的内容。似乎没有任何关于如何制作所需内容的文档。 (除非有人可以指出我可能错过的正确位置)
最终,我想让Blazor(服务器端)应用程序进行API调用以使用应用程序中的数据,然后让IdentityServer4封装身份验证。我需要具有Azure以及ASP.net Identity作为可能的身份验证方法。
我已经尝试并能够创建一个也具有本地API的IdentityServer4。我可以致电Postman来获取令牌等。但是,在将Blazor(服务器端)应用程序与IdentityServer4绑定时,我很困惑。
我试图具体询问这个问题,但是根本没有任何结果。我希望从更大的角度来看可能会有所帮助。
似乎odic-client.js是从IdentityServer4回调中获取数据的方法,但是,这似乎与Blazor(服务器端)中的.NET授权并不太好。我如何使它们一起工作。
答案 0 :(得分:1)
我使用API / IdentityServer4 / Blazor(服务器端)进行了类似的设置。我将向您展示一些我使用的代码,也许您可以利用它。
使用NuGet包Microsoft.AspNetCore.Authentication.OpenIdConnect,我在Startup类的ConfigureServices方法中获得了以下代码:
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.Authority = "https://localhost:5001";
options.ClientId = "myClient";
options.ClientSecret = "mySecret";
options.ResponseType = "code id_token";
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.Scope.Add("MyApi");
options.Scope.Add("offline_access");
options.ClaimActions.MapJsonKey("website", "website");
});
以及在Configure方法app.UseAuthentication();
然后在App.razor中,我使用了CascadingAuthenticationState组件:
<CascadingAuthenticationState>
<Router AppAssembly="typeof(Startup).Assembly" />
</CascadingAuthenticationState>
在我的主页Index.razor中使用NuGet包Microsoft.AspNetCore.Authorization:
@using Microsoft.AspNetCore.Authorization
@attribute [Authorize]
现在,当您打开主页时,它应该显示“未经身份验证”,但是仍然没有重定向到IdentityServer4。为此,正如我从this stackoverflow question中学到的那样,您还必须在启动中添加MVC:
services.AddMvcCore(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
现在,应该将您重定向到IdentityServer4,以在启动应用程序后登录。就我而言,我有一个ApiClient,它描述了我的API的方法。我使用DI注入ApiClient并添加访问令牌:
services.AddHttpClient<IApiClient, ApiClient>(async client =>
{
var serviceProvider = services.BuildServiceProvider();
var httpContextAccessor = serviceProvider.GetService<IHttpContextAccessor>();
var accessToken = await httpContextAccessor.HttpContext.GetTokenAsync("access_token");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
client.BaseAddress = new Uri("http://localhost:55578");
});
就像您说的那样,除了关于stackoverflow的一些答案以外,没有太多关于此主题的文档。我花了很长时间来设置此功能,因此希望我可以为其他人提供帮助。
答案 1 :(得分:0)