【问题标题】:How to authorize an API endpoint with both JWT and Azure Ad token?如何使用 JWT 和 Azure Ad 令牌授权 API 端点?
【发布时间】:2023-01-19 21:59:26
【问题描述】:

我创建了一个 React 应用程序,它调用 .net API 作为后端服务。在我的 React 应用程序中,有两种登录方式,第一种是使用用户名和密码,第二种是使用 azure ad 登录。

当我们使用用户名和密码登录时,它会访问 api 端点并生成令牌并根据生成的令牌授权用户。以同样的方式,我想在用户从天蓝色的广告部分登录时授权他。

那么,当用户使用用户名或密码登录或借助 azure ad login 登录时,我如何授权后端 API 端点。

Startup.cs(这是我处理 jwt 授权流程的代码)

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddCors(p => p.AddPolicy("corsapp", builder =>
{
    builder.WithOrigins("http://localhost:8082").AllowAnyMethod().AllowAnyHeader();
}));

builder.Services.AddControllers().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.PropertyNamingPolicy = null;
});

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "BaseWebApi", Version = "v1" });
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Description = "Jwt Authorization",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
        Scheme = "Bearer"
    });
    c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                         new OpenApiSecurityScheme
                    {
                        Reference = new OpenApiReference
                        {
                            Type = ReferenceType.SecurityScheme,
                            Id= "Bearer"
                        }
                    },
                    new string[]{}
                    }
                });

});

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = builder.Configuration["Jwt:Issuer"],
        ValidAudience = builder.Configuration["Jwt:Audience"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:key"]))
    };
});

var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "DemoJWTToken v1"));
}

app.UseHttpsRedirection();
app.UseCors("corsapp");

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();
 

【问题讨论】:

    标签: c# reactjs .net api authorization


    【解决方案1】:

    您应该使用“ClaimsPrinciple”对象,可以通过在 API 的控制器上使用关键字“User”找到。

    这将允许您构建一个逻辑,该逻辑取决于令牌是否存在、一组用户名或您真正想做的任何事情。

    【讨论】:

      猜你喜欢
      • 2021-04-24
      • 2020-11-09
      • 1970-01-01
      • 2016-11-30
      • 2016-08-02
      • 2016-12-02
      • 2019-06-04
      • 1970-01-01
      • 2019-05-14
      相关资源
      最近更新 更多