我需要帮助,我被困了几天,试图保护一个Web (ASP.NET Core6),方法是从用户发送访问令牌 (Azure Ad B2C with google /local),使用身份验证代码流(PKCE)< code >E29签名。
这会产生(401)未经授权的错误。出什么问题了?
Next.js应用程序:(helloworld.webapp)
Azure Ad B2C设置
管理->身份验证
Single-page-application与重定向uri:http://localhost:3000
管理-> API权限
helloworld.api
需要access_as_user \管理同意:是的:状态:✅授予helloworld
微软图
需要offline_access \管理同意:是的:状态:✅授予helloworld
需要openid \管理同意:是的:为helloworld授予的✅
(未经检查)
访问令牌(用于隐式流)
ID令牌(用于隐式流和混合流)
这就是登录的方式。
const login = (event: React.MouseEvent<HTMLButtonElement>) => {
console.log("only logs in browser console")
instance.loginRedirect({
scopes: [
"openid",
"offline_access",
// ✅ checked for typo
"https://helloworld.onmicrosoft.com/8a1bc000-2000-4000-a000-d3156a663000/access_as_user",
]
})
}在下面的片段中,您可以看到我如何获得我的accessToken.
const postData = (event: React.MouseEvent<HTMLButtonElement>) => {
event.preventDefault();
// to prevent ssr mismatch errors.
if (!data && inProgress === InteractionStatus.None) {
instance
.acquireTokenSilent({
scopes: [
"openid",
"offline_access",
// ✅ checked for typo
"https://helloworld.onmicrosoft.com/8a1bc000-2000-4000-a000-d3156a663000/access_as_user",
]
})
.then((accessTokenResponse) => {
let accesstoken = accessTokenResponse.accessToken;
console.log(accesstoken); // only logs in browser console.
// // ✅ weatherforecast endpoint checked. Maps to http://localhost:5015/api/:path*
fetch("/api/net/weatherforecast", {
method: "GET",
headers: {
Authorization: `Bearer ${JSON.stringify(accesstoken)}`,
},
})
.then((res) => console.log(res))
.catch((err) => console.log(err));
});
}
};我在next.config.js中有以下规则
async rewrites() {
return {
fallback: [
{
source: "/api/net/:path*",
destination: "http://localhost:5015/api/:path*",
},
],
};
},ASP.NET核心6应用程序:(helloworld.api)
管理->公开API
作用域✅都检查了错误用户
谁能同意:只有管理员
状态:启用
The appsettings.json
"AzureAdB2C": {
"Instance": "https://helloworld.b2clogin.com/",
"ClientId": "8a1bc000-2000-4000-a000-d3156a663000",
"Domain": "helloworld.onmicrosoft.com",
"Scopes": "access_as_user",
"SignUpSignInPolicyId": "B2C_1_authflow"
},使用添加了Program.cs的dotnet new webapi -au IndividualB2C生成的cors。
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Identity.Web;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAdB2C"));
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddCors(o => o.AddPolicy("default", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI();
}
else
{
app.UseHttpsRedirection();
}
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();The WeatherForecastController
[Authorize]
[ApiController]
[Route("api/[controller]")]
[RequiredScope(RequiredScopesConfigurationKey = "AzureAd:Scopes")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}最后,用户流
用户流(B2C_1_authflow)

可能的原因?:
没有https,因为这提供了一个net::ERR_CERT_AUTHORITY_INVALID
else
{
app.UseHttpsRedirection();
}因为next.js是一个全堆栈应用程序,所以有问题吗?我相信它作为SPA的作用,因为我推迟收购accessToken,直到InteractionStatus.None?
发布于 2022-06-29 15:05:49
请检查您是否需要在应用程序设置中修改配置范围的方式。尝试给出完整的范围https://<tenant>/api/<scope>.
{
"AzureAdB2C": {
"Instance": "https://<your-tenant-name>.b2clogin.com",
"ClientId": "<web-app-application-id>",
"Domain": "<your-b2c-domain>",
"SignUpSignInPolicyId": "<your-sign-up-in-policy>"
// "SignedOutCallbackPath": "/signout/<your-sign-up-in-policy>",
},
"TodoList": {
"TodoListScope": "https://contoso.onmicrosoft.com/api/access_as_user openid offline_access",
"TodoListBaseAddress": "https://localhost:44332"
}}
此外,请确保重新检查和提供适当的重定向url,这必须是相同的门户和授权请求。一定是有效网址
https://stackoverflow.com/questions/72771430
复制相似问题