首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Azure AD C2C/Next.Js/ASP.NETCore 6:如何使用PKCE代码流访问令牌访问Web API?

Azure AD C2C/Next.Js/ASP.NETCore 6:如何使用PKCE代码流访问令牌访问Web API?
EN

Stack Overflow用户
提问于 2022-06-27 11:35:04
回答 1查看 202关注 0票数 0

我需要帮助,我被困了几天,试图保护一个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令牌(用于隐式流和混合流)

这就是登录的方式。

代码语言:javascript
复制
  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.

代码语言:javascript
复制
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中有以下规则

代码语言:javascript
复制
  async rewrites() {
    return {
      fallback: [
        {
          source: "/api/net/:path*",
          destination: "http://localhost:5015/api/:path*",
        },
      ],
    };
  },

ASP.NET核心6应用程序:(helloworld.api)

管理->公开API

作用域✅都检查了错误用户

谁能同意:只有管理员

状态:启用

The appsettings.json

代码语言:javascript
复制
  "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.csdotnet new webapi -au IndividualB2C生成的cors

代码语言:javascript
复制
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

代码语言:javascript
复制
[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

代码语言:javascript
复制
else
{
    app.UseHttpsRedirection();
}

因为next.js是一个全堆栈应用程序,所以有问题吗?我相信它作为SPA的作用,因为我推迟收购accessToken,直到InteractionStatus.None?

EN

回答 1

Stack Overflow用户

发布于 2022-06-29 15:05:49

请检查您是否需要在应用程序设置中修改配置范围的方式。尝试给出完整的范围https://<tenant>/api/<scope>.

代码语言:javascript
复制
{
"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"
  }

}

  • 还检查app.UseHttpsRedirection();是否在if循环之后使用 if (env.IsDevelopment()) { app.UseDeveloperExceptionPage();} app.UseHttpsRedirection();app.UseRouting();app.UseAuthentication();app.UseAuthorization();

此外,请确保重新检查和提供适当的重定向url,这必须是相同的门户和授权请求。一定是有效网址

参考资料:在使用Azure Active B2C Microsoft文档调用web的示例web应用程序中配置身份验证

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72771430

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档