admin管理员组

文章数量:1122832

So far, we've been using Azure's built-in Easy Auth to provide authentication for our Azure-deployed webapp but have decided to implement our own AuthN because we need more flexibility.

So I added the following configuration to Program.cs:

string stsDiscoveryEndpoint = ".0/.well-known/openid-configuration";
ConfigurationManager<OpenIdConnectConfiguration> configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>(
    stsDiscoveryEndpoint, new OpenIdConnectConfigurationRetriever());
OpenIdConnectConfiguration openIdConfig = configurationManager.GetConfigurationAsync().Result; //Please ignore .Result
builder.Services.AddAuthentication()
    .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, opts =>
    {
        opts.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuers = new[]
            { 
                "Issuer1",
                "Issuer2"
            },
            ValidateIssuerSigningKey = true,
            IssuerSigningKeys = openIdConfig.SigningKeys,
            //TryAllIssuerSigningKeys = true,
            ValidateLifetime = true,
            ValidAudiences = new[]
            {
                "Audience1",
                "Audience2"
            },
        };
    });

With Easy Auth if the AuthN failed, control wouldn't reach my AuthZ filter implementation. With these settings control reaches my AuthZ filter irrespective of whether the JWT verification failed or succeeded.

Question 1: How do I find out if the AuthN failed?

Also, with Easy Auth I could pull the identity of the caller using:

string? userId = authorizationFilterContext.HttpContext.User.Identity?.Name;

in my AuthZ filter, but this doesn't work with JwtBearer middleware.

Question 2: How do I do the equivalent with the JwtBearer middleware?

So far, we've been using Azure's built-in Easy Auth to provide authentication for our Azure-deployed webapp but have decided to implement our own AuthN because we need more flexibility.

So I added the following configuration to Program.cs:

string stsDiscoveryEndpoint = "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration";
ConfigurationManager<OpenIdConnectConfiguration> configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>(
    stsDiscoveryEndpoint, new OpenIdConnectConfigurationRetriever());
OpenIdConnectConfiguration openIdConfig = configurationManager.GetConfigurationAsync().Result; //Please ignore .Result
builder.Services.AddAuthentication()
    .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, opts =>
    {
        opts.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuers = new[]
            { 
                "Issuer1",
                "Issuer2"
            },
            ValidateIssuerSigningKey = true,
            IssuerSigningKeys = openIdConfig.SigningKeys,
            //TryAllIssuerSigningKeys = true,
            ValidateLifetime = true,
            ValidAudiences = new[]
            {
                "Audience1",
                "Audience2"
            },
        };
    });

With Easy Auth if the AuthN failed, control wouldn't reach my AuthZ filter implementation. With these settings control reaches my AuthZ filter irrespective of whether the JWT verification failed or succeeded.

Question 1: How do I find out if the AuthN failed?

Also, with Easy Auth I could pull the identity of the caller using:

string? userId = authorizationFilterContext.HttpContext.User.Identity?.Name;

in my AuthZ filter, but this doesn't work with JwtBearer middleware.

Question 2: How do I do the equivalent with the JwtBearer middleware?

Share Improve this question asked Nov 21, 2024 at 9:15 markvgtimarkvgti 4,6097 gold badges41 silver badges69 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Let me address your two questions:

To check if auth failed, look at the User object in your filter:

if (!context.HttpContext.User.Identity?.IsAuthenticated ?? false)
{
    // Auth failed
}

For getting the user ID with JWT, you'll need to grab it from the claims. The exact claim depends on your token setup, but typically:

string? userId = context.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
// or
string? userId = context.HttpContext.User.FindFirstValue("preferred_username");

Don't forget to add:

csharpCopyusing System.Security.Claims;

Hope this helps! Let me know if you need anything else.

本文标签: