ASP.NET Core API从React客户端返回401 [英] ASP.NET Core API returning 401 on call from React client

查看:320
本文介绍了ASP.NET Core API从React客户端返回401的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有React/Redux前端的全新ASP.NET Core 2.1 SPA应用程序.我已经实现了jwt身份验证,该身份验证是从Azure AD B2C获取其令牌的.

I'm working on a brand new ASP.NET Core 2.1 SPA app with React/Redux front end. I've implemented jwt authentication which gets its token from Azure AD B2C.

当我分析针对后端的API调用的网络标签时,我看到令牌位于标头中-见下文:

When I analyze the network tab for my API call to the backend, I see that token is placed in the header -- see below:

这是我的提取调用的代码:

Here's the code for my fetch call:

import { fetchOptionsGet, fetchOptionsPost, parseJSON } from '../../utils/fetch/fetch-options';

export const getData = () => {

    return (dispatch) => fetch("/api/accounts/test", fetchOptionsGet())
        .then((response) => {

            if (response.ok) {

                parseJSON(response)
                    .then(result => {
                        // Do something here...
                    })
            }
        })
};

这是我的提取选项:

export const fetchOptionsGet = () => {

    const token = authentication.getAccessToken();
    debugger
    return {
        method: 'GET',
        mode: 'cors',
        headers: {
            "Content-Type": "application/json",
            "Authentication": "Bearer " + token
        }
    }
}

请注意上面代码中的debugger,以确保我得到的令牌确认我具有令牌-更不用说这也是我的网络通话.

Notice the debugger in the above code to make sure I'm getting the token which confirms I have the token -- not to mention it's my network call as well.

这是Startup.cs中的ConfigureServices()方法:

public void ConfigureServices(IServiceCollection services)
{
        services.AddAuthentication(options => {
             options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
         })
         .AddJwtBearer(jwtOptions => {
         jwtOptions.Authority = $"https://login.microsoftonline.com/tfp/{Configuration["AzureAdB2C:Tenant"]}/{Configuration["AzureAdB2C:Policy"]}/v2.0/";
         jwtOptions.Audience = Configuration["AzureAdB2C:ClientId"];
         jwtOptions.Events = new JwtBearerEvents
         {
              OnAuthenticationFailed = AuthenticationFailed
         };
     });

     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

     // In production, the React files will be served from this directory
     services.AddSpaStaticFiles(configuration =>
     {
         configuration.RootPath = "ClientApp/build";
     });
}

这是Startup.cs中的Configure()方法:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
       app.UseDeveloperExceptionPage();
    }
    else
    {
       app.UseExceptionHandler("/Error");
       app.UseHsts();
    }

    app.UseHttpsRedirection();

    ScopeRead = Configuration["AzureAdB2C:ScopeRead"];
    app.UseAuthentication();

    app.UseStaticFiles();
    app.UseSpaStaticFiles();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller}/{action=Index}/{id?}");
    });

    app.UseSpa(spa =>
    {
        spa.Options.SourcePath = "ClientApp";

        if (env.IsDevelopment())
        {
           spa.UseReactDevelopmentServer(npmScript: "start");
        }
     });
}

这是API控制器:

[Produces("application/json")]
[Route("api/[controller]")]
[Authorize]
public class AccountsController : Controller
{
    [HttpGet("test")]
    public async Task<IActionResult> Test()
    {
        // Do something here...
    }
}

我在Test() API方法的开头放置了一个断点,但是我没有碰到它.没有[Authorize]属性,我可以使用Test() API方法并获取我的数据.因此,在我什至未使用API​​方法之前,管道中的某些内容就阻止了该调用.

I put a break point right at the beginning of my Test() API method but I'm not hitting it. Without the [Authorize] attribute, I'm able to hit the Test() API method and get my data. So, something in the pipeline is blocking the call before I even hit the API method.

我还尝试使用以下命令在我的API控制器中指定授权方案,但这没有任何区别.仍然出现401错误.

I also tried specifying the authorization scheme in my API controller with the following but that didn't make any difference. Still getting a 401 error.

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

有什么主意我在这里犯错了吗?

Any idea where I'm making a mistake here?

推荐答案

标头名称应为Authorization.

export const fetchOptionsGet = () => {

    const token = authentication.getAccessToken();
    debugger
    return {
        method: 'GET',
        mode: 'cors',
        headers: {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + token //<--
        }
    }
}

这篇关于ASP.NET Core API从React客户端返回401的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆