【发布时间】:2022-11-25 06:35:08
【问题描述】:
我正在尝试使用具有 API 授权的 React.js 项目创建一个 ASP.NET Core,但很难找到有意义的文档/说明。
https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity-api-authorization?view=aspnetcore-7.0 似乎是一个很好的参考,但它使用的是实体框架,而我不是。我的目标是在没有 EF 的情况下管理用户身份验证。
dotnet new react -au Individual 创建的 React 模板提供了 AuthorizeService.js 和 OidcConfigurationController.cs 我在这里链接:https://gist.github.com/julesx/d3daa6ed5a7f905c984a3fedf02004c0
我的program.cs如下:
using Duende.IdentityServer.Models;
using Microsoft.AspNetCore.Authentication;
var ApiScopes = new List<ApiScope> {
new ApiScope("api1", "My API")
};
var Clients = new List<Client> {
new Client {
ClientId = "client",
// no interactive user, use the clientid/secret for authentication
AllowedGrantTypes = GrantTypes.ClientCredentials,
// secret for authentication
ClientSecrets =
{
new Secret("secret".Sha256())
},
// scopes that client has access to
AllowedScopes = { "api1" }
}
};
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiScopes(ApiScopes)
.AddInMemoryClients(Clients);
builder.Services.AddAuthentication()
.AddIdentityServerJwt();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseIdentityServer();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
app.MapFallbackToFile("index.html");
app.Run();
在努力走到这一步之后,应用程序成功启动(开发环境)。
我从前端获取的内容如下:
export async function getKpiData(): Promise<IRawKpi[]> {
const token = await authService.getAccessToken();
const response = await fetch('/kpidata', {
headers: !token ? {} : { 'Authorization': `Bearer ${token}` }
});
if (response.status == 200) {
return response.json();
}
return [];
}
这会导致对 OidcConfigurationController 的获取请求失败并出现以下错误:
Unable to resolve service for type 'Microsoft.AspNetCore.ApiAuthorization.IdentityServer.IClientRequestParametersProvider' while attempting to activate 'MyNamespace.Controllers.OidcConfigurationController'.
我知道这是因为我没有将 IClientRequestParametersProvider 注册到 OidcConfigurationController 中,但是当我查看示例代码时,我也没有看到它被注入到那里。我也没有看到任何明显的东西我应该注入Program.csbuilder.Services。
我在正确的轨道上吗?配置它所需的“神秘”知识量似乎难以承受。我可以参考某个地方的质量示例吗? Program.cs 实现一些超级基本身份验证的最低要求是什么?
【问题讨论】:
标签: reactjs asp.net asp.net-core authentication