通过传递 Azure B2C JWT Bearer 令牌从 Angular 调用 .NET CORE Web API Secure End-point

Call .NET CORE Web API Secure End-point from Angular by passing Azure B2C JWT Bearer token

我需要通过出示 Azure B2C JWT Bearer 令牌从 Angular 9 应用程序调用安全 Web API。我正在使用 Angular 9 和 .NET CORE 3.1 Web API。我已设法生成 Azure B2C 令牌,但由于收到 401 未经授权的错误,因此无法调用安全 Web API end-point。我正在从 angular.

在 header 中传递令牌

Angular 组件调用 Web API end-point

testAPI1(){
    console.log("calling test API ...");

    const myheaders = new HttpHeaders({
        'Content-Type': 'application/json; charset=utf-8',
        'Authorization': this.authService.accessToken
    });

    this.http.get('https://localhost:5001/txn/v1/Dashboard/GetMessage', {headers: myheaders})
        .subscribe((data)=>{
            console.warn(data);
        })
}

授权服务

@Injectable()
export class AuthService implements OnInit{

constructor(
    private oauthService: OAuthService,
    private router: Router

){// other code}


public get accessToken() { 
    return this.oauthService.getAccessToken(); 
}

Web API 控制器和端点

[Authorize]
[Route("txn/v1/[controller]/[action]")]
[EnableCors("CorsPolicy")]
[ApiController]
public class DashboardController : ControllerBase
{
    [HttpGet]
    public ActionResult<HelloMessage> GetMessage()
    {
        var result = new HelloMessage()
        {
            GivenName = "james",
            ReturnMessage = "Dashboard@ Hello, Welcome to Digital tech"
        };
        return result;
    }

Startup.cs

public void ConfigureServices(IServiceCollection services)
    {
       //JWT Authentication 
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(jwtConfig => 
            {
                jwtConfig.Audience = Configuration["AzureAdB2C:ResourceId"];
                jwtConfig.Authority = $"{Configuration["AzureAdB2C:Instance"]}{Configuration["AzureAdB2C:TanantId"]}";
                jwtConfig.RequireHttpsMetadata = false;
                jwtConfig.SaveToken = true;
                jwtConfig.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    ValidateIssuer =true,
                    ValidateAudience = true,
                    ValidateLifetime = true

                };
        });

 //CORS policy
 services.AddCors(options =>
                          options.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin()));

错误

请求header响应

visual studio 事件异常

PII 是隐藏错误

根据您提供的代码,您使用错误Authority。如果我们使用 Azure AD B2C,Authority 应该像 https://{your-tenant-name}.b2clogin.com/tfp/{your-tenant-domain}/{your-policy-name}/v2.0

例如

Web API 应用程序

一个。 appsettings.json.

{
  "AzureAdB2C": {
    "Instance": "https://<your tenant name>.b2clogin.com",
    "ClientId": " your client id",
    "Domain": "your tenant domain",
"TenantId": "your tenant id",
    "SignUpSignInPolicyId": "your policy name"
  },
  ...
}

b。 Startup.cs.

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(jwtConfig =>
            {
                jwtConfig.Audience = Configuration["AzureAdB2C:ClientId"];
                jwtConfig.Authority = $"{Configuration["AzureAdB2C:Instance"]}/tfp/{Configuration["AzureAdB2C:Domain"]}/{Configuration["AzureAdB2C:SignUpSignInPolicyId"]}/v2.0";
                jwtConfig.RequireHttpsMetadata = false;
                jwtConfig.SaveToken = true;
                jwtConfig.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidAudience= jwtConfig.Audience,
                    ValidIssuer = $"{Configuration["AzureAdB2C:Instance"]}/{Configuration["AzureAdB2C:TenantId"]}/v2.0/"
                };

            });

            services.AddCors(options =>
            {
                options.AddDefaultPolicy(
                    builder => builder.AllowAnyOrigin()
                        .AllowAnyHeader()
                        .AllowAnyMethod());
            });
            services.AddControllers();
        }

Angular组件调用WebAPI端点

public getMessage() {
    const myheaders = new HttpHeaders({
      'Content-Type': 'application/json; charset=utf-8',
      'Authorization': 'Bearer '+this.oauthService.getAccessToken(),
      'Access-Control-Allow-Origin':'*'
  });
   console.log(myheaders)
    this.http.get("https://localhost:44389/weatherforecast", {headers: myheaders})
      .subscribe(r => {
        this.message = JSON.stringify(r) 
        console.log("message: ", this.message);
      });
  }