【发布时间】:2020-08-02 05:02:36
【问题描述】:
我在从 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);
});
Startup.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 控制器没有“授权”属性,则有效,但一旦添加,则将继续未经授权。
【问题讨论】:
-
如何配置客户端认证库,调用web api时是否使用引用令牌作为http请求头?也可以使用 fiddler 跟踪 web api 请求,检查是否返回任何详细的错误信息。
-
我们能看到控制器代码吗?特别是 [Route] 属性,你是在它前面添加 /api/ 吗?
-
@PabloRecalde,感谢您的帮助。是我的错误,在身份服务器中缺少配置会导致问题。
-
@NanYu,感谢您的帮助。是我的错误,在身份服务器中缺少配置会导致问题。
标签: c# asp.net-core identityserver4 asp.net-spa