c# - .Net Core 3.1 SPA 授权失败
问题描述
我在从 React SPA 调用授权 api 时遇到问题。如果删除控制器/操作中的 [Authorize] 属性,它就可以工作,但是一旦添加到属性中,响应就会转到 SPA 主页。
项目结构
IdentityServer (.net core 3.1 mvc with IdentityServer4 *reference token type)
登录(使用 IdentityServer 进行身份验证和对 Portal 的身份验证回调)
Portal(.net core 3.1 react SPA,使用IdentityServer4.AccessTokenValidation进行验证
反应
fetch('/api/test').then(async (response) => {
var data = await response.json();
console.dir(response);
console.dir(data);
});
启动.cs
public void ConfigureServices(IServiceCollection services)
{
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddControllersWithViews()
.ConfigureApiBehaviorOptions(options => { options.SuppressModelStateInvalidFilter = true; });
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
options.Authority = "https://localhost:44302";
options.ApiName = "api1";
options.ApiSecret = "thisissecret";
});
services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/build"; });
}
public override void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); });
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (_WebHostEnvironment.IsDevelopment())
{
spa.UseReactDevelopmentServer("start");
}
});
}
如果 api 控制器没有“授权”属性,则有效,但一旦添加,则将继续未经授权。
解决方案
抱歉,伙计们,我错过了在 IdentityServer 中设置 ApiSecret 的错误。因此,它一直未经身份验证。
new ApiResource("api1", )
{
// the missing part
ApiSecrets = {
new Secret("thisissecret".Sha256())
}
}
推荐阅读
- python - 如何强制 jupyter notebook 只使用安装在虚拟环境中的包?
- python - 如何在Flask中对SubmitField使用onclick函数(WTF SubmitField问题)
- mysql - 为什么我可以使用卷参数启动容器
- python - poll_disconnected、poll_in、poll_out 和取消之间的区别
- wordpress - 如何对使用 wp.apiFetch 的古腾堡类/组件方法进行单元测试
- c# - MSBuild 任务的默认区域性是什么?
- django - django 与过滤后的 ListView 没有反向匹配
- javascript - HTML 中断标记混淆了 javascript 处理的项目的顺序
- python - 使用 scalingo 的 URL python 连接到 prod 数据库
- oracle - 使用 TEXT_IO 显示一条记录的过程