ASP.NET Core API从React客户端

时间:2018-05-18 19:53:28

标签: asp.net asp.net-core jwt azure-ad-b2c

我正在开发一个带有React / Redux前端的全新ASP.NET Core 2.1 SPA应用。我已实施jwt身份验证,该身份验证从Azure AD B2C获取其令牌。

当我分析我对后端的API调用的网络选项卡时,我看到该标记放在标题中 - 见下文:

enter image description here

这是我的提取电话的代码:

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,以确保我获得了确认我拥有令牌的令牌 - 更不用说它也是我的网络电话。

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

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";
     });
}

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

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​​方法之前,管道中的某些东西阻止了调用。

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

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

我知道我在哪里犯了错误吗?

1 个答案:

答案 0 :(得分:3)

标题名称应为Authorization

export const fetchOptionsGet = () => {

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