Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/api/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ASP.NET Core 3.1如何使用Azure AD B2C返回401未经授权而不是质询_C#_Api_Asp.net Core_Asp.net Web Api_Azure Ad B2c - Fatal编程技术网

C# ASP.NET Core 3.1如何使用Azure AD B2C返回401未经授权而不是质询

C# ASP.NET Core 3.1如何使用Azure AD B2C返回401未经授权而不是质询,c#,api,asp.net-core,asp.net-web-api,azure-ad-b2c,C#,Api,Asp.net Core,Asp.net Web Api,Azure Ad B2c,在我的API控制器中,我希望[Authorize]属性返回401 Unauthorized,而不是强制Azure AD B2C登录质询,并将该响应返回到我的前端(对API进行ajax调用) 由于Azure CORS策略,质询重定向无法工作。我找到了多个答案,其中没有一个似乎有效(401没有返回,它仍然试图重定向到Azure B2C挑战) API控制器: [Route("api/[controller]")] [ApiController] [Authorize] public class Hie

在我的API控制器中,我希望
[Authorize]
属性返回401 Unauthorized,而不是强制Azure AD B2C登录质询,并将该响应返回到我的前端(对API进行ajax调用)

由于Azure CORS策略,质询重定向无法工作。我找到了多个答案,其中没有一个似乎有效(401没有返回,它仍然试图重定向到Azure B2C挑战)

API控制器:

[Route("api/[controller]")]
[ApiController]
[Authorize]
public class HierarchyController : ControllerBase
// ...
这是我当前的
启动。ConfigureServices
代码:

// ...
services.Configure<AzureADB2COptions>(opt => 
            Configuration.GetSection("AzureAdB2C").Bind(opt));

services.AddAuthentication(AzureADB2CDefaults.AuthenticationScheme)
            .AddAzureADB2C(opt => Configuration.Bind("AzureAdB2C", opt))
            .AddCookie(opt =>
            {
                opt.Events = new CookieAuthenticationEvents
                {
                    OnRedirectToLogin = ctx =>
                    {
                        ctx.Response.StatusCode = 401;
                        return Task.CompletedTask;
                    }
                };
            });
在这两种情况下,都会使用
OnRedirectToAccessDenied
向上切换
OnRedirectToLogin
。这些都不管用。 这些事件中的断点永远不会被命中,在执行未经授权的API调用后,我出现以下错误:

在处访问XMLHttpRequest(已从重定向)https://localhost:44394/api/Hierarchy“)起源”https://localhost:44394'已被CORS策略阻止:对飞行前请求的响应未通过访问控制检查:请求的资源上不存在'access control Allow Origin'标头。

编辑:
配置服务

// ...
app.UseRouting(); 

app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
      endpoints.MapControllerRoute(
           name: "default",
           pattern: "{controller}/{action=Index}/{id?}");
});
对于将来阅读的任何人(或我),我已经解决了这个问题。 在
ConfigureServices
do中:

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = AzureADB2CDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultSignOutScheme = AzureADB2CDefaults.AuthenticationScheme;
        })
            .AddAzureADB2C(options => Configuration.Bind("AzureAdB2C", options))
            .AddCookie(options =>
            {
                options.Events = new CookieAuthenticationEvents
                {
                    OnRedirectToLogin = context =>
                    {
                        if (context.Request.Path.StartsWithSegments("/api"))
                        {
                            context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                        }
                        else
                        {
                            context.Response.Redirect(context.RedirectUri);
                        }

                        return Task.FromResult(0);
                    }
                };
            });

我有完全相同的问题,但在.NET Core 3.1中,我不知道如何通过调用
AddMicrosoftIdentityWebAppAuthentication
方法来实现这一点,这似乎是向应用程序添加ADB2C的推荐方法(基于示例)。不过我可能错了。有人用.NETCore3.1实现过同样的目标吗?
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = AzureADB2CDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultSignOutScheme = AzureADB2CDefaults.AuthenticationScheme;
        })
            .AddAzureADB2C(options => Configuration.Bind("AzureAdB2C", options))
            .AddCookie(options =>
            {
                options.Events = new CookieAuthenticationEvents
                {
                    OnRedirectToLogin = context =>
                    {
                        if (context.Request.Path.StartsWithSegments("/api"))
                        {
                            context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                        }
                        else
                        {
                            context.Response.Redirect(context.RedirectUri);
                        }

                        return Task.FromResult(0);
                    }
                };
            });