admin管理员组

文章数量:1402331

Hoping someone can help me out.

We have a 8 blazor web site (ServerPrerendered) with web pages that have to use OpenIdConnectDefaults.AuthenticationScheme so users logged into the company's SSO can reach the pages.

Now we are adding a new controller with api endpoints that have to use JwtBearerDefaults.AuthenticationScheme so another system can make calls those endpoints.

Here is what we have in Program.cs:

var builder = WebApplication.CreateBuilder(args);

Workflow.Startup(builder.Configuration);

builder.Services.AddControllersWithViews(options =>
{
    var policy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
    options.Filters.Add(new AuthorizeFilter(policy));
    options.Filters.Add(new AutoValidateAntiferyTokenAttribute());
});

builder.Services.AddSingleton(userController => new UserController())
                .AddSingleton(logController => new LoggingController())
                .AddSingleton(adminController => new AdminController())
                .AddSingleton(recordController => new RecordController())
                .AddSingleton(storageController => new StorageController())
                .AddSingleton(svfRecordController => new SvfRecordController());

builder.Services.AddHttpContextAccessor();

// Add services to the container.
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("ApiAzureAd"));

builder.Services.AddControllersWithViews()
    .AddMicrosoftIdentityUI();

builder.Services.AddAuthorization(options =>
{
    // By default, all incoming requests will be authorized according to the default policy
    options.FallbackPolicy = options.DefaultPolicy;
});

builder.Services.AddRazorPages();

builder.Services.AddServerSideBlazor()
    .AddMicrosoftIdentityConsentHandler();
    
builder.Services.AddBlazorBootstrap();

// Learn more about configuring Swagger/OpenAPI at 
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

//this allows the IP Address of the caller to be obtained for logs, from here : 
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
    ForwardedHeaders = ForwardedHeaders.XForwardedFor |
    ForwardedHeaders.XForwardedProto
});

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see .
    app.UseHsts();
}
else
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

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

app.MapControllers();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();

When I comment out the OpenIdConnectDefaults.AuthenticationScheme lines, the api is able to be called (via Postman), but the web page all get 401s (no rendering code reached).

When I comment out the JwtBearerDefaults.AuthenticationScheme lines, the web pages function fine, but the api cannot accept requests.

Is there a way to have both work?

Thanks In Advance!

Hoping someone can help me out.

We have a 8 blazor web site (ServerPrerendered) with web pages that have to use OpenIdConnectDefaults.AuthenticationScheme so users logged into the company's SSO can reach the pages.

Now we are adding a new controller with api endpoints that have to use JwtBearerDefaults.AuthenticationScheme so another system can make calls those endpoints.

Here is what we have in Program.cs:

var builder = WebApplication.CreateBuilder(args);

Workflow.Startup(builder.Configuration);

builder.Services.AddControllersWithViews(options =>
{
    var policy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
    options.Filters.Add(new AuthorizeFilter(policy));
    options.Filters.Add(new AutoValidateAntiferyTokenAttribute());
});

builder.Services.AddSingleton(userController => new UserController())
                .AddSingleton(logController => new LoggingController())
                .AddSingleton(adminController => new AdminController())
                .AddSingleton(recordController => new RecordController())
                .AddSingleton(storageController => new StorageController())
                .AddSingleton(svfRecordController => new SvfRecordController());

builder.Services.AddHttpContextAccessor();

// Add services to the container.
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("ApiAzureAd"));

builder.Services.AddControllersWithViews()
    .AddMicrosoftIdentityUI();

builder.Services.AddAuthorization(options =>
{
    // By default, all incoming requests will be authorized according to the default policy
    options.FallbackPolicy = options.DefaultPolicy;
});

builder.Services.AddRazorPages();

builder.Services.AddServerSideBlazor()
    .AddMicrosoftIdentityConsentHandler();
    
builder.Services.AddBlazorBootstrap();

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

//this allows the IP Address of the caller to be obtained for logs, from here : https://stackoverflow/questions/28664686/how-do-i-get-client-ip-address-in-asp-net-core
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
    ForwardedHeaders = ForwardedHeaders.XForwardedFor |
    ForwardedHeaders.XForwardedProto
});

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}
else
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

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

app.MapControllers();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();

When I comment out the OpenIdConnectDefaults.AuthenticationScheme lines, the api is able to be called (via Postman), but the web page all get 401s (no rendering code reached).

When I comment out the JwtBearerDefaults.AuthenticationScheme lines, the web pages function fine, but the api cannot accept requests.

Is there a way to have both work?

Thanks In Advance!

Share Improve this question edited Mar 25 at 5:52 Qiang Fu 9,3871 gold badge6 silver badges16 bronze badges asked Mar 21 at 13:04 OrionOrion 1377 bronze badges 1
  • You should call AddAuthentication only once and chain your authentication methods one after another. In each call you are specifying the default authentication scheme, that's why commenting one, allows the other one to work. You can then specify in the [Authorize] attribute, which scheme needs to be used. – Parsa99 Commented Mar 23 at 13:56
Add a comment  | 

1 Answer 1

Reset to default 0

To explain it clearly, the syntax is

builder.Services.AddAuthentication(
    options =>
    {
        options.DefaultScheme = Scheme?;
        options.DefaultSignInScheme = Scheme?;
        options.DefaultSignInScheme = Scheme?;
        ...
    })
    .AddAuthScheme1()
    .AddAuthScheme2()
    ...

When you use without options like AddAuthentication(Scheme?), it sets the "DefaultScheme" globally and will be override if you set it again. So you can use it like below:

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("ApiAzureAd"));

Then you could specify controllers scheme globally like below.

builder.Services.AddControllersWithViews(options =>
{
    var jwtPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
        .Build();
    options.Filters.Add(new AuthorizeFilter(jwtPolicy)); 
});

本文标签: