【发布时间】:2022-02-17 19:05:24
【问题描述】:
我有一个 react 应用程序作为我的客户端应用程序和一个 asp.net api 作为我的 api(资源)。我已经设法在我的客户端应用程序中集成了 azure ad b2c 登录。现在我正在准备向我的 api(现在使用 azure ad b2c 保护)发送一个包含访问令牌的请求,以访问我的 api 资源。但我从 api 获得状态码 401,这意味着未经授权。我将访问令牌(承载令牌)从客户端应用程序(react)发送到 api,如下所示:
const tokenItem = sessionStorage.getItem('item1');
const tokenjson = JSON.parse(tokenItem);
const accessToken = tokenjson.secret;
const tokenConfig = {
headers: { Authorization: `Bearer ${accessToken}` }
};
axios.post('https://localhost:44304/func', model, tokenConfig)
.then(response => {
this.setState({ Result: response.data });
})
.catch(error => {
console.log(error)
})
在 api 应用程序中,我在 Startup.cs 中有以下代码
public void ConfigureServices(IServiceCollection services)
{
...
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(options =>
{
Configuration.Bind("AzureAdB2C", options);
options.TokenValidationParameters.NameClaimType = "name";
},
options => { Configuration.Bind("AzureAdB2C", options); });
...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseAuthentication();
app.UseAuthorization();
...
}
我在api应用中的appsettings.json是这样的:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AzureAdB2C": {
"Instance": "https://mytenantName.b2clogin.com",
"Domain": "mytenantName.onmicrosoft.com",
"ClientId": "my api client id ",
"SignUpSignInPolicyId": "B2C_1_mySignupSignin_userflow"
},
"AllowedHosts": "*"
}
我的控制器如下:
[Authorize]
[Route("[Controller]")]
[RequiredScope("user.read", "user.write")]
[ApiController]
public class TokenController : Controller
{
[HttpPost]
public async Task<IActionResult> Func([FromBody] CreateModel model)
{
some functions...
}
}
我应该说我可以在客户端应用程序中看到访问令牌(反应)。 为什么我向api发送请求后得到状态码401? 我的代码有问题吗?我真的很感谢任何帮助:)
【问题讨论】:
-
能否请您解码jwt.io 中的令牌并使用获得的变量更新问题。
标签: reactjs azure asp.net-web-api azure-ad-b2c