English 中文(简体)
为什么我的"允许匿名控制器" 授权我的请求?
原标题:Why is my AllowAnonymous api controller routing my request through authorization?

我在控制器一级明确添加了 [AllowAnononymous] 注释,因为我要求不要发生这个问题,然而,当我在控制器上发布时,我发现一个 CORS 错误:

访问 https://login.microsoconline.com//oauth...&x-client-SKU=ID_NET6_0&x-client-ver=6.21.0.0(从 ) 源代码被 CORS 政策封锁...

据我所知,这绝对不应该发生(而且不会发生在POST的其他行动上,

我不知道问题在哪里,或者如何解决。

[AllowAnonymous]
[ApiController]
[Route("api/[controller]")]
public class MembersController : ControllerBase

    [HttpPost]
    public async Task<IActionResult> CreateMemberAsync(CreateMemberViewmodel model)
    {
        if (!model.IsValid(out List<string> validationResult))
        {
            return BadRequest(new { Success = false, Errors = validationResult });
        }

        if (memberService.Exists(model, out Member _))
        {
            var failResult = new { Success = false, Errors = new List<Exception> { new("Unable to create member; member already exists.") } };
            return BadRequest(failResult);
        }

        var result = await memberService.CreateAsync(model, User);

        return Ok(new { Success = true, Values = new [] { result }});
    }

    [HttpPost("Suggest")]
    public async Task<IActionResult> SuggestMembersAsync(CreateMemberViewmodel member)
    {
        var phoneNumberUtil = PhoneNumberUtil.GetInstance();
        try
        {
            var phoneNumber = phoneNumberUtil.Parse(member.MobileTel, "ZA");
            var intlFormat = phoneNumberUtil.Format(phoneNumber, PhoneNumberFormat.INTERNATIONAL);

            member.MobileTel = intlFormat;
        }
        catch (NumberParseException)
        {
            var result = new { Success = false, Value = $"Unable to suggest members; submitted mobileTel is invalid:  {member.MobileTel} "};

            return BadRequest(result);
        }

        var members = await memberService.GetMembersAsync(o => o.OrderBy(x => x.Name));
        members = members.Where(x =>
            (x.Name.Trim() + " " + x.Surname.Trim()).ToLower().Contains((member.Name + " " + member.Surname).ToLower()) ||
            x.Email.ToLower().Trim().Contains(member.Email.ToLower().Trim()) ||
            x.MobileTel.Contains(member.MobileTel)
        ).ToList();

        return Ok(new { Success = true, Values = members });
    }

我只包括了控制器的 POST 2 动作, 用于简洁 。

[HtpPPost (“ 调查”) action, 检索一份成员名单, 其PII与提交的工作相同, 但 [HtpPost] 方法无论如何都拯救了新成员, 但没有 。

要求采取这些行动的标本基本上完全相同:

function getMemberSuggestions(member, containerParent) {
    fetch(`https://<api url>/api/Members/Suggest`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(member)
    })
    .then(res => res.json())
    .then(data => {
        ...
    })

function saveMember(member)
{
    fetch(`https://<api url>/api/Members`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(member)
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            // Redirect to the Calendar with the new member preloaded.
            location.href = `/Home/${data.values[0].id}`
        }
        else
        {
            console.error("Failed to save member.")
            data.errors.forEach(error => console.error(error))
        }
    })
}

我不明白为什么"建议"的终点 不通过授权满足请求, 但未命名的终点是。

我加了CORS 在Api项目上:

services.AddCors(options =>
{
    options.AddPolicy("SignalRPolicy",
        builder => builder.AllowAnyMethod()
                        .AllowAnyHeader()
                        .WithOrigins(
                            "https://localhost:5001", // Self
                            "https://localhost:5003", // Bookings Portal
                            "https://localhost:7008", // Providers Portal
                            "https://localhost:7060", // Patients Portal
                            "https://localhost:7066", // Reports Portal
                            "https://localhost:7093", // Amani Portal

                            // Live URLs go here as well
                    )
                    .AllowCredentials());
});

那又怎样?我该如何绕过CORS的发行?

问题回答

您是否在启动时配置了 UseCors 。 cs 位于 公共真空配置(IApplicationBuilder ap, IWebHostenviron env) ?

您能否设置以下显示的启动. cs :

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy("MyAllowSpecificOrigins",
                builder => builder
                    .WithOrigins(
                        "https://localhost:5001", 
                        "https://localhost:5003", 
                        "https://localhost:7008", 
                        "https://localhost:7060", 
                        "https://localhost:7066", 
                        "https://localhost:7093" 
                        // live URLs 
                    )
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials());
        });

        services.AddControllers();
        // Other services
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseCors("MyAllowSpecificOrigins"); // Make sure to call this before UseAuthorization

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

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

主计长:

[ApiController]
[Route("api/[controller]")]
[EnableCors("MyAllowSpecificOrigins")] 
public class MembersController : ControllerBase
{
    [HttpPost]
    [AllowAnonymous]
    public async Task<IActionResult> CreateMemberAsync(CreateMemberViewmodel model)
    {
        // Original code 
    }

    [HttpPost("Suggest")]
    public async Task<IActionResult> SuggestMembersAsync(CreateMemberViewmodel member)
    {
        // Original code 
    }
}

您可以将此文档转介至此文件以获取更多细节 :

< a href=>https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-ennetcore-800#enable-cors-with-atribites" rel=“不跟随 no follown norefererr">https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-enable-cors- with-atripittes

https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-8.0" rel=“不跟随 noreferrer">https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-8.0





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签