我正在开发一个带有 React/Redux 前端的全新 ASP.NET Core 2.1 SPA 应用程序。我已经实施了jwt
从 Azure AD B2C 获取其令牌的身份验证。
当我分析对后端 API 调用的网络选项卡时,我看到令牌被放置在标头中 - 见下文:
这是我的 fetch 调用的代码:
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)]
知道我在这里犯了错误吗?