Skip to content

MSAL Token cache for ASP.Net Core protected API  #28858

Open

Description

Hi Team,

We have implemented the distributed token cache for our Asp.net Core Web API. The API won't be signing the users, the API will be authenticated and users with a JWT (Bearer token) can access the API endpoints. Below is the code snippet of our authentication and distributed token cache setup.

`

       services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddMicrosoftIdentityWebApi(configuration.GetSection(AuthConfigKeyName))
            .EnableTokenAcquisitionToCallDownstreamApi()
            .AddMicrosoftGraph(configuration.GetSection("GraphBeta"))
            .AddDistributedTokenCaches();

       // Setup Distributed Token Caches using cosmos DB
        services.Configure<MsalDistributedTokenCacheAdapterOptions>(options =>
        {
            // Optional: Disable the L1 cache in apps that don't use session affinity
            //                 by setting DisableL1Cache to 'true'.
            options.DisableL1Cache = true;

            options.Encrypt = true;

            options.SlidingExpiration = TimeSpan.FromDays(2); //TODO: fetch from config

            options.OnL2CacheFailure = (ex) =>
            {
                //TODO: Add logging here
                throw ex;
            };
        });

        // Azure Cosmos DB token cache
        services.AddCosmosCache((cacheOptions) =>
        {
            cacheOptions.ContainerName = configuration["TokenCache:CosmosCacheContainer"];
            cacheOptions.DatabaseName = configuration["TokenCache:CosmosCacheDatabase"];
            cacheOptions.ClientBuilder = new CosmosClientBuilder(configuration["TokenCache:CosmosConnectionString"]); //TODO: check if we can use Managed Identity
            cacheOptions.CreateIfNotExists = true;
        });
       
        services.Configure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options =>
        {
            options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
            {
                ValidateAudience = true,
                ValidateIssuer = false,
                ValidateLifetime = true,
                ValidAudience = configuration[$"{AuthConfigKeyName}:ClientId"]
            };
        });

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

We are able to save the token cache successfully when we make a call from the client to an endpoint that has the implementation of generating an access token e..g to call Graph or any other downstream API. But in the cases, when the client calls the API endpoint where we don't explicitly generate any access token, the token cache doesn't get saved.

I wanted to clarify whether the token cache will not get saved if we are authorizing the API endpoint with a bearer token and not generating any access token.

And how can we control the token cache id value, e.g. if we want it to be in this format like {{userLocalAccountId.tenantId}}?

Currently the id that it's storing in the token cache (in this cache cosmos DB. seems like an encrypted formated.). Screenshot below:
image

But we want it in the below format:

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions